repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
maierbn/opendihu
|
core/src/specialized_solver/solid_mechanics/hyperelasticity/01_material_computations.h
|
<filename>core/src/specialized_solver/solid_mechanics/hyperelasticity/01_material_computations.h
#pragma once
#include <Python.h> // has to be the first included header
#include "specialized_solver/solid_mechanics/hyperelasticity/expression_helper.h"
#include "specialized_solver/solid_mechanics/hyperelasticity/00_initialize.h"
namespace SpatialDiscretization
{
/** This class contains all formulas for computation of physical quantities.
*/
template<typename Term = Equation::SolidMechanics::MooneyRivlinIncompressible3D, bool withLargeOutput=true, typename MeshType = Mesh::StructuredDeformableOfDimension<3>, int nDisplacementComponents = 3>
class HyperelasticityMaterialComputations :
public HyperelasticityInitialize<Term,withLargeOutput,MeshType,nDisplacementComponents>
{
public:
typedef FunctionSpace::FunctionSpace<MeshType, BasisFunction::LagrangeOfOrder<2>> DisplacementsFunctionSpace;
typedef FunctionSpace::FunctionSpace<MeshType, BasisFunction::LagrangeOfOrder<1>> PressureFunctionSpace;
typedef FunctionSpace::FunctionSpace<Mesh::StructuredDeformableOfDimension<1>, BasisFunction::LagrangeOfOrder<1>> FiberFunctionSpace;
typedef DisplacementsFunctionSpace FunctionSpace;
typedef Data::QuasiStaticHyperelasticity<PressureFunctionSpace,DisplacementsFunctionSpace,Term,withLargeOutput,Term> Data;
typedef ::Data::QuasiStaticHyperelasticityPressureOutput<PressureFunctionSpace> PressureDataCopy;
typedef FieldVariable::FieldVariable<DisplacementsFunctionSpace,3> DisplacementsFieldVariableType;
typedef FieldVariable::FieldVariable<PressureFunctionSpace,1> PressureFieldVariableType;
typedef FieldVariable::FieldVariable<DisplacementsFunctionSpace,6> StressFieldVariableType;
typedef PartitionedPetscVecForHyperelasticity<DisplacementsFunctionSpace,PressureFunctionSpace,Term,nDisplacementComponents> VecHyperelasticity;
typedef PartitionedPetscMatForHyperelasticity<DisplacementsFunctionSpace,PressureFunctionSpace,Term,nDisplacementComponents> MatHyperelasticity;
//! constructor
HyperelasticityMaterialComputations(DihuContext context, std::string settingsKey = "HyperelasticitySolver");
//! not relevant, as it does nothing. Contains a lot of commented out debugging code that is helpful to debug the analytic jacobian matrix
template<typename double_v_t>
void materialTesting(const double_v_t pressure, //< [in] pressure value p
const Tensor2<3,double_v_t> &rightCauchyGreen, //< [in] C
const Tensor2<3,double_v_t> &inverseRightCauchyGreen, //< [in] C^{-1}
const std::array<double_v_t,5> reducedInvariants, //< [in] the reduced invariants Ibar_1, Ibar_2
const double_v_t deformationGradientDeterminant, //< [in] J = det(F)
VecD<3,double_v_t> fiberDirection, //< [in] a0, direction of fibers
Tensor2<3,double_v_t> &fictitiousPK2Stress, //< [in] Sbar, the fictitious 2nd Piola-Kirchhoff stress tensor
Tensor2<3,double_v_t> &pk2StressIsochoric //< [in] S_iso, the isochoric part of the 2nd Piola-Kirchhoff stress tensor
);
//! compute δWint from given displacements, this is a wrapper to materialComputeInternalVirtualWork
bool materialComputeInternalVirtualWork(
std::shared_ptr<VecHyperelasticity> displacements,
std::shared_ptr<VecHyperelasticity> internalVirtualWork
);
//! solve the dynamic hyperelastic problem, using a load stepping
//! output internalVirtualWork, externalVirtualWorkDead and accelerationTerm which is the acceleration contribution to δW
void solveDynamicProblem(std::shared_ptr<VecHyperelasticity> displacementsVelocitiesPressure, bool isFirstTimeStep,
Vec internalVirtualWork, Vec &externalVirtualWorkDead, Vec accelerationTerm, bool withOutputWritersEnabled = true);
//! compute u from the equation ∂W_int - externalVirtualWork = 0 and J = 1, the result will be in displacements,
//! the previous value in displacements will be used as initial guess (call zeroEntries() of displacements beforehand, if no initial guess should be provided)
void solveForDisplacements(
std::shared_ptr<VecHyperelasticity> externalVirtualWork,
std::shared_ptr<VecHyperelasticity> displacements
);
//! compute the resulting forces and moments at the 2- (bottom) and 2+ (top) surfaces of the volume
//! @param elements <element_no, isTop> a list of elements that are at bottom and top of the volume and on which the integration over forces and moments is performed, !isTop means bottom element
void computeBearingForceAndMoment(const std::vector<std::tuple<element_no_t,bool>> &elements,
Vec3 &bearingForceBottom, Vec3 &bearingMomentBottom, Vec3 &bearingForceTop, Vec3 &bearingMomentTop);
protected:
typedef HyperelasticityInitialize<Term,withLargeOutput,MeshType,nDisplacementComponents> Parent;
//! compute δW_int, input is in this->data_.displacements() and this->data_.pressure(), output is in solverVariableResidual_
//! @param communicateGhosts if startGhostManipulation() and finishGhostManipulation() will be called on combinedVecResidual_ inside this method, if set to false, you have to do it manually before and after this method
//! @return true if computation was successful (i.e. no negative jacobian)
bool materialComputeInternalVirtualWork(bool communicateGhosts=true);
//! compute the nonlinear function F(x), x=solverVariableSolution_, F=solverVariableResidual_
//! solverVariableResidual_[0-2] contains δW_int - δW_ext, solverVariableResidual_[3] contains int_Ω (J-1)*Ψ dV
//! @param loadFactor: a factor with which the rhs is scaled. This is equivalent to set the body force and traction (neumann bc) to this fraction
//! @return true if computation was successful (i.e. no negative jacobian)
bool materialComputeResidual(double loadFactor = 1.0);
//! compute δW_ext,dead = int_Ω B^L * phi^L * phi^M * δu^M dx + int_∂Ω T^L * phi^L * phi^M * δu^M dS
void materialComputeExternalVirtualWorkDead();
//! add the acceleration term that is needed for the dynamic problem to δW_int - δW_ext,dead, and secondly, add the velocity/displacement equation 1/dt (u^(n+1) - u^(n)) - v^(n+1) - v^n = 0
//! @param communicateGhosts if startGhostManipulation() and finishGhostManipulation() will be called on combinedVecResidual_ inside this method, if set to false, you have to do it manually before and after this method
void materialAddAccelerationTermAndVelocityEquation(bool communicateGhosts=true);
//! compute the jacobian of the Newton scheme
//! @return true if computation was successful (i.e. no negative jacobian)
bool materialComputeJacobian();
//! compute the deformation gradient, F inside the current element at position xi, the value of F is still with respect to the reference configuration,
//! the formula is F_ij = x_i,j = δ_ij + u_i,j
template<typename double_v_t>
Tensor2<3,double_v_t> computeDeformationGradient(const std::array<VecD<3,double_v_t>,DisplacementsFunctionSpace::nDofsPerElement()> &displacements,
const Tensor2<3,double_v_t> &inverseJacobianMaterial,
const std::array<double,3> xi);
//! compute the time velocity of the deformation gradient, Fdot inside the current element at position xi, the value of F is still with respect to the reference configuration,
//! the formula is Fdot_ij = d/dt x_i,j = v_i,j
template<typename double_v_t>
Tensor2<3,double_v_t> computeDeformationGradientTimeDerivative(const std::array<VecD<3,double_v_t>,DisplacementsFunctionSpace::nDofsPerElement()> &velocities,
const Tensor2<3,double_v_t> &inverseJacobianMaterial,
const std::array<double,3> xi);
//! compute the right Cauchy Green tensor, C = F^T*F. This is simply a matrix matrix multiplication
template<typename double_v_t>
Tensor2<3,double_v_t> computeRightCauchyGreenTensor(const Tensor2<3,double_v_t> &deformationGradient);
//! compute the invariants, [I1,I2,I3,I4,I5] where I1 = tr(C), I2 = 1/2 * (tr(C)^2 - tr(C^2)), I3 = det(C), I4 = a0•C a0, I5 = a0•C^2 a0
template<typename double_v_t>
std::array<double_v_t,5> computeInvariants(const Tensor2<3,double_v_t> &rightCauchyGreen, const double_v_t rightCauchyGreenDeterminant,
const VecD<3,double_v_t> fiberDirection);
//! compute the reduced invariants, [Ibar1, Ibar2]
template<typename double_v_t>
std::array<double_v_t,5> computeReducedInvariants(const std::array<double_v_t,5> invariants, const double_v_t deformationGradientDeterminant);
//! compute the 2nd Piola-Kirchhoff pressure, S
template<typename double_v_t>
Tensor2<3,double_v_t>
computePK2Stress(double_v_t &pressure, //< [in/out] pressure value p
const Tensor2<3,double_v_t> &rightCauchyGreen, //< [in] C
const Tensor2<3,double_v_t> &inverseRightCauchyGreen, //< [in] C^{-1}
const std::array<double_v_t,5> invariants, //< [in] the strain invariants I_1, ..., I_5
const std::array<double_v_t,5> reducedInvariants, //< [in] the reduced invariants Ibar_1, ..., Ibar_5
const double_v_t deformationGradientDeterminant, //< [in] J = det(F)
VecD<3,double_v_t> fiberDirection, //< [in] a0, direction of fibers
dof_no_v_t elementNoLocalv, //< [in] the current element nos (simd vector) with unused entries set to -1, needed only as mask which entries to discard
Tensor2<3,double_v_t> &fictitiousPK2Stress, //< [out] Sbar, the fictitious 2nd Piola-Kirchhoff stress tensor
Tensor2<3,double_v_t> &pk2StressIsochoric //< [out] S_iso, the isochoric part of the 2nd Piola-Kirchhoff stress tensor
);
//! compute the PK2 stress and the deformation gradient at every node and set value in data, for output
void computePK2StressField();
//! compute the material elasticity tensor
template<typename double_v_t>
void computeElasticityTensor(const Tensor2<3,double_v_t> &rightCauchyGreen,
const Tensor2<3,double_v_t> &inverseRightCauchyGreen, double_v_t deformationGradientDeterminant, double_v_t pressure,
std::array<double_v_t,5> invariants, std::array<double_v_t,5> reducedInvariants, const Tensor2<3,double_v_t> &fictitiousPK2Stress,
const Tensor2<3,double_v_t> &pk2StressIsochoric, VecD<3,double_v_t> fiberDirection,
Tensor4<3,double_v_t> &fictitiousElasticityTensor, Tensor4<3,double_v_t> &elasticityTensorIso,
Tensor4<3,double_v_t> &elasticityTensor);
//! compute P : Sbar
template<typename double_v_t>
Tensor2<3,double_v_t> computePSbar(const Tensor2<3,double_v_t> &fictitiousPK2Stress, const Tensor2<3,double_v_t> &rightCauchyGreen);
//! compute the value of Sbar : C
template<typename double_v_t>
double computeSbarC(const Tensor2<3,double_v_t> &Sbar, const Tensor2<3,double_v_t> &C);
//! use Petsc to solve the nonlinear equation using the SNES solver
virtual void nonlinearSolve() = 0;
//! do some steps after nonlinearSolve(): close log file, copy the solution values back to this->data_.displacements() and this->data.pressure(),
//! compute the PK2 stress at every node, update the geometry field by the new displacements, dump files containing rhs and system matrix
virtual void postprocessSolution() = 0;
// use variables from the base class, this avoids writing "this->" in front of those members
using Parent::displacementsFunctionSpace_; //< the function space with quadratic Lagrange basis functions, used for discretization of displacements
using Parent::pressureFunctionSpace_; //< the function space with linear Lagrange basis functions, used for discretization of pressure
using Parent::solverVariableResidual_; //< PETSc Vec to store the residual, equal to combinedVecResidual_->valuesGlobal()
using Parent::solverVariableSolution_; //< PETSc Vec to store the solution, equal to combinedVecSolution_->valuesGlobal()
using Parent::combinedVecResidual_; //< the Vec for the residual and result of the nonlinear function
using Parent::combinedVecSolution_; //< the Vec for the solution, combined means that ux,uy,uz and p components are combined in one vector
using Parent::combinedVecExternalVirtualWorkDead_; //< the Vec for the external virtual work part that does not change with u, δW_ext,dead
using Parent::combinedMatrixJacobian_; //< single jacobian matrix
using Parent::combinedMatrixAdditionalNumericJacobian_; //< only used when both analytic and numeric jacobians are computed, then this holds the numeric jacobian
using Parent::externalVirtualWorkDead_; //< the external virtual work resulting from the traction, this is a dead load, i.e. it does not change during deformation
using Parent::getString; //< function to get a string representation of the values for debugging output
using Parent::setUVP; //< function to copy the values of the vector x which contains (u and p) or (u,v and p) values to this->data_.displacements(), this->data_.velocities() and this->data_.pressure();
};
} // namespace
#include "specialized_solver/solid_mechanics/hyperelasticity/01_material_computations.tpp"
#include "specialized_solver/solid_mechanics/hyperelasticity/01_material_computations_auxiliary.tpp"
#include "specialized_solver/solid_mechanics/hyperelasticity/01_material_computations_elasticity_tensor.tpp"
#include "specialized_solver/solid_mechanics/hyperelasticity/01_material_computations_stress.tpp"
#include "specialized_solver/solid_mechanics/hyperelasticity/01_material_computations_wrappers.tpp"
#include "specialized_solver/solid_mechanics/hyperelasticity/01_material_testing.tpp"
|
BroadleafCommerce/ReactStarter
|
api/src/main/java/com/mycompany/api/endpoint/theme/ThemeEndpoint.java
|
<reponame>BroadleafCommerce/ReactStarter
/*
* #%L
* React API Starter
* %%
* Copyright (C) 2009 - 2017 Broadleaf Commerce
* %%
* Broadleaf Commerce React Starter
*
* Written in 2017 by Broadleaf Commerce <EMAIL>
*
* To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
* You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*
* Please Note - The scope of CC0 Public Domain Dedication extends to Broadleaf Commerce React Starter demo application alone. Linked libraries (including all Broadleaf Commerce Framework libraries) are subject to their respective licenses, including the requirements and restrictions specified therein.
* #L%
*/
package com.mycompany.api.endpoint.theme;
import org.broadleafcommerce.common.web.resource.BroadleafDefaultResourceResolverChain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import org.springframework.web.servlet.resource.ResourceResolverChain;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/**
* @author <NAME> ncrum
*/
@RestController("blThemeEndpoint")
@RequestMapping("/theme")
public class ThemeEndpoint {
@Autowired
@Qualifier("blCssResources")
protected ResourceHttpRequestHandler cssResourceHandler;
@RequestMapping(value = "/css/{fileName:.+}")
public Resource getCssThemeFile(HttpServletRequest request,
@PathVariable("fileName") String fileName,
@RequestParam(value = "filePath", defaultValue = "") String filePath) {
ResourceResolverChain resolverChain = new BroadleafDefaultResourceResolverChain(
cssResourceHandler.getResourceResolvers());
List<Resource> locations = cssResourceHandler.getLocations();
return resolverChain.resolveResource(request, Paths.get(filePath, fileName).toString(), locations);
}
}
|
SunBeau/qlibc
|
tests/test_qhasharr_darkdh.c
|
/******************************************************************************
* qLibc
*
* Copyright (c) 2010-2015 <NAME>.
* All rights reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT OWNER OR 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.
*****************************************************************************/
/* This code is written and updated by following people and released under
* the same license as above qLibc license.
* Copyright (c) 2015 <NAME> - https://github.com/darkdh
*****************************************************************************/
#include "qunit.h"
#include "qlibc.h"
#include <errno.h>
QUNIT_START("Test qhasharr.c by darkdh");
qhasharr_t *tbl;
char *memory;
TEST("qhasharr()")
{
int memsize = qhasharr_calculate_memsize(5);
memory = (char*) malloc(memsize * sizeof(char));
tbl = qhasharr(memory, memsize);
ASSERT_NOT_NULL(tbl);
int maxslots, usedslots;
tbl->size(tbl, &maxslots, &usedslots);
ASSERT(maxslots > 0);
ASSERT(usedslots == 0);
}
char *key[] = { "key1", "key2", "key3", "key4", "key5" };
char *value[] = { "data1", "data2", "data3", "data4", "data5" };
#define TARGET_NUM sizeof(key)/sizeof(char*)
int valuesize[TARGET_NUM];
int found[TARGET_NUM];
int i, j;
for (i = 0; i < TARGET_NUM; i++) {
valuesize[i] = strlen(value[i]);
found[i] = 0;
}
char *extra_key[] = { "extra1", "extra2", "extra3" };
char *extra_value[] = { "extra_data1", "extra_data2", "extra_data3" };
#define EXTRA_NUM sizeof(extra_key)/sizeof(char*)
int extra_valuesize[EXTRA_NUM];
for (i = 0; i < EXTRA_NUM; i++) {
extra_valuesize[i] = strlen(extra_value[i]);
}
TEST("put() to full")
{
size_t size;
for (i = 0; i < TARGET_NUM; i++) {
ASSERT_TRUE(tbl->put(tbl, key[i], value[i], valuesize[i]));
char *target_got = (char*) tbl->get(tbl, key[i], &size);
ASSERT_NOT_NULL(target_got);
ASSERT_EQUAL_MEM(target_got, value[i], valuesize[i]);
free(target_got);
}
ASSERT_EQUAL_INT(tbl->size(tbl, NULL, NULL), TARGET_NUM);
ASSERT_FALSE(
tbl->put(tbl, extra_key[0], extra_value[0], extra_valuesize[0]));
ASSERT_NULL(tbl->get(tbl, extra_key[0], &size));
ASSERT_EQUAL_INT(tbl->size(tbl, NULL, NULL), TARGET_NUM);
}
TEST("get() non-exist key")
{
size_t size;
char *target_got = (char*) tbl->get(tbl, extra_key[0], &size);
ASSERT_NULL(target_got);
}
TEST("remove() to empty")
{
for (i = 0; i < TARGET_NUM; i++) {
ASSERT_TRUE(tbl->remove(tbl, key[i]));
}
ASSERT_EQUAL_INT(tbl->size(tbl, NULL, NULL), 0);
ASSERT_FALSE(tbl->remove(tbl, key[0]));
ASSERT_EQUAL_INT(tbl->size(tbl, NULL, NULL), 0);
}
TEST("add() same key")
{
size_t size;
ASSERT_TRUE(tbl->put(tbl, key[0], value[0], valuesize[0]));
ASSERT_TRUE(tbl->put(tbl, key[0], value[1], valuesize[1]));
char *target_got = (char*) tbl->get(tbl, key[0], &size);
ASSERT_NOT_NULL(target_got);
ASSERT_EQUAL_MEM(target_got, value[1], valuesize[1]);
free(target_got);
ASSERT_TRUE(tbl->remove(tbl, key[0]));
}
TEST("getnext()")
{
size_t size;
for (i = 0; i < TARGET_NUM; i++) {
ASSERT_TRUE(tbl->put(tbl, key[i], value[i], valuesize[i]));
char *target_got = (char*) tbl->get(tbl, key[i], &size);
ASSERT_NOT_NULL(target_got);
ASSERT_EQUAL_MEM(target_got, value[i], valuesize[i]);
free(target_got);
}
ASSERT_EQUAL_INT(tbl->size(tbl, NULL, NULL), TARGET_NUM);
int idx = 0;
qhasharr_obj_t obj;
for (i = 0; i < TARGET_NUM; i++) {
ASSERT_TRUE(tbl->getnext(tbl, &obj, &idx));
for (j = 0; j < TARGET_NUM; j++) {
if (!memcmp(obj.data, value[j], valuesize[j]) && found[j] == 0)
found[j] = 1;
}
free(obj.name);
free(obj.data);
}
ASSERT_FALSE(tbl->getnext(tbl, &obj, &idx));
for (i = 0; i < TARGET_NUM; i++) {
ASSERT_EQUAL_INT(found[i], 1);
}
ASSERT_EQUAL_INT(tbl->size(tbl, NULL, NULL), TARGET_NUM);
}
// free table reference object.
tbl->free(tbl);
free(memory);
QUNIT_END();
|
fexter-svk/C90-Compiler-EIE2
|
src/c_compiler/ast/ast_dowhileloop.cpp
|
#include "ast_dowhileloop.hpp"
DoWhileLoop::DoWhileLoop(Expression* _conditions, Expression* _statement){
conditions = _conditions;
if (_statement){
statement = _statement;
}
}
void DoWhileLoop::add(Expression* _exp){
if (statement){
statement->add(_exp);
}
}
uint32_t DoWhileLoop::getSize(Context& context) const{
if (statement){
return statement->getSize(context) + conditions->getSize(context);
} else {
return conditions->getSize(context);
}
}
string DoWhileLoop::print(const bool& complete) const{
stringstream ss;
ss<<"<DoWhileLoop>"<<endl;
ss<<"<Scope>"<<endl;
if (statement){
ss<<statement->print(complete);
}
ss<<"</Scope>"<<endl;
ss<<"<Condition>"<<endl;
ss<<conditions->print(complete)<<endl;
ss<<"</Condition>"<<endl;
ss<<"</DoWhileLoop>"<<endl;
return ss.str();
}
void DoWhileLoop::setType(const string &_type){}
string DoWhileLoop::getType() const{
return "DoWhileLoop";
}
string DoWhileLoop::getVal() const{
return "";
}
void DoWhileLoop::codeGen(const string& destReg, Context& context){
//Create labels and scratch registers
context.incrementLoopCounter();
string L1 = string("$LOOP"+to_string(context.getLoopCounter()));
string L2 = string("$EXIT"+to_string(context.getLoopCounter()));
string reg1 = context.getFreeRegister("");
string scratch_id1 = context.makeLabel("scratch_dowhile");
context.makeBinding(scratch_id1, reg1,"scratch");
cout<<L1<<":"<<endl;
//Codegen the condition
if (statement){
statement->codeGen(destReg, context);
}
conditions->codeGen(reg1, context);
cout<<"\t"<<"bne "<<reg1<<",$0,"<<L1
<<"\t #Branching for loop"
<<endl;
cout<<"\t"<<"nop"<<endl;
cout<<L2<<":"<<endl;
context.releaseBinding(scratch_id1);
}
|
lingxuan630/fis-postprocessor-amd
|
test/expected/async/modE.js
|
define('ns:modE', function(require) {
return 5;
});
// globa async as sync
require(['ns:modA', 'ns:modB'], function(modA, modB) {
console.log('here');
});
|
kylin589/cross_border
|
renren-admin/src/main/java/io/renren/modules/sys/service/ConsumeService.java
|
package io.renren.modules.sys.service;
import com.baomidou.mybatisplus.service.IService;
import io.renren.common.utils.PageUtils;
import io.renren.modules.sys.entity.ConsumeEntity;
import java.math.BigDecimal;
import java.util.Map;
/**
* 消费记录
*
* @author wdh
* @email <EMAIL>
* @date 2018-12-17 17:36:01
*/
public interface ConsumeService extends IService<ConsumeEntity> {
PageUtils queryPage(Map<String, Object> params);
BigDecimal consumTotal(Long deptId);
}
|
Killian-G/doom-nukem
|
srcs/scene/editor/draw_sector.c
|
<filename>srcs/scene/editor/draw_sector.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* draw_sector.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kguibout <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/06/01 12:46:56 by kguibout #+# #+# */
/* Updated: 2020/06/09 22:38:05 by kguibout ### ########.fr */
/* */
/* ************************************************************************** */
#include "editor.h"
static void draw_triangle2(t_triangle *triangle, t_env *env)
{
t_vec2i pos0;
t_vec2i pos1;
t_vec2i pos2;
pos0 = grid_to_win(&triangle->vertex[0].v, env);
pos1 = grid_to_win(&triangle->vertex[1].v, env);
pos2 = grid_to_win(&triangle->vertex[2].v, env);
draw_line_clip((t_clipping_line){pos0, pos1, vec2i(0, 0),
vec2i(WIDTH, HEIGHT)}, 0x3dc5ff, env->main_window->surface);
draw_line_clip((t_clipping_line){pos1, pos2, vec2i(0, 0),
vec2i(WIDTH, HEIGHT)}, 0x3dc5ff, env->main_window->surface);
draw_line_clip((t_clipping_line){pos2, pos0, vec2i(0, 0),
vec2i(WIDTH, HEIGHT)}, 0x3dc5ff, env->main_window->surface);
}
static void draw_wall(t_wall *wall, t_env *env)
{
t_color color;
t_vec2i tmp;
color = 0xFFFFFF;
if (wall == env->editor.closest)
color = 0x00FF00;
else if (wall->neighbor != NULL)
color = 0xFF0000;
tmp = grid_to_win(&wall->v1->v.v, env);
draw_line_clip((t_clipping_line){tmp, grid_to_win(&wall->v2->v.v, env),
vec2i(0, 0), vec2i(WIDTH, HEIGHT)}, color, env->main_window->surface);
draw_elipse((SDL_Rect){tmp.x, tmp.y, 3, 3}, 0xFF0000,
env->main_window->surface);
}
static void draw_sector(t_sector *sector, t_env *env)
{
size_t i;
t_triangle *triangle;
size_t nb_triangle;
t_wall *walls;
size_t nb_wall;
i = 0;
triangle = sector->triangle_bottom.items;
nb_triangle = sector->triangle_bottom.total;
while (i < nb_triangle)
{
draw_triangle2(&triangle[i], env);
++i;
}
i = 0;
walls = sector->walls.items;
nb_wall = sector->walls.total;
while (i < nb_wall)
{
draw_wall(&walls[i], env);
++i;
}
}
void draw_sectors(t_env *env)
{
size_t i;
size_t nb_sector;
t_map *sectors;
sectors = env->current_map->sectors;
nb_sector = env->current_map->sectors->total;
i = 0;
while (i < nb_sector)
{
draw_sector(*(t_sector **)map_get_index(sectors, i), env);
i++;
}
}
|
pustian/pattern
|
96-facade/java/01/CameraImpl.java
|
public class CameraImpl implements Camera {
public void takePicture() {
System.out.println("--- take picture ---");
}
}
|
liuhpleon/RubyLCPractice
|
test/509_Fibonacci_Number_Test.rb
|
require 'test/unit'
require_relative '../leetcode/509_Fibonacci_Number'
class FibonacciNumberTest < Test::Unit::TestCase
def setup
@fib = FibonacciNumber.new
end
def test_solution
assert_equal @fib.fib(5), 5
end
end
|
gta-chaos-mod/plugin-sdk
|
plugin_III/game_III/meta/meta.CAntennas.h
|
/*
Plugin-SDK (Grand Theft Auto 3) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "PluginBase.h"
namespace plugin {
META_BEGIN(CAntennas::Init)
static int address;
static int global_address;
static const int id = 0x4F64D0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4F64D0, 0x4F6580, 0x4F6510>;
// total references count: 10en (2), 11en (2), steam (2)
using refs_t = RefList<0x48C23E,100,0,0x48BED0,1, 0x48C561,100,0,0x48C4B0,1, 0x48C32E,110,0,0x48BFC0,1, 0x48C661,110,0,0x48C5B0,1, 0x48C2BE,120,0,0x48BF50,1, 0x48C5F1,120,0,0x48C540,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CAntennas::Update)
static int address;
static int global_address;
static const int id = 0x4F6550;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4F6550, 0x4F6600, 0x4F6590>;
// total references count: 10en (1), 11en (1), steam (1)
using refs_t = RefList<0x48C918,100,0,0x48C850,1, 0x48CA18,110,0,0x48C950,1, 0x48C9A8,120,0,0x48C8E0,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CAntennas::Render)
static int address;
static int global_address;
static const int id = 0x4F6590;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4F6590, 0x4F6640, 0x4F65D0>;
// total references count: 10en (1), 11en (1), steam (1)
using refs_t = RefList<0x48E0AE,100,0,0x48E090,1, 0x48E16E,110,0,0x48E150,1, 0x48E0FE,120,0,0x48E0E0,1>;
using def_t = void();
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<>>;
META_END
META_BEGIN(CAntennas::RegisterOne)
static int address;
static int global_address;
static const int id = 0x4F66C0;
static const bool is_virtual = false;
static const int vtable_index = -1;
using mv_addresses_t = MvAddresses<0x4F66C0, 0x4F6770, 0x4F6700>;
// total references count: 10en (1), 11en (1), steam (1)
using refs_t = RefList<0x535BBB,100,0,0x535B40,1, 0x535DFB,110,0,0x535D80,1, 0x535D8B,120,0,0x535D10,1>;
using def_t = void(unsigned int, CVector, CVector, float);
static const int cb_priority = PRIORITY_BEFORE;
using calling_convention_t = CallingConventions::Cdecl;
using args_t = ArgPick<ArgTypes<unsigned int,CVector,CVector,float>, 0,1,2,3>;
META_END
}
|
deyani27/gatsby-cloud-poc
|
src/components/TopArticlesHome/TopArticlesHome.js
|
import React from "react"
import { Link } from "gatsby"
import "./TopArticles.scss"
function Article({ title, byline, category, imageUrl, articleUrl }) {
return (
<div className="top_articles__columns__column__inner">
<div
className="top_articles__columns__column__image"
style={{ backgroundImage: imageUrl ? `url("${imageUrl}")` : "" }}
/>
{category && <div className="article__category">{category}</div>}
{title && <div className="article__title">{title}</div>}
{byline && <div className="article__description">{byline}</div>}
{articleUrl && (
<div className="article__more">
<Link to={articleUrl} className="article__more__link">
Read More
</Link>
</div>
)}
</div>
)
}
export default function TopArticles(props) {
const { featuredArticle, articles, theme } = props
const getFormattedArticle = article => {
if (!article) return null
const imageObj =
article.components.contents &&
article.components.contents.find(content => content.thumbnailImage)
const imageHeroObj =
article.components.contents &&
article.components.contents.find(content => content.heroImage)
const category = article.categories.nodes.find(
category => category.name.toLowerCase() !== "featured category"
)
const bylineObj =
article.components.contents &&
article.components.contents.find(content => content.byline)
const formattedArticle = {
imageUrl:
(imageObj && imageObj.thumbnailImage.sourceUrl) ||
(imageHeroObj && imageHeroObj.heroImage.sourceUrl),
category: category ? category.name : "",
title: article.title,
byline: bylineObj && bylineObj.byline,
articleUrl: article.uri,
}
return formattedArticle
}
const getFeaturedArticle = () => {
let fArticle = null
if (featuredArticle) {
fArticle = getFormattedArticle(featuredArticle)
} else {
const firstArticle = articles.column1[0]
? articles.column1[0].article
: null
fArticle = getFormattedArticle(firstArticle)
}
return fArticle
}
const getArticles = articles => {
const newArticles = []
articles.map(articleObj => {
const { article } = articleObj
const newArticle = getFormattedArticle(article)
newArticles.push(newArticle)
})
return newArticles
}
const featuredArticleFormatted = getFeaturedArticle()
const formattedARticles = getArticles(articles)
return (
<div className="top-articles-container">
<div className={`top-articles container ${theme}`}>
<div className="featured-article">
{featuredArticleFormatted && (
<div className="featured-article__inner">
{featuredArticleFormatted.imageUrl && (
<div
className="featured-article__image"
style={{
backgroundImage: `url("${featuredArticleFormatted.imageUrl}")`,
}}
/>
)}
{featuredArticleFormatted.category && (
<div className="article__category">
{featuredArticleFormatted.category}
</div>
)}
{featuredArticleFormatted.title && (
<div className="article__title">
{featuredArticleFormatted.title}
</div>
)}
{featuredArticleFormatted.byline && (
<div className="article__description">
{featuredArticleFormatted.byline}
</div>
)}
{featuredArticleFormatted.articleUrl && (
<div className="article__more">
<Link
to={featuredArticleFormatted.articleUrl}
className="article__more__link"
>
Read more
</Link>
</div>
)}
</div>
)}
</div>
<div className="top_articles__columns">
{formattedARticles.map((article, index) => (
<Article key={index} {...article} />
))}
{formattedARticles.length > 1 && (
<div className="top_articles__columns__column__divider first" />
)}
{formattedARticles.length > 2 && (
<div className="top_articles__columns__column__divider second" />
)}
{/* <div className="top_articles__columns__column">
{articles.column1 && articles.column1.length > 0 && (
<div>
{getArticles(articles.column1).map((article, index) => (
<Article key={index} {...article} />
))}
<div className="top_articles__columns__column__divider" />
</div>
)}
</div>
<div className="top_articles__columns__column">
{articles.column2 && articles.column2.length > 0 && (
<div>
{getArticles(articles.column2).map((article, index) => (
<Article key={index} {...article} />
))}
<div className="top_articles__columns__column__divider" />
</div>
)}
</div>
<div className="top_articles__columns__column">
{articles.column3 && articles.column3.length > 0 && (
<div>
{getArticles(articles.column3).map((article, index) => (
<Article key={index} {...article} />
))}
<div className="top_articles__columns__column__divider" />
</div>
)}
</div> */}
</div>
</div>
</div>
)
}
|
prabal999/Design-Patterns-
|
src/main/java/com/prabalhub/design/patterns/structural/decorator/Sandwich.java
|
package com.prabalhub.design.patterns.structural.decorator;
/**
* Sandwich component.
* @author <NAME>
*
*/
public interface Sandwich {
String make();
int getCost();
}
|
BoomApps-LLC/SteemApp
|
steemj-core/src/main/java/eu/bittrade/libs/steemj/base/models/operations/virtual/FillOrderOperation.java
|
<reponame>BoomApps-LLC/SteemApp
package eu.bittrade.libs.steemj.base.models.operations.virtual;
import java.util.Map;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonProperty;
import eu.bittrade.libs.steemj.base.models.AccountName;
import eu.bittrade.libs.steemj.base.models.Asset;
import eu.bittrade.libs.steemj.base.models.operations.Operation;
import eu.bittrade.libs.steemj.enums.PrivateKeyType;
import eu.bittrade.libs.steemj.enums.ValidationType;
import eu.bittrade.libs.steemj.exceptions.SteemInvalidTransactionException;
import eu.bittrade.libs.steemj.interfaces.SignatureObject;
/**
* This class represents a Steem "fill_order_operation" object.
*
* This operation type occurs if a order has been closed completely or if a part
* of the order has been closed.
*
* @author <a href="http://steemit.com/@dez1337">dez1337</a>
*/
public class FillOrderOperation extends Operation {
@JsonProperty("current_owner")
private AccountName currentOwner;
@JsonProperty("current_orderid")
// Original type is uint32_t here so we have to use long.
private int currentOrderId;
@JsonProperty("current_pays")
private Asset currentPays;
@JsonProperty("open_owner")
private AccountName openOwner;
@JsonProperty("open_orderid")
// Original type is uint32_t here so we have to use long.
private long openOrderId;
@JsonProperty("open_pays")
private Asset openPays;
/**
* This operation is a virtual one and can only be created by the blockchain
* itself. Due to that, this constructor is private.
*/
private FillOrderOperation() {
super(true);
}
/**
* @return The current owner.
*/
public AccountName getCurrentOwner() {
return currentOwner;
}
/**
* @return The current order id.
*/
public int getCurrentOrderId() {
return currentOrderId;
}
/**
* @return The current pays.
*/
public Asset getCurrentPays() {
return currentPays;
}
/**
* @return The open owner.
*/
public AccountName getOpenOwner() {
return openOwner;
}
/**
* @return The open order id.
*/
public long getOpenOrderId() {
return openOrderId;
}
/**
* @return The open pays.
*/
public Asset getOpenPays() {
return openPays;
}
@Override
public byte[] toByteArray() throws SteemInvalidTransactionException {
// The byte representation is not needed for virtual operations as we
// can't broadcast them.
return new byte[0];
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public Map<SignatureObject, PrivateKeyType> getRequiredAuthorities(
Map<SignatureObject, PrivateKeyType> requiredAuthoritiesBase) {
// A virtual operation can't be created by the user, therefore it also
// does not require any authority.
return null;
}
@Override
public void validate(ValidationType validationType) {
// There is no need to validate virtual operations.
}
}
|
dexterdarwich/lightbend-academy
|
LAC-Sharding-v1/exercises/java/src/test/java/com/reactivebbq/orders/SQLOrderRepositoryTest.java
|
<gh_stars>0
package com.reactivebbq.orders;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SQLOrderRepositoryTest extends OrderRepositoryTest {
private Executor executor;
@Override
public OrderRepository createOrderRepository() {
executor = Executors.newFixedThreadPool(100);
return new SQLOrderRepository(executor);
}
@Override
public void destroyOrderRepository() {
((ExecutorService) executor).shutdown();
}
}
|
Charismara/ImmersivePortalsModForForge
|
src/main/java/com/qouteall/immersive_portals/ducks/IEWorldChunk.java
|
<filename>src/main/java/com/qouteall/immersive_portals/ducks/IEWorldChunk.java<gh_stars>1-10
package com.qouteall.immersive_portals.ducks;
import net.minecraft.entity.Entity;
import net.minecraft.util.ClassInheritanceMultiMap;
public interface IEWorldChunk {
ClassInheritanceMultiMap<Entity>[] getEntitySections();
}
|
ChanhyoLee/WICWIU
|
Documentation/WICWIU API 설명서/class_container.js
|
<reponame>ChanhyoLee/WICWIU<filename>Documentation/WICWIU API 설명서/class_container.js
var class_container =
[
[ "Container", "class_container.html#ab2bf85021abd93687431712eec397bd6", null ],
[ "~Container", "class_container.html#aa842cc3579205a9431569dea02b0976e", null ],
[ "GetElement", "class_container.html#a127e7b9fa3de03c7f7f866190fd1c585", null ],
[ "GetLast", "class_container.html#ac4fb1b6458674b9876afb4b1fa18c4a9", null ],
[ "GetRawData", "class_container.html#adbb3e154598ae672e37283a1fb292ba2", null ],
[ "GetSize", "class_container.html#ac0cc8e4e6056e832c4874635ac871c40", null ],
[ "operator[]", "class_container.html#a884d3c64b1d6556018585569d8f00994", null ],
[ "Pop", "class_container.html#ad7b9f7d5eb283748a0d31389b487e396", null ],
[ "Pop", "class_container.html#a15c8f4962022d9ad82ffb6c721b672f9", null ],
[ "Push", "class_container.html#ac875fe061a6d4c1137def5251eaef95a", null ],
[ "Reverse", "class_container.html#ab86a61645d5fff30cff8062e7988b770", null ],
[ "SetElement", "class_container.html#a4f113e1ecebcf3a21273aefd26d7bbb5", null ],
[ "m_aElement", "class_container.html#a31fedbac1a575c035ab8066b6fc7d0ea", null ],
[ "m_size", "class_container.html#ab956079cdfb7c75a58a6de1fe2fd170b", null ]
];
|
kzborisov/SoftUni
|
3. Python Advanced (September 2021)/3.2 Python OOP (October 2021)/05. Inheritance/06_stack_of_strings/main.py
|
class Stack:
def __init__(self):
self.data = []
def push(self, element):
self.data.append(element)
def pop(self):
return self.data.pop()
def top(self):
return self.data[-1]
def is_empty(self):
return False if self.data else True
def __str__(self):
msg = f"[{', '.join(sorted(self.data, reverse=True))}]"
return msg
|
JoeyBling/base-boot
|
base-common/src/main/java/com/tynet/saas/common/util/StringUtils.java
|
<filename>base-common/src/main/java/com/tynet/saas/common/util/StringUtils.java
package com.tynet.saas.common.util;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Date;
/**
* 字符串工具类
*
* @author Created by 思伟 on 2021/2/22
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* 将对象转换为String
*
* @param value Object
* @return String
*/
public static String toString(Object value) {
String strValue;
if (value == null) {
strValue = null;
} else if (value instanceof String) {
strValue = (String) value;
} else if (value instanceof BigDecimal) {
strValue = ((BigDecimal) value).toString();
} else if (value instanceof Integer) {
strValue = ((Integer) value).toString();
} else if (value instanceof Long) {
strValue = ((Long) value).toString();
} else if (value instanceof Float) {
strValue = ((Float) value).toString();
} else if (value instanceof Double) {
strValue = ((Double) value).toString();
} else if (value instanceof Boolean) {
strValue = ((Boolean) value).toString();
} else if (value instanceof Date) {
strValue = DateUtils.format((Date) value);
} else if (value instanceof LocalDateTime) {
strValue = DateUtils.format((LocalDateTime) value);
} else if (value instanceof LocalDate) {
strValue = DateUtils.format((LocalDate) value);
} else if (value instanceof LocalTime) {
strValue = DateUtils.format((LocalTime) value);
} else if (value.getClass().isArray()) {
// 基本数据类型处理...
if (value instanceof char[]) {
strValue = Arrays.toString((char[]) value);
} else if (value instanceof long[]) {
strValue = Arrays.toString((long[]) value);
} else if (value instanceof int[]) {
strValue = Arrays.toString((int[]) value);
} else if (value instanceof short[]) {
strValue = Arrays.toString((short[]) value);
} else if (value instanceof byte[]) {
strValue = Arrays.toString((byte[]) value);
} else if (value instanceof boolean[]) {
strValue = Arrays.toString((boolean[]) value);
} else if (value instanceof float[]) {
strValue = Arrays.toString((float[]) value);
} else if (value instanceof double[]) {
strValue = Arrays.toString((double[]) value);
} else {
// 对象数组
strValue = Arrays.deepToString((Object[]) value);
}
} else {
strValue = value.toString();
}
return strValue;
}
/**
* message格式化,用{}替代任何的对象
* 参考:{@link cn.hutool.core.util.StrUtil#format(CharSequence, Object...)}
*
* @param message 待格式化字符串
* @param objs 入参
* @return 格式化后的字符串
*/
public static String format(String message, Object... objs) {
for (Object obj : objs) {
message = formatByStr(message, obj, "{}");
}
return message;
}
/**
* 使用指定的替换符进行格式化字符串
*
* @param str 待格式化字符串
* @param obj 入参
* @param formatStr 格式化替换字符串(默认:{})
* @return 格式化后的字符串
*/
public static String formatByStr(String str, Object obj, String formatStr) {
formatStr = defaultString(formatStr, "{}");
// 获取开始下标
int i = str.indexOf(formatStr);
if (i != -1) {
return str.substring(0, i).concat(stripToEmpty(toString(obj)))
.concat(str.substring(i + formatStr.length()));
} else {
// 跳过替换
return str;
}
}
/**
* 转换为Integer类型
*
* @param cs 待转换字符串
* @return Integer
*/
public static Integer getIntegerValue(CharSequence cs) {
// Integer.getInteger
return isNumeric(cs) ? Integer.parseInt(cs.toString()) : null;
}
/**
* 转换为Integer类型,当输入的字符串不是一个整型类型时返回默认值
*
* @param defaultInt 要返回的默认值
* if the input is {@code null}, may be null
* @see #getIntegerValue(CharSequence)
*/
public static Integer getIntegerValue(CharSequence cs, Integer defaultInt) {
final Integer intVal = getIntegerValue(cs);
return intVal == null ? defaultInt : intVal;
}
/**
* just test
*/
public static void main(String[] args) {
System.out.println(format("{}-{}_JoeyBling_Blog:{}",
new Date(), "周思伟", "https://zhousiwei.gitee.io/ibooks/"));
System.out.println(toString(new Date()));
System.out.println(toString(DateUtils.now()));
System.out.println(toString(DateUtils.nowDate()));
System.out.println(toString(DateUtils.nowTime()));
System.out.println(toString("just_test".toCharArray()));
}
}
|
xu456as/TankWeb
|
mock/article.js
|
import { parse } from 'url';
export const getArticles = [
{
id: 0,
title: "AI Tank游戏规则",
author: "fangheng",
content: [
'1.地图大小为N*N,中心旋转对称,队伍的tank出生在地图的两个对边角上。',
'2.地图上有以下元素',
'2.1.障碍物,不可被摧毁。地图的最外围会被一圈障碍物覆盖。',
' 2.2.战旗,始终固定在地图中心出现。可被经过的tank获得。战旗消失后会在固定回合后重新出现。',
' 2.3.森林,处于森林中的tank不会被敌方发现。处于森里中的炮弹对双方均不可见。',
'3.每个玩家M个坦克,M为地图给出的参数。',
'4.每辆tank在地图上最多只能存在一发炮弹。必须在之前发射的炮弹消失掉之后才能进行开火的操作。',
'5.tank可以进行如下操作:左转,右转,掉头,前进,原地不动,开火。开火方向可以和坦克的行进方向不一样。开火方向限制在上下左右四个方向(游戏中所有的方向均以地图为基准,即向左转向会转到地图向左的方向,而不是tank自己的左方。)。每个回合只能执行一个操作。前进只能走完tank速度的全程。',
'6.tank速度为x,炮弹速度为y,其中x<y。',
'7.炮弹之间不能互相抵消,炮弹不区分敌我。',
'8.tank有H格血量,每发炮弹只能打掉tank一格血量。',
'9.炮弹具有最高优先结算权,即游戏首先结算炮弹的行进,然后再结算tank的开火,最后结算行进和移动操作。如果炮弹击毁一辆tank,此辆tank将不具有进行下一步操作的权利。炮弹命中tank或障碍物之后炮弹即消失。多发炮弹命中同一量坦克后,所有炮弹全部消失,即使被命中的tank只有一滴HP。tank行进路上遭遇炮弹会被判定为被击中。',
'10.同一坐标不允许有两辆tank存在,即两辆tank的下一步操作导致进入相同坐标,这两辆tank的位置停留在进入相同坐标前的位置。例如,如果两辆坦克行进两格后会处于同于位置,则两辆坦克各自行进一格。',
'11.单场地图比赛获胜条件: A)在限定的回合当中,一方的坦克被全部击毁则游戏结束,幸存的一方获胜。 B)在限定的回合结束后,双方均有坦克存留,按以下方式结算:',
' 11.1.每辆剩余的tank获得i分',
' 11.2.每一面获取的战旗得j分',
' 11.3.i+j分数高的一方获胜'
],
date: "2018-04-03"
},
{
id: 1,
title: "平台操作流程",
author: "fangheng",
content: ['1.在”策略管理“中上传项目,目前仅支持Java项目,并压缩成zip格式,其中结构为:',
'1.1.src/main: 存放代码',
'1.2.src/resources: 存放资源',
'1.3.lib: 存放需要使用到的库文件',
'2.项目上传后,可在”游戏大厅“寻觅战斗,既可以自己开房间,让其他玩家进入房间产生战斗;也可以进入别人的房间战斗.',
'3.战斗在服务器计算完毕之后,会生成对应的战斗回放,可在“战斗回放“中查看.'],
date: "2018-05-05"
}
];
export default {
getArticles,
};
|
TexBlock/project-rankine
|
src/main/java/com/cannolicatfish/rankine/world/gen/feature/FallenLogFeature.java
|
package com.cannolicatfish.rankine.world.gen.feature;
import com.cannolicatfish.rankine.blocks.RankineOreBlock;
import com.cannolicatfish.rankine.init.Config;
import com.cannolicatfish.rankine.init.RankineBlocks;
import com.cannolicatfish.rankine.util.WorldgenUtils;
import com.mojang.serialization.Codec;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.ISeedReader;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.NoFeatureConfig;
import java.util.Arrays;
import java.util.Random;
public class FallenLogFeature extends Feature<NoFeatureConfig> {
public FallenLogFeature(Codec<NoFeatureConfig> p_i49915_1_) {
super(p_i49915_1_);
}
@Override
public boolean generate(ISeedReader reader, ChunkGenerator generator, Random rand, BlockPos pos, NoFeatureConfig config) {
if (rand.nextFloat() < Config.MISC_WORLDGEN.END_METEORITE_CHANCE.get()) {
}
return true;
}
}
|
jmbuck/mediarchive
|
server/src/main/java/com/mediarchive/server/service/SeriesRepository.java
|
<reponame>jmbuck/mediarchive<gh_stars>0
package com.mediarchive.server.service;
import com.mediarchive.server.domain.MediaList;
import com.mediarchive.server.domain.Series;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface SeriesRepository extends CrudRepository<Series, Long> {
List<Series> findByMediaList(MediaList mediaList);
Series findByMediaListAndId(MediaList mediaList, String id);
<S extends Series>S save(S series);
}
|
connect-foundation/2019-06
|
server/src/database/index.js
|
<filename>server/src/database/index.js
import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
import configs from '../config/config';
const env = process.env.NODE_ENV || 'development';
const config = configs[env];
const db = {};
const { database, username, password } = config;
const sequelize = new Sequelize(database, username, password, config);
const MODEL_DIRECTORY = '/models';
const directoryFiles = fs.readdirSync(path.join(__dirname, MODEL_DIRECTORY));
const modelFiles = directoryFiles.filter(file => file.slice(-3) === '.js');
modelFiles.forEach(file => {
// eslint-disable-next-line no-path-concat
const model = sequelize.import(path.join(__dirname + MODEL_DIRECTORY, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
export default db;
|
tonioshikanlu/tubman-hack
|
sources/b/l/a/d/a/e/e.java
|
package b.l.a.d.a.e;
import android.os.IInterface;
public interface e extends IInterface {
}
|
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
|
src/StockIT-v1-release_source_from_JADX/sources/com/google/zxing/datamatrix/encoder/EncoderContext.java
|
<reponame>atul-vyshnav/2021_IBM_Code_Challenge_StockIT
package com.google.zxing.datamatrix.encoder;
import com.google.zxing.Dimension;
import java.nio.charset.StandardCharsets;
import kotlin.UByte;
final class EncoderContext {
private final StringBuilder codewords;
private Dimension maxSize;
private Dimension minSize;
private final String msg;
private int newEncoding;
int pos;
private SymbolShapeHint shape;
private int skipAtEnd;
private SymbolInfo symbolInfo;
EncoderContext(String str) {
byte[] bytes = str.getBytes(StandardCharsets.ISO_8859_1);
StringBuilder sb = new StringBuilder(bytes.length);
int length = bytes.length;
int i = 0;
while (i < length) {
char c = (char) (bytes[i] & UByte.MAX_VALUE);
if (c != '?' || str.charAt(i) == '?') {
sb.append(c);
i++;
} else {
throw new IllegalArgumentException("Message contains characters outside ISO-8859-1 encoding.");
}
}
this.msg = sb.toString();
this.shape = SymbolShapeHint.FORCE_NONE;
this.codewords = new StringBuilder(str.length());
this.newEncoding = -1;
}
public void setSymbolShape(SymbolShapeHint symbolShapeHint) {
this.shape = symbolShapeHint;
}
public void setSizeConstraints(Dimension dimension, Dimension dimension2) {
this.minSize = dimension;
this.maxSize = dimension2;
}
public String getMessage() {
return this.msg;
}
public void setSkipAtEnd(int i) {
this.skipAtEnd = i;
}
public char getCurrentChar() {
return this.msg.charAt(this.pos);
}
public char getCurrent() {
return this.msg.charAt(this.pos);
}
public StringBuilder getCodewords() {
return this.codewords;
}
public void writeCodewords(String str) {
this.codewords.append(str);
}
public void writeCodeword(char c) {
this.codewords.append(c);
}
public int getCodewordCount() {
return this.codewords.length();
}
public int getNewEncoding() {
return this.newEncoding;
}
public void signalEncoderChange(int i) {
this.newEncoding = i;
}
public void resetEncoderSignal() {
this.newEncoding = -1;
}
public boolean hasMoreCharacters() {
return this.pos < getTotalMessageCharCount();
}
private int getTotalMessageCharCount() {
return this.msg.length() - this.skipAtEnd;
}
public int getRemainingCharacters() {
return getTotalMessageCharCount() - this.pos;
}
public SymbolInfo getSymbolInfo() {
return this.symbolInfo;
}
public void updateSymbolInfo() {
updateSymbolInfo(getCodewordCount());
}
public void updateSymbolInfo(int i) {
SymbolInfo symbolInfo2 = this.symbolInfo;
if (symbolInfo2 == null || i > symbolInfo2.getDataCapacity()) {
this.symbolInfo = SymbolInfo.lookup(i, this.shape, this.minSize, this.maxSize, true);
}
}
public void resetSymbolInfo() {
this.symbolInfo = null;
}
}
|
amvb/GUCEF
|
dependencies/MyGui/UnitTests/UnitTest_TreeControl/GenericNode.h
|
/*!
@file
@author <NAME>
@date 08/2009
*/
#ifndef __GENERIC_NODE_H__
#define __GENERIC_NODE_H__
namespace MyGUI
{
template<class NODE, class OWNER>
class GenericNode
{
public:
typedef std::vector<NODE*> VectorGenericNodePtr;
GenericNode();
GenericNode(OWNER* pOwner);
GenericNode(const UString& strText, NODE* pParent = nullptr);
virtual ~GenericNode();
void add(NODE* pNode);
void remove(NODE* pNode, bool bDelete = true);
void removeAll(bool bDelete = true);
bool hasAncestor(const NODE* pNode) const;
bool hasDescendant(const NODE* pNode) const;
bool hasChildren() const;
const VectorGenericNodePtr& getChildren() const;
VectorGenericNodePtr& getChildren();
NODE* getParent() const;
const UString& getText() const;
void setText(const UString& strText);
OWNER* getOwner() const;
void setOwner(OWNER* pOwner);
void invalidate();
protected:
NODE* mpParent;
VectorGenericNodePtr mChildren;
UString mstrText;
OWNER* mpOwner;
};
template<class NODE, class OWNER>
GenericNode<NODE, OWNER>::GenericNode(OWNER* pOwner) :
mpParent(nullptr),
mstrText("[ROOT]"),
mpOwner(pOwner)
{
MYGUI_DEBUG_ASSERT(mpOwner, "GenericNode<NODE, OWNER>::GenericNode pOwner is nullptr");
}
template<class NODE, class OWNER>
GenericNode<NODE, OWNER>::GenericNode(const UString& strText, NODE* pParent) :
mpParent(pParent),
mstrText(strText)
{
if (pParent)
{
mpOwner = pParent->mpOwner;
pParent->mChildren.push_back(static_cast<NODE*>(this));
invalidate();
}
else
mpOwner = nullptr;
}
template<class NODE, class OWNER>
GenericNode<NODE, OWNER>::~GenericNode()
{
if (mpParent)
mpParent->remove(static_cast<NODE*>(this), false);
while (!mChildren.empty())
{
NODE* pChild = mChildren.back();
mChildren.pop_back();
pChild->mpParent = nullptr;
delete pChild;
}
invalidate();
}
template<class NODE, class OWNER>
void GenericNode<NODE, OWNER>::setText(const UString& strText)
{
mstrText = strText;
invalidate();
}
template<class NODE, class OWNER>
void GenericNode<NODE, OWNER>::setOwner(OWNER* pOwner)
{
mpOwner = pOwner;
for (typename VectorGenericNodePtr::iterator Iterator = mChildren.begin(); Iterator != mChildren.end(); ++Iterator)
(*Iterator)->setOwner(pOwner);
}
template<class NODE, class OWNER>
bool GenericNode<NODE, OWNER>::hasAncestor(const NODE* pNode) const
{
return (mpParent == pNode || (mpParent && mpParent->hasAncestor(pNode)));
}
template<class NODE, class OWNER>
bool GenericNode<NODE, OWNER>::hasDescendant(const NODE* pNode) const
{
for (typename VectorGenericNodePtr::const_iterator Iterator = mChildren.begin(); Iterator != mChildren.end(); ++Iterator)
{
if (*Iterator == pNode || (*Iterator)->hasDescendant(pNode))
return true;
}
return false;
}
template<class NODE, class OWNER>
void GenericNode<NODE, OWNER>::add(NODE* pNode)
{
MYGUI_DEBUG_ASSERT(pNode, "GenericNode<NODE, OWNER>::add pNode is nullptr");
if (pNode->mpParent)
pNode->mpParent->remove(pNode, false);
pNode->mpParent = static_cast<NODE*>(this);
pNode->setOwner(mpOwner);
mChildren.push_back(pNode);
invalidate();
}
template<class NODE, class OWNER>
void GenericNode<NODE, OWNER>::remove(NODE* pNode, bool bDelete)
{
MYGUI_DEBUG_ASSERT(pNode, "GenericNode<NODE, OWNER>::remove pNode is nullptr");
for (typename VectorGenericNodePtr::iterator Iterator = mChildren.begin(); Iterator != mChildren.end(); ++Iterator)
{
if (*Iterator != pNode)
continue;
mChildren.erase(Iterator);
pNode->mpParent = nullptr;
if (bDelete)
delete pNode;
invalidate();
return;
}
MYGUI_DEBUG_ASSERT(pNode, "GenericNode<NODE, OWNER>::remove pNode not child");
}
template<class NODE, class OWNER>
void GenericNode<NODE, OWNER>::removeAll(bool bDelete)
{
while (!mChildren.empty())
{
NODE* pChild = mChildren.back();
mChildren.pop_back();
pChild->mpParent = nullptr;
if (bDelete)
delete pChild;
}
invalidate();
}
template<class NODE, class OWNER>
void GenericNode<NODE, OWNER>::invalidate()
{
if (mpOwner)
mpOwner->invalidate();
}
template<class NODE, class OWNER>
inline GenericNode<NODE, OWNER>::GenericNode()
{
mpParent = nullptr;
mpOwner = nullptr;
}
template<class NODE, class OWNER>
inline const std::vector<NODE*>& GenericNode<NODE, OWNER>::getChildren() const
{
return mChildren;
}
template<class NODE, class OWNER>
inline std::vector<NODE*>& GenericNode<NODE, OWNER>::getChildren()
{
return mChildren;
}
template<class NODE, class OWNER>
inline bool GenericNode<NODE, OWNER>::hasChildren() const
{
return !mChildren.empty();
}
template<class NODE, class OWNER>
inline const UString& GenericNode<NODE, OWNER>::getText() const
{
return mstrText;
}
template<class NODE, class OWNER>
inline OWNER* GenericNode<NODE, OWNER>::getOwner() const
{
return mpOwner;
}
template<class NODE, class OWNER>
NODE* GenericNode<NODE, OWNER>::getParent() const
{
return mpParent;
}
}
#endif // __GENERIC_NODE_H__
|
fjacobs/spring-data-examples
|
jpa/deferred/src/main/java/example/service/Customer1493Service.java
|
<gh_stars>1-10
package example.service;
import example.repo.Customer1493Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer1493Service {
public Customer1493Service(Customer1493Repository repo) {
}
}
|
rhuan080/dls-repository-stack
|
shared-source/src/edu/ucar/dls/suggest/resource/urlcheck/UrlValidator.java
|
<gh_stars>1-10
/*
Copyright 2017 Digital Learning Sciences (DLS) at the
University Corporation for Atmospheric Research (UCAR),
P.O. Box 3000, Boulder, CO 80307
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 edu.ucar.dls.suggest.resource.urlcheck;
import edu.ucar.dls.serviceclients.remotesearch.SearchServiceClient;
import edu.ucar.dls.serviceclients.remotesearch.reader.ADNItemDocReader;
import edu.ucar.dls.schemedit.url.UrlHelper;
import edu.ucar.dls.schemedit.url.DupSim;
import edu.ucar.dls.index.SimpleLuceneIndex;
import java.util.*;
/**
* Uses the Search Web Service (DDSWS v1.0) to search a repository (or a
* collection within a repository) for ADN records having duplicate and/or similar
* urls in it's primary or mirrorUrl fields.<p>
*
* The primary method is validate, which takes a referenceUrl, and returns a
* ValidatorResults instance that stores information about records that contain
* duplicate and similar urls in the PrimaryURL and MirrorUrl fields.
*
*
* @author ostwald<p>
*
* $Id $
* @version $Id: UrlValidator.java,v 1.3 2009/03/20 23:34:00 jweather Exp $
*/
public class UrlValidator {
private static boolean debug = true;
private String referenceCollection = null;
private SearchServiceClient searchServiceClient = null;
private DupSim duplicate = null;
private List similarPrimaryUrls = null;
static int SEARCH_LEVELS = 3;
static int MAX_DELTA = 3;
/**
* Constructor for the UrlValidator object
*
* @param searchServiceBaseUrl base url of the Search Service used to
* validate a url
* @param referenceCollection NOT YET DOCUMENTED
*/
public UrlValidator(String searchServiceBaseUrl, String referenceCollection) {
this(new SearchServiceClient(searchServiceBaseUrl), referenceCollection);
}
/**
* Constructor for the UrlValidator object
*
* @param searchServiceClient base url of the Search Service used to validate
* a url
* @param referenceCollection NOT YET DOCUMENTED
*/
public UrlValidator(SearchServiceClient searchServiceClient, String referenceCollection) {
this.referenceCollection = referenceCollection;
SearchServiceClient.setDebug(false);
if (searchServiceClient == null) {
prtln("ERROR: failed to initialize searchServiceClient");
return;
}
this.searchServiceClient = searchServiceClient;
}
/**
* Gets the referenceCollection attribute of the UrlValidator object
*
* @return The referenceCollection value
*/
public String getReferenceCollection() {
return this.referenceCollection;
}
/**
* Construct query string to be used by the Search Service to search for
* records containing matches to the provided url.
*
* @param url Description of the Parameter
* @return Description of the Return Value
*/
private static String makeUrlQueryStr(String url) {
return makeUrlQueryStr(url, null);
}
/**
* Construct query string to search for records (in the specified collection)
* containing urls that match the provided url in either the PrimaryUrl or
* MirrorUrls fields. If a collection is not specified, the entire repository
* is searched.
*
* @param url referenceUrl
* @param collection collection to be searched.
* @return Description of the Return Value
*/
private static String makeUrlQueryStr(String url, String collection) {
String urlEnc = SimpleLuceneIndex.encodeToTerm(url, false);
// construct query string
String q = "urlenc:" + urlEnc;
q += "+OR+urlMirrorsEncoded:" + urlEnc;
// add collection (if present) to query
if (collection != null) {
q = "(" + q + ")+AND+collection:0" + collection;
}
return "q=" + q + "&s=0&n=500";
}
/**
* Create the query string to search for records containing similar urls to
* the provided url.
*
* @param url Description of the Parameter
* @return Description of the Return Value
*/
private String makeSimilarUrlQueryStr(String url) {
String similarUrlPath = UrlHelper.getSimilarUrlPath(url, SEARCH_LEVELS);
prtln("similarUrlPath: " + similarUrlPath);
return makeUrlQueryStr(similarUrlPath, this.referenceCollection);
}
/**
* Return a ValidatorResults instance containing the results of a query to
* find duplicate and similiar urls in the primaryUrl and mirrorUrl fields of
* repository records.
*
* @param referenceUrl The url to be validated
* @return Description of the Return Value
*/
public ValidatorResults validate(String referenceUrl) {
ValidatorResults vr = new ValidatorResults();
// return empty results if there is no referenceCollection Specified
if (this.referenceCollection == null)
return vr;
String queryStr = makeSimilarUrlQueryStr(referenceUrl);
// prtln ("query string: " + queryStr + "\n");
prtln("referenceUrl: " + referenceUrl + "\n");
List searchResults = searchServiceClient.searchDocs(queryStr);
prtln(searchResults.size() + " search results found");
for (Iterator i = searchResults.iterator(); i.hasNext(); ) {
ADNItemDocReader reader = (ADNItemDocReader) i.next();
String primaryUrl = reader.getUrl();
// is it a duplicate?
if (primaryUrl.equals(referenceUrl)) {
vr.setDuplicate(new DupSim(reader, "primary"));
return vr;
}
if (UrlHelper.isSimilar(referenceUrl, primaryUrl, MAX_DELTA)) {
vr.addSimilarPrimaryUrl(new DupSim(reader, "primary"));
}
for (Iterator m = reader.getMirrorUrls().iterator(); m.hasNext(); ) {
String mirrorUrl = (String) m.next();
if (mirrorUrl.equals(referenceUrl)) {
String id = reader.getId();
DupSim dup = new DupSim(reader.getId(), mirrorUrl, "dup", "mirror", "adn");
vr.setDuplicate(dup);
return vr;
}
if (UrlHelper.isSimilar(referenceUrl, mirrorUrl, MAX_DELTA)) {
DupSim dup = new DupSim(reader.getId(), mirrorUrl, "sim", "mirror", "adn");
vr.addSimilarMirrorUrl(dup);
}
}
}
return vr;
}
/**
* The main program for the UrlValidator class
*
* @param args The command line arguments
* @exception Exception Description of the Exception
*/
public static void main(String[] args)
throws Exception {
String url = "http://www.fooberry.com";
if (args.length > 0) {
url = args[0];
}
String collection = null;
if (args.length > 1) {
collection = args[1];
}
prtln("reference Url: " + url);
String serviceUrl = "http://172.16.58.3:8688/schemedit/services/ddsws1-0";
UrlValidator v = new UrlValidator(serviceUrl, collection);
ValidatorResults vr = v.validate(url);
prtln(vr.toString());
prtln("======================================");
}
/**
* Sets the debug attribute of the UrlValidator class
*
* @param bool The new debug value
*/
public static void setDebug(boolean bool) {
debug = bool;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
*/
private static void prtln(String s) {
if (debug) {
System.out.println("UrlValidator: " + s);
}
}
}
|
pankajnegi17/hermes-ui-widget
|
example/src/redux/actions/activeChatsActions.js
|
export const ADD_ACTIVE_CHAT = "ADD_ACTIVE_CHAT";
export const DELETE_ACTICE_CHAT = "DELETE_ACTICE_CHAT";
export const DELETE_ALL_ACTIVE_CHATS = "DELETE_ALL_ACTIVE_CHATS";
|
korneliakobiela/TAU-Design-Editor
|
design-editor/src/panel/property/attribute/attribute-element-interactive.js
|
<gh_stars>0
import mustache from 'mustache';
import $ from 'jquery';
import path from 'path';
import utils from '../../../utils/utils';
import {DressElement} from '../../../utils/dress-element';
import {appManager as AppManager} from '../../../app-manager';
var brackets = utils.checkGlobalContext('brackets');
var PreferencesManager = brackets ? brackets.getModule('preferences/PreferencesManager') : {};
var ProjectManager = brackets ? brackets.getModule('project/ProjectManager') : {};
var NodeDomain = brackets ? brackets.getModule('utils/NodeDomain') : {};
var TEMPLATE_FILE = 'panel/property/attribute/attribute-element-interactive.html';
// FIXME: I could't find a way to find the root directory of the project.
// So I used a specific location of the domain of the interactive.
var domainPath = '../../../../../../brackets-server/embedded-ext/interactive3D/node/interactiveDomain';
var nodeDomain = brackets ? new NodeDomain('interactiveDomain', domainPath): {};
function getBasePath (path) {
var newPath = path.split('/');
newPath.splice(newPath.length-1, 1);
newPath.splice(0, 2);
return newPath.join('/');
}
class AttributeInterative extends DressElement {
onAttached() {
this._render();
}
onCreated() {
}
_clearElement(empty) {
var self = this;
if (empty) {
self.$el.empty();
}
}
setData(element) {
var self = this,
$el = self.$el;
var globalData = utils.checkGlobalContext('globalData');
var designEditor = AppManager.getActiveDesignEditor();
var basePath = getBasePath(globalData.fileUrl);
var modelContainer = $el.find('#model-editor-container');
modelContainer.hide();
var projectId = PreferencesManager.getViewState('projectId');
if (nodeDomain) {
nodeDomain.exec('getModel', projectId).done(data => {
var models = JSON.parse(data);
var modelImage = $el.find('#model-image');
var modelSelect = $el.find('#model-selector');
var typeSelect = $el.find('#type-selector');
modelSelect.empty();
var seedOption = document.createElement('option');
seedOption.text = 'Choose model';
seedOption.setAttribute('selected', true);
modelSelect.append(seedOption);
for (var model of models) {
var option = document.createElement('option');
option.text = model.title;
option.setAttribute('value', model.title);
option.setAttribute('i3d-model', model.id);
modelSelect.append(option);
}
var objects;
// Remove registered event handlers
typeSelect.off();
typeSelect.change(function() {
var selectedIndex = this.options.selectedIndex;
var selectedOption = this.options.item(selectedIndex);
var selectedModel = selectedOption.getAttribute('i3d-model');
var selectedId = selectedOption.getAttribute('id');
var selectedType = selectedOption.getAttribute('type');
for (var object of objects) {
if (object.id === selectedId) {
if (designEditor) {
var model = designEditor.getModel();
var file = object.files.find(function(f) { return f.type === selectedType; });
model.updateAttribute(element.id, 'type', selectedType);
model.updateAttribute(element.id, 'src', path.join('i3d', 'models', selectedModel, selectedId, file.file));
if (selectedType === 'obj') {
var mtl = object.files.find(function(f) { return f.type === 'mtl' });
if (mtl) {
model.updateAttribute(element.id, 'mtl', path.join('i3d', 'models', selectedModel, selectedId, mtl.file));
}
} else {
// Remove the mtl attribute
model.removeAttribute(element.id, 'mtl');
}
}
}
}
});
// Remove registered event handlers
modelSelect.off();
modelSelect.change(function() {
var selectedIndex = this.options.selectedIndex;
if (selectedIndex !== 0) {
var selectedOption = this.options.item(selectedIndex);
var modelID = selectedOption.getAttribute('i3d-model');
for (var model of models) {
if (model.id === modelID) {
objects = model.objects;
typeSelect.empty();
for (var object of objects) {
var option = document.createElement('option');
option.setAttribute('id', object.id);
option.setAttribute('type', object.type);
option.setAttribute('i3d-model', modelID);
option.text = object.type;
typeSelect.append(option);
}
object = model.objects[0];
break;
}
}
nodeDomain.exec('copyModel', projectId, basePath, modelID).done(() => {
if (designEditor) {
var model = designEditor.getModel();
model.updateAttribute(element.id, 'name', selectedOption.getAttribute('value'));
model.updateAttribute(element.id, 'i3d-model', modelID);
var file = objects[0].files.find(function(f) { return f.type === objects[0].type; });
model.updateAttribute(element.id, 'src', path.join('i3d', 'models', modelID, objects[0].id, file.file));
model.updateAttribute(element.id, 'i3d-model', modelID);
}
modelContainer.show();
modelImage.attr('src', path.join('/projects', projectId, basePath, 'i3d', 'models', modelID, 'model.png'));
ProjectManager.refreshFileTree();
});
}
});
if (designEditor) {
// Clear all previous data
$el.find('input[name^="i3d-"][type=text]').val('');
$el.find('input[name^="i3d-"][type=checkbox]').attr('checked', false);
for (var attr of element.attributes) {
if (attr.name.name === 'name') {
modelSelect.val(attr.name.value).change();
} else if (attr.name.name === 'type') {
typeSelect.val(attr.name.value).change();
} else if (['width', 'height', 'position', 'scale', 'rotation', 'light'].indexOf(attr.name.name) !== -1) {
$el.find('input[name=i3d-'+attr.name.name+']').val(attr.name.value);
} else if (['autoplay', 'controls'].indexOf(attr.name.name) !== -1) {
$el.find('input[name=i3d-'+attr.name.name+']').attr('checked', true);
}
}
}
});
}
}
_render() {
var self = this;
$.get(path.join(AppManager.getAppPath().src, TEMPLATE_FILE), (template) => {
self._clearElement(true);
self.$el.append(mustache.render(template, self._data));
});
}
}
var AttributeInteractiveElement = document.registerElement('closet-attribute-interactive', AttributeInterative);
export {AttributeInteractiveElement, AttributeInterative};
|
sfahad1414/AGENT
|
components/page-analyzer/tests/test_concrete_state_featurizer.py
|
<reponame>sfahad1414/AGENT
import json
import pandas as pd
import pytest
from services.concrete_state_featurizer import calc_color_distance, calc_point_distance, sigmoid, get_nearest_color, \
normalize, ConcreteStateFeaturize, basic_html_tags
class TestConcreteStateFeaturize:
def test_calc_color_distance_same_color(self):
# Arrange
color_1 = [100, 100, 100]
color_2 = [100, 100, 100]
# Act
dist = calc_color_distance(color_1, color_2)
# Assert
assert dist == 0.0
def test_calc_color_distance_similar_colors(self):
# Arrange
color_1 = [101, 100, 100]
color_2 = [100, 100, 100]
# Act
dist = calc_color_distance(color_1, color_2)
# Assert
assert 0.0 < dist < 30.0
def test_calc_color_distance_different_colors(self):
# Arrange
color_1 = [0, 100, 100]
color_2 = [100, 100, 100]
# Act
dist = calc_color_distance(color_1, color_2)
# Assert
assert 30.0 < dist < 50.0
def test_calc_point_distance_zero_distance(self):
# Act.
dist = calc_point_distance(50, 50, 50, 50)
# Assert.
assert dist == 0.0
def test_calc_point_distance_non_zero_distance(self):
# Act.
dist = calc_point_distance(50, 50, 55, 55)
# Assert.
assert dist == 7.0710678118654755
def test_sigmoid_zero(self):
# Act.
sig = sigmoid(0)
# Assert.
assert sig == 0.5
def test_sigmoid_one(self):
# Act.
sig = sigmoid(1)
# Assert.
assert sig == 0.7310585786300049
def test_get_nearest_color_red(self):
# Arrange.
color = "rgb(255, 0, 0)"
# Act.
nearest = get_nearest_color(color)
# Assert.
assert nearest == "red"
def test_get_nearest_color_rgba(self):
# Arrange.
color = "rgb(255, 0, 0, 1)"
# Act.
nearest = get_nearest_color(color)
# Assert.
assert nearest == "red"
def test_get_nearest_color_shade_of_red(self):
# Arrange.
color = "rgb(196, 31, 31)"
# Act.
nearest = get_nearest_color(color)
# Assert.
assert nearest == "red"
def test_get_nearest_color_shade_of_grey(self):
# Arrange.
color = "rgb(147, 144, 144)"
# Act.
nearest = get_nearest_color(color)
# Assert.
assert nearest == "grey"
def test_get_nearest_color_invalid_format(self):
# Arrange.
color = "rgb"
# Act.
nearest = get_nearest_color(color)
# Assert.
assert nearest == "black"
def test_normalize(self):
# Arrange.
my_dict = {
'name': ["a", "b", "c", "d", "e", "f", "g"],
'age': [20, 27, 35, 55, 18, 21, 35],
'designation': ["VP", "CEO", "CFO", "VP", "VP", "CEO", "MD"]
}
df = pd.DataFrame(my_dict)
# Act.
df = normalize(df, ['name', 'designation'])
# Assert.
assert df['age'][0] == 0.0541
assert df['age'][1] == 0.2432
assert df['age'][2] == 0.4595
assert df['age'][3] == 1.0000
assert df['age'][4] == 0.0000
assert df['age'][5] == 0.0811
assert df['age'][6] == 0.4595
def test_normalize_with_non_excluded_non_numeric_data(self):
# Arrange.
my_dict = {
'name': ["a", "b", "c", "d", "e", "f", "g"],
'age': [20, 27, 35, 55, 18, 21, 35],
'designation': ["VP", "CEO", "CFO", "VP", "VP", "CEO", "MD"]
}
df = pd.DataFrame(my_dict)
# Act.
with pytest.raises(Exception) as e_info:
normalize(df, ['name'])
# Assert.
assert str(e_info.value) == 'Error normalizing feature: designation'
def test_convert_to_feature_frame_single_widget(self):
# Arrange.
with open('json/single_widget.json') as file:
json_data = json.loads(file.read())
# Act.
df = ConcreteStateFeaturize.convert_to_feature_frame(json_data)
# Assert.
assert df.shape[0] == 3
assert df.shape[1] == 16
assert 'Key' in df.columns.values
assert 'Tag' in df.columns.values
assert 'Parent_Tag' in df.columns.values
assert 'Attr_For' in df.columns.values
assert 'Num_Children' in df.columns.values
assert 'Num_Siblings' in df.columns.values
assert 'Depth' in df.columns.values
assert 'X_Percent' in df.columns.values
assert 'Y_Percent' in df.columns.values
assert 'Font_Size' in df.columns.values
assert 'Font_Weight' in df.columns.values
assert 'Is_Text' in df.columns.values
assert 'Nearest_Color' in df.columns.values
assert 'Nearest_Bg_Color' in df.columns.values
assert 'Distance_From_Input' in df.columns.values
assert 'Text' in df.columns.values
assert df['Key'][0] == "DIV0_0_1_0_0_0:4"
assert df['Key'][1] == "LABEL0_0_1_0_0_0_0_0_0_1_1_0:10"
assert df['Key'][2] == "INPUTusername0_0_1_0_0_0_0_0_0_1_1_1:10"
assert df['Tag'][0] == basic_html_tags.index('div') + 1
assert df['Tag'][1] == basic_html_tags.index('label') + 1
assert df['Tag'][2] == basic_html_tags.index('input') + 1
assert df['Parent_Tag'][0] == 0
assert df['Parent_Tag'][1] == basic_html_tags.index('div') + 1
assert df['Parent_Tag'][2] == basic_html_tags.index('div') + 1
assert df['Attr_For'][0] == 0.0
assert df['Attr_For'][1] == 1.0
assert df['Attr_For'][2] == 0.0
# Num Children is normalized.
assert df['Num_Children'][0] == 1.0
assert df['Num_Children'][1] == 0.5
assert df['Num_Children'][2] == 0.0
# Num Siblings is normalized.
assert df['Num_Siblings'][0] == 0.0
assert df['Num_Siblings'][1] == 1.0
assert df['Num_Siblings'][2] == 1.0
# Depth is normalized.
assert df['Depth'][0] == 0.0
assert df['Depth'][1] == 1.0
assert df['Depth'][2] == 1.0
# X_Percent is normalized.
assert df['X_Percent'][0] == 0.0
assert df['X_Percent'][1] == 1.0
assert df['X_Percent'][2] == 1.0
# Y_Percent is normalized.
assert df['Y_Percent'][0] == 0.0
assert df['Y_Percent'][1] == 0.875
assert df['Y_Percent'][2] == 1.0
# Font Size is normalized.
assert df['Font_Size'][0] == 0.0
assert df['Font_Size'][1] == 1.0
assert df['Font_Size'][2] == 0.5556
# Font Weight is normalized.
assert df['Font_Weight'][0] == 0.3333
assert df['Font_Weight'][1] == 1.0
assert df['Font_Weight'][2] == 0.0
assert df['Is_Text'][0] == 0.0
assert df['Is_Text'][1] == 1.0
assert df['Is_Text'][2] == 0.0
assert df['Nearest_Color'][0] == "grey"
assert df['Nearest_Color'][1] == "grey"
assert df['Nearest_Color'][2] == "grey"
assert df['Nearest_Bg_Color'][0] == "black"
assert df['Nearest_Bg_Color'][1] == "black"
assert df['Nearest_Bg_Color'][2] == "white"
# Distance From Input is normalized.
assert df['Distance_From_Input'][0] == 1.0
assert df['Distance_From_Input'][1] == 0.0325
assert df['Distance_From_Input'][2] == 0.0
assert df['Text'][0] == ""
assert df['Text'][1] == "Username"
assert df['Text'][2] == ""
def test_convert_to_feature_frame_without_color_measurements(self):
# Arrange.
with open('json/single_widget.json') as file:
json_data = json.loads(file.read())
# Act.
df = ConcreteStateFeaturize.convert_to_feature_frame(json_data, measure_color_distance=False)
# Assert.
assert df.shape[0] == 3
assert df.shape[1] == 16
assert 'Key' in df.columns.values
assert 'Tag' in df.columns.values
assert 'Parent_Tag' in df.columns.values
assert 'Attr_For' in df.columns.values
assert 'Num_Children' in df.columns.values
assert 'Num_Siblings' in df.columns.values
assert 'Depth' in df.columns.values
assert 'X_Percent' in df.columns.values
assert 'Y_Percent' in df.columns.values
assert 'Font_Size' in df.columns.values
assert 'Font_Weight' in df.columns.values
assert 'Is_Text' in df.columns.values
assert 'Nearest_Color' in df.columns.values
assert 'Nearest_Bg_Color' in df.columns.values
assert 'Distance_From_Input' in df.columns.values
assert 'Text' in df.columns.values
assert df['Key'][0] == "DIV0_0_1_0_0_0:4"
assert df['Key'][1] == "LABEL0_0_1_0_0_0_0_0_0_1_1_0:10"
assert df['Key'][2] == "INPUTusername0_0_1_0_0_0_0_0_0_1_1_1:10"
assert df['Tag'][0] == basic_html_tags.index('div') + 1
assert df['Tag'][1] == basic_html_tags.index('label') + 1
assert df['Tag'][2] == basic_html_tags.index('input') + 1
assert df['Parent_Tag'][0] == 0
assert df['Parent_Tag'][1] == basic_html_tags.index('div') + 1
assert df['Parent_Tag'][2] == basic_html_tags.index('div') + 1
assert df['Attr_For'][0] == 0.0
assert df['Attr_For'][1] == 1.0
assert df['Attr_For'][2] == 0.0
# Num Children is normalized.
assert df['Num_Children'][0] == 1.0
assert df['Num_Children'][1] == 0.5
assert df['Num_Children'][2] == 0.0
# Num Siblings is normalized.
assert df['Num_Siblings'][0] == 0.0
assert df['Num_Siblings'][1] == 1.0
assert df['Num_Siblings'][2] == 1.0
# Depth is normalized.
assert df['Depth'][0] == 0.0
assert df['Depth'][1] == 1.0
assert df['Depth'][2] == 1.0
# X_Percent is normalized.
assert df['X_Percent'][0] == 0.0
assert df['X_Percent'][1] == 1.0
assert df['X_Percent'][2] == 1.0
# Y_Percent is normalized.
assert df['Y_Percent'][0] == 0.0
assert df['Y_Percent'][1] == 0.875
assert df['Y_Percent'][2] == 1.0
# Font Size is normalized.
assert df['Font_Size'][0] == 0.0
assert df['Font_Size'][1] == 1.0
assert df['Font_Size'][2] == 0.5556
# Font Weight is normalized.
assert df['Font_Weight'][0] == 0.3333
assert df['Font_Weight'][1] == 1.0
assert df['Font_Weight'][2] == 0.0
assert df['Is_Text'][0] == 0.0
assert df['Is_Text'][1] == 1.0
assert df['Is_Text'][2] == 0.0
assert df['Nearest_Color'][0] == "black"
assert df['Nearest_Color'][1] == "black"
assert df['Nearest_Color'][2] == "black"
assert df['Nearest_Bg_Color'][0] == "black"
assert df['Nearest_Bg_Color'][1] == "black"
assert df['Nearest_Bg_Color'][2] == "black"
# Distance From Input is normalized.
assert df['Distance_From_Input'][0] == 1.0
assert df['Distance_From_Input'][1] == 0.0325
assert df['Distance_From_Input'][2] == 0.0
assert df['Text'][0] == ""
assert df['Text'][1] == "Username"
assert df['Text'][2] == ""
def test_convert_to_feature_frame_with_empty_for_attribute(self):
# Arrange.
with open('json/empty_for_attribute.json') as file:
json_data = json.loads(file.read())
# Act.
df = ConcreteStateFeaturize.convert_to_feature_frame(json_data, measure_color_distance=False)
# Assert.
assert df.shape[0] == 3
assert df.shape[1] == 16
assert 'Key' in df.columns.values
assert 'Attr_For' in df.columns.values
assert df['Key'][0] == "DIV0_0_1_0_0_0:4"
assert df['Key'][1] == "LABEL0_0_1_0_0_0_0_0_0_1_1_0:10"
assert df['Key'][2] == "INPUTusername0_0_1_0_0_0_0_0_0_1_1_1:10"
assert df['Attr_For'][0] == 0.0
assert df['Attr_For'][1] == 0.0
assert df['Attr_For'][2] == 0.0
def test_convert_to_feature_frame_with_equal_min_max_during_normalize(self):
# Arrange.
with open('json/min_equal_max_normalize.json') as file:
json_data = json.loads(file.read())
# Act.
df = ConcreteStateFeaturize.convert_to_feature_frame(json_data, measure_color_distance=False)
# Assert.
assert df.shape[0] == 3
assert df.shape[1] == 16
assert 'Key' in df.columns.values
assert 'Tag' in df.columns.values
assert 'Parent_Tag' in df.columns.values
assert 'Attr_For' in df.columns.values
assert 'Num_Children' in df.columns.values
assert 'Num_Siblings' in df.columns.values
assert 'Depth' in df.columns.values
assert 'X_Percent' in df.columns.values
assert 'Y_Percent' in df.columns.values
assert 'Font_Size' in df.columns.values
assert 'Font_Weight' in df.columns.values
assert 'Is_Text' in df.columns.values
assert 'Nearest_Color' in df.columns.values
assert 'Nearest_Bg_Color' in df.columns.values
assert 'Distance_From_Input' in df.columns.values
assert 'Text' in df.columns.values
assert df['Key'][0] == "DIV0_0_1_0_0_0:4"
assert df['Key'][1] == "LABEL0_0_1_0_0_0_0_0_0_1_1_0:10"
assert df['Key'][2] == "INPUTusername0_0_1_0_0_0_0_0_0_1_1_1:10"
# Font Size is normalized.
assert df['Font_Size'][0] == 1.0
assert df['Font_Size'][1] == 1.0
assert df['Font_Size'][2] == 1.0
def test_convert_to_feature_frame(self):
# Arrange.
with open('json/login_page.json') as file:
json_data = json.loads(file.read())
# Act.
df = ConcreteStateFeaturize.convert_to_feature_frame(json_data)
# Assert.
assert df.shape[0] == 14
assert df.shape[1] == 16
assert 'Key' in df.columns.values
assert 'Tag' in df.columns.values
assert 'Parent_Tag' in df.columns.values
assert 'Attr_For' in df.columns.values
assert 'Num_Children' in df.columns.values
assert 'Num_Siblings' in df.columns.values
assert 'Depth' in df.columns.values
assert 'X_Percent' in df.columns.values
assert 'Y_Percent' in df.columns.values
assert 'Font_Size' in df.columns.values
assert 'Font_Weight' in df.columns.values
assert 'Is_Text' in df.columns.values
assert 'Nearest_Color' in df.columns.values
assert 'Nearest_Bg_Color' in df.columns.values
assert 'Distance_From_Input' in df.columns.values
assert 'Text' in df.columns.values
print(df.to_string())
|
MiguelGL/dots-and-boxes
|
server/src/main/java/com/mgl/dotsandboxes/server/resources/game/exception/IllegalConnectionExceptionMapper.java
|
package com.mgl.dotsandboxes.server.resources.game.exception;
import com.mgl.dotsandboxes.server.resources.support.ErrorResponse;
import com.mgl.dotsandboxes.server.service.game.exception.IllegalConnectionException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class IllegalConnectionExceptionMapper {
@ExceptionHandler(IllegalConnectionException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse processException(IllegalConnectionException ex) {
return ErrorResponse.forHttpStatusCode(HttpStatus.BAD_REQUEST, ex.getMessage());
}
}
|
tranquilitybase-io/tb-houston-service
|
models/landing_zone_action.py
|
from config import db, ma
class LandingZoneAction(db.Model):
__tablename__ = "landingzoneaction"
__table_args__ = {"schema": "eagle_db"}
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
categoryName = db.Column(db.String)
categoryClass = db.Column(db.String)
completionRate = db.Column(db.Integer)
locked = db.Column(db.Boolean())
routerLink = db.Column(db.String)
dependantOn = db.Column(db.Integer)
isOptional = db.Column(db.Boolean())
def __repr__(self):
return "<LandingZoneAction(id={self.id!r}, name={self.title!r})>".format(
self=self
)
class LandingZoneActionSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = LandingZoneAction
include_fk = True
load_instance = True
|
DamieFC/chromium
|
chrome/browser/resources/read_later/side_panel/app.js
|
// Copyright 2021 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.
// TODO(crbug.com/1199527): The current structure of c/b/r/read_later/* is
// only temporary. Eventually, this side_panel directory should become the main
// directory, with read_later being moved into a subdirectory within side_panel.
import 'chrome://resources/cr_elements/cr_tabs/cr_tabs.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-pages/iron-pages.js';
import './bookmarks_list.js';
import '../app.js'; /* <read-later-app> */
import '../strings.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {ReadLaterApiProxy, ReadLaterApiProxyImpl} from '../read_later_api_proxy.js';
/**
* Key for localStorage object that refers to the last active tab's ID.
* @const {string}
*/
export const LOCAL_STORAGE_TAB_ID_KEY = 'lastActiveTab';
export class SidePanelAppElement extends PolymerElement {
static get is() {
return 'side-panel-app';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/** @private {!Object<string, string>} */
tabs_: {
type: Object,
value: () => ({
'readingList': loadTimeData.getString('title'),
'bookmarks': loadTimeData.getString('bookmarksTabTitle'),
}),
},
/** @private {number} */
selectedTab_: {
type: Number,
value: 0,
},
};
}
constructor() {
super();
/**
* The side panel is currently hosted within Read Later UI.
* @const @private {!ReadLaterApiProxy}
*/
this.apiProxy_ = ReadLaterApiProxyImpl.getInstance();
}
connectedCallback() {
super.connectedCallback();
const lastActiveTab = window.localStorage[LOCAL_STORAGE_TAB_ID_KEY];
if (lastActiveTab) {
this.selectedTab_ = Object.keys(this.tabs_).indexOf(lastActiveTab) || 0;
}
// Show the UI as soon as the app is connected.
this.apiProxy_.showUI();
}
/**
* @return {!Array<string>}
* @private
*/
getTabNames_() {
return Object.values(this.tabs_);
}
/**
* @param {number} selectedTab
* @param {number} index
* @return {boolean}
* @private
*/
isSelectedTab_(selectedTab, index) {
return selectedTab === index;
}
/** @private */
onCloseClick_() {
this.apiProxy_.closeUI();
}
/**
* @param {!Event} event
* @private
*/
onSelectedTabChanged_(event) {
const tabIndex = event.detail.value;
window.localStorage[LOCAL_STORAGE_TAB_ID_KEY] =
Object.keys(this.tabs_)[tabIndex];
}
}
customElements.define(SidePanelAppElement.is, SidePanelAppElement);
|
KeyrisXdSnow/release
|
src/main/java/io/bootique/tools/release/model/persistent/ClosedIssue.java
|
package io.bootique.tools.release.model.persistent;
import io.bootique.tools.release.model.persistent.auto._ClosedIssue;
public class ClosedIssue extends _ClosedIssue {
private static final long serialVersionUID = 1L;
public ClosedIssue() {
}
public ClosedIssue(OpenIssue issue) {
setGithubId(issue.getGithubId());
setUrl(issue.getUrl());
setNumber(issue.getNumber());
setTitle(issue.getTitle());
setCommentsCount(issue.getCommentsCount());
milestone = issue.getMilestone();
}
}
|
Matixsss/Minecraft-Zmod
|
Zmod 1.15.2/src/main/java/com/DystryktZ/Network/ClientPacketSettings.java
|
package com.DystryktZ.Network;
import java.util.function.Supplier;
import com.DystryktZ.ZmodJson;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkEvent;
public class ClientPacketSettings {
private final CompoundNBT nbt;
public ClientPacketSettings(CompoundNBT nbt)
{
this.nbt = nbt;
}
public static void encode(ClientPacketSettings msg, PacketBuffer buf)
{
buf.writeCompoundTag(msg.nbt);
}
public static ClientPacketSettings decode(PacketBuffer buf)
{
return new ClientPacketSettings(buf.readCompoundTag());
}
public static class Handler //on server side
{
public static void handle(final ClientPacketSettings message, Supplier<NetworkEvent.Context> ctx)
{
ctx.get().enqueueWork(() -> {
ServerPlayerEntity server_player = ctx.get().getSender();
String name = server_player.getDisplayName().getString();
boolean[] settings = new boolean[3];
settings[0] = message.nbt.getBoolean("notification");
if(server_player.hasPermissionLevel(4))
{
settings[1] = message.nbt.getBoolean("blockinfo");
settings[2] = message.nbt.getBoolean("entityinfo");
}
else
{
settings[1] = false;
settings[2] = false;
}
ZmodJson.players_settings.put(name, settings);
});
ctx.get().setPacketHandled(true);
}
}
}
|
herrgrossmann/jo-widgets
|
modules/core/org.jowidgets.api/src/main/java/org/jowidgets/api/layout/ICachedFillLayout.java
|
/*
* Copyright (c) 2013, grossmann
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the jo-widgets.org nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 jo-widgets.org 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.
*/
package org.jowidgets.api.layout;
import org.jowidgets.common.widgets.layout.ILayouter;
/**
* This layouter renders the first visible child of the container into the whole available space and caches the size
* of its children, so the next time the layout will be done, the cached values will be used until
* the cache is cleared by the user.
*
* In many cases, the min, max and pref size of the child container will not change until the child container
* has not been changed by adding or removing children. So using this layout manager as a parent for a complicate
* layout can improve performance extremely. The tradeoff is, that the programmer has to take care for container
* changes itself and clearing the cache.
*/
public interface ICachedFillLayout extends ILayouter {
/**
* Clear's the cache of the layouter, e.g. after container changed
*/
void clearCache();
}
|
sqerison/CloudDeploy_System
|
lib/eops/lib/domain.rb
|
class Domain
def initialize
@sdb = AWS::SimpleDB.new
end
def create(domain_name)
AWS::SimpleDB.consistent_reads do
@sdb.domains.create(domain_name)
end
end
def destroy(domain_name)
@sdb.domains[domain_name].delete
end
def destroy_item(domain_name, item_name)
@sdb.domains[domain_name].items[item_name].delete
end
def load(file_name, sdb_domain, item_name)
file = File.open("#{file_name}", "r")
AWS::SimpleDB.consistent_reads do
item = @sdb.domains[sdb_domain].items[item_name]
file.each_line do |line|
key,value = line.split '='
item.attributes.set( "#{key}" => "#{value}")
end
end
end
def get_property(sdb_domain, item_name, key)
AWS::SimpleDB.consistent_reads do
item = @sdb.domains[sdb_domain].items[item_name]
item.attributes.each_value do |name, value|
if name == key
@property_value = value.chomp
end
end
end
return @property_value
end
def set_property(sdb_domain, item_name, property, value)
AWS::SimpleDB.consistent_reads do
item = @sdb.domains[sdb_domain].items[item_name]
item.attributes.set(property => [value])
end
end
end
|
kabicm/arbor
|
modcc/modccutil.hpp
|
#pragma once
#include <exception>
#include <memory>
#include <sstream>
#include <vector>
#include <initializer_list>
namespace impl {
template <typename C, typename V>
struct has_count_method {
template <typename T, typename U>
static decltype(std::declval<T>().count(std::declval<U>()), std::true_type{}) test(int);
template <typename T, typename U>
static std::false_type test(...);
using type = decltype(test<C, V>(0));
};
template <typename X, typename C>
bool is_in(const X& x, const C& c, std::false_type) {
for (const auto& y: c) {
if (y==x) return true;
}
return false;
}
template <typename X, typename C>
bool is_in(const X& x, const C& c, std::true_type) {
return !!c.count(x);
}
}
template <typename X, typename C>
bool is_in(const X& x, const C& c) {
return impl::is_in(x, c, typename impl::has_count_method<C,X>::type{});
}
template <typename X>
bool is_in(const X& x, const std::initializer_list<X>& c) {
return impl::is_in(x, c, std::false_type{});
}
struct enum_hash {
template <typename E, typename V = typename std::underlying_type<E>::type>
std::size_t operator()(E e) const noexcept {
return std::hash<V>{}(static_cast<V>(e));
}
};
inline std::string pprintf(const char *s) {
std::string errstring;
while(*s) {
if(*s == '%' && s[1]!='%') {
// instead of throwing an exception, replace with ??
//throw std::runtime_error("pprintf: the number of arguments did not match the format ");
errstring += "<?>";
}
else {
errstring += *s;
}
++s;
}
return errstring;
}
// variadic printf for easy error messages
template <typename T, typename ... Args>
std::string pprintf(const char *s, T value, Args... args) {
std::string errstring;
while(*s) {
if(*s == '%' && s[1]!='%') {
std::stringstream str;
str << value;
errstring += str.str();
errstring += pprintf(++s, args...);
return errstring;
}
else {
errstring += *s;
++s;
}
}
return errstring;
}
template <typename T>
std::string to_string(T val) {
std::stringstream str;
str << val;
return str.str();
}
//'\e[1;31m' # Red
//'\e[1;32m' # Green
//'\e[1;33m' # Yellow
//'\e[1;34m' # Blue
//'\e[1;35m' # Purple
//'\e[1;36m' # Cyan
//'\e[1;37m' # White
enum class stringColor {white, red, green, blue, yellow, purple, cyan};
#define COLOR_PRINTING
#ifdef COLOR_PRINTING
inline std::string colorize(std::string const& s, stringColor c) {
switch(c) {
case stringColor::white :
return "\033[1;37m" + s + "\033[0m";
case stringColor::red :
return "\033[1;31m" + s + "\033[0m";
case stringColor::green :
return "\033[1;32m" + s + "\033[0m";
case stringColor::blue :
return "\033[1;34m" + s + "\033[0m";
case stringColor::yellow:
return "\033[1;33m" + s + "\033[0m";
case stringColor::purple:
return "\033[1;35m" + s + "\033[0m";
case stringColor::cyan :
return "\033[1;36m" + s + "\033[0m";
}
return s;
}
#else
inline std::string colorize(std::string const& s, stringColor c) {
return s;
}
#endif
// helpers for inline printing
inline std::string red(std::string const& s) {
return colorize(s, stringColor::red);
}
inline std::string green(std::string const& s) {
return colorize(s, stringColor::green);
}
inline std::string yellow(std::string const& s) {
return colorize(s, stringColor::yellow);
}
inline std::string blue(std::string const& s) {
return colorize(s, stringColor::blue);
}
inline std::string purple(std::string const& s) {
return colorize(s, stringColor::purple);
}
inline std::string cyan(std::string const& s) {
return colorize(s, stringColor::cyan);
}
inline std::string white(std::string const& s) {
return colorize(s, stringColor::white);
}
template <typename T>
std::ostream& operator<< (std::ostream& os, std::vector<T> const& V) {
os << "[";
for(auto it = V.begin(); it!=V.end(); ++it) { // ugly loop, pretty printing
os << *it << (it==V.end()-1 ? "" : " ");
}
return os << "]";
}
template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args) ...));
}
|
xswz8015/infra
|
go/src/infra/cros/cmd/prototype-rts/internal/cmd/flags.go
|
<reponame>xswz8015/infra
package cmd
import "github.com/maruel/subcommands"
type flags struct {
subcommands.CommandRunBase
progressSinkPort int
tlsCommonPort int
}
func (f *flags) InitRTSFlags() {
if f == nil {
*f = flags{}
}
f.Flags.IntVar(&f.progressSinkPort, "progress-sink-port", 0, "Port for the local ProgressSink gRPC server. The default value implies a random port selection.")
f.Flags.IntVar(&f.tlsCommonPort, "tls-common-port", 0, "Port for the local TLSCommon gRPC server. The default value implies a random port selection.")
}
|
LucaCappelletti94/repairing_genomic_gaps
|
repairing_genomic_gaps/datasets/build_synthetic_dataset.py
|
import pandas as pd
from cache_decorator import Cache
from typing import List, Tuple, Dict
from ucsc_genomes_downloader import Genome
from tensorflow.keras.utils import Sequence
from ucsc_genomes_downloader.utils import tessellate_bed
from keras_synthetic_genome_sequence import SingleGapCenterSequence, SingleGapWindowsSequence
def build_synthetic_dataset_sequence(
window_size: int,
keras_sequence_class: Sequence,
chromosomes: List[str],
batch_size: int,
genome: Genome,
seed: int
):
"""Return given keras sequence class for training and testing.
Parameters
--------------------------
window_size: int,
Windows size to extend gaps to.
keras_sequence_class: Sequence,
The class of Sequence to use to build the train and test sequences.
chromosomes: List[str],
List of chromosomes to use.
batch_size: int
Batch size for training the model.
genome: Genome,
Genome object from which to retrieve the filled regions
for the given chromosomes.
seed: int,
Random seed to use when generating gaps.
Returns
---------------------------
Return Tuple of Sequences.
"""
# Rendering genomic gaps
return keras_sequence_class(
assembly=genome,
bed=tessellate_bed(genome.filled(
chromosomes=chromosomes
), window_size=window_size),
batch_size=batch_size,
seed=seed
)
def build_synthetic_dataset(
window_size: int,
keras_sequence_class: Sequence,
assembly: str = "hg19",
training_chromosomes: List[str] = (
"chr1", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8", "chr9",
"chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr19",
"chr20", "chr21", "chr22", "chrX", "chrY"
),
testing_chromosomes: List[str] = ("chr17", "chr18"),
batch_size: int = 1024,
seed: int = 42
) -> Tuple:
"""Return given keras sequence class for training and testing.
Parameters
--------------------------
window_size: int,
Windows size to extend gaps to.
keras_sequence_class: Sequence,
The class of Sequence to use to build the train and test sequences.
assembly: str,
Genomic assembly from which to extract sequences.
training_chromosomes: List[str],
List of chromosomes to use for training set.
testing_chromosomes: List[str],
List of chromosomes to use for test set.
batch_size: int
Batch size for training the model.
seed: int,
Random seed to use when generating gaps.
Returns
---------------------------
Return Tuple of Sequences.
"""
# Retrieving and loading the assembly for required chromosomes
genome = Genome(
assembly=assembly,
chromosomes=training_chromosomes+testing_chromosomes
)
training = build_synthetic_dataset_sequence(
window_size,
keras_sequence_class,
training_chromosomes,
batch_size,
genome,
seed
)
testing = build_synthetic_dataset_sequence(
window_size,
keras_sequence_class,
testing_chromosomes,
batch_size,
genome,
seed
)
return training, testing
@Cache()
def build_synthetic_dataset_cae(window_size:int, **kwargs:Dict)->Tuple[SingleGapWindowsSequence, SingleGapWindowsSequence]:
"""Return SingleGapWindowsSequence for training and testing.
Parameters
--------------------------
window_size: int,
Windows size to use for rendering the synthetic datasets.
"""
return build_synthetic_dataset(window_size, SingleGapWindowsSequence, **kwargs)
@Cache()
def build_synthetic_dataset_cnn(window_size:int, **kwargs:Dict)->Tuple[SingleGapCenterSequence, SingleGapCenterSequence]:
"""Return SingleGapCenterSequence for training and testing.
Parameters
--------------------------
window_size: int,
Windows size to use for rendering the synthetic datasets.
"""
return build_synthetic_dataset(window_size, SingleGapCenterSequence, **kwargs)
|
bopopescu/google-cloud-sdk
|
lib/googlecloudsdk/sql/sql.py
|
# Copyright 2013 Google Inc. All Rights Reserved.
"""This file can be executed directly to run the CLI or loaded as a module.
"""
import os
from googlecloudsdk.core import cli
_cli = cli.CLILoader(
name='sql',
command_root_directory=os.path.join(
cli.GoogleCloudSDKPackageRoot(),
'sql',
'tools')).Generate()
sql = _cli.EntryPoint()
def main():
_cli.Execute()
if __name__ == '__main__':
main()
|
albertofinardi/FINFO_1
|
11_15/3.c
|
<reponame>albertofinardi/FINFO_1<filename>11_15/3.c
/*
Scrivere un programma che apre in scrittura un file di testo il cui
nome, di al massimo 30 caratteri, è chiesto all'utente. In seguito,
il programma chiede all'utente quanti valori interi vuole acquisire
da tastiera, e poi procede con l'acquisizione da tastiera della
serie di numeri ed il loro salvataggio nel file.
*/
#include <stdio.h>
#define DIMSTR 30
int main(){
FILE *fp;
char filename[DIMSTR+1];
int i, max, curr;
scanf("%s", filename);
scanf("%d", &max);
fp = fopen(filename, "w");
if(fp){
for(i=0; i<max; i++){
scanf("%d", &curr);
fprintf(fp, "%d ", curr);
}
fclose(fp);
}else
printf("Errore apertura file\n");
return 0;
}
|
KamillaGarifullina/jsdk
|
uploader/build.cfg.js
|
export const uploader_build_cfg = [
{
in: './uploader/regular/index.js',
out: './uploader/build/regular/index.min.js',
minify: true,
minifyHtml: true,
},
{
in: './uploader/regular/index.css',
out: './uploader/build/regular/index.css',
minify: false,
},
{
in: './uploader/regular/index.css',
out: './uploader/build/regular/index.min.css',
minify: true,
},
];
|
timfel/netbeans
|
profiler/lib.profiler.ui/src/org/netbeans/lib/profiler/ui/cpu/LiveCPUViewUpdater.java
|
<filename>profiler/lib.profiler.ui/src/org/netbeans/lib/profiler/ui/cpu/LiveCPUViewUpdater.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 org.netbeans.lib.profiler.ui.cpu;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.lib.profiler.ProfilerClient;
import org.netbeans.lib.profiler.client.ClientUtils;
import org.netbeans.lib.profiler.results.RuntimeCCTNode;
import org.netbeans.lib.profiler.results.cpu.CPUCCTProvider;
import org.netbeans.lib.profiler.results.cpu.CPUResultsSnapshot;
import org.openide.util.Lookup;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author <NAME>
*/
public class LiveCPUViewUpdater {
private static final int MIN_UPDATE_DIFF = 900;
private static final int MAX_UPDATE_DIFF = 1400;
private CCTHandler handler;
private final LiveCPUView cpuView;
private final ProfilerClient client;
private volatile boolean paused;
private volatile boolean forceRefresh;
public LiveCPUViewUpdater(LiveCPUView cpuView, ProfilerClient client) {
this.cpuView = cpuView;
this.client = client;
handler = CCTHandler.registerUpdater(this);
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public void setForceRefresh(boolean forceRefresh) {
this.forceRefresh = forceRefresh;
}
public void update() throws ClientUtils.TargetAppOrVMTerminated {
if (forceRefresh || (!paused && cpuView.getLastUpdate() + MAX_UPDATE_DIFF < System.currentTimeMillis()))
client.forceObtainedResultsDump(true);
}
public void cleanup() {
handler.unregisterUpdater(this);
handler = null;
}
private void updateData() throws ClientUtils.TargetAppOrVMTerminated, CPUResultsSnapshot.NoDataAvailableException {
if (!forceRefresh && (paused || cpuView.getLastUpdate() + MIN_UPDATE_DIFF > System.currentTimeMillis())) return;
boolean sampling = client.getCurrentInstrType() == ProfilerClient.INSTR_NONE_SAMPLING;
CPUResultsSnapshot data = client.getStatus().getInstrMethodClasses() == null ?
null : client.getCPUProfilingResultsSnapshot(false);
cpuView.setData(data, sampling);
forceRefresh = false;
}
private void resetData() {
cpuView.resetData();
}
@ServiceProvider(service=CPUCCTProvider.Listener.class)
public static class CCTHandler implements CPUCCTProvider.Listener {
private final List<LiveCPUViewUpdater> updaters = new ArrayList();
public static CCTHandler registerUpdater(LiveCPUViewUpdater updater) {
CCTHandler handler = Lookup.getDefault().lookup(CCTHandler.class);
handler.updaters.add(updater);
return handler;
}
public void unregisterUpdater(LiveCPUViewUpdater updater) {
updaters.remove(updater);
}
public final void cctEstablished(RuntimeCCTNode appRootNode, boolean empty) {
if (!empty) {
for (LiveCPUViewUpdater updater : updaters) try {
updater.updateData();
} catch (ClientUtils.TargetAppOrVMTerminated ex) {
} catch (CPUResultsSnapshot.NoDataAvailableException ex) {
Logger.getLogger(LiveCPUView.class.getName()).log(Level.FINE, null, ex);
}
}
}
public final void cctReset() {
for (LiveCPUViewUpdater updater : updaters) updater.resetData();
}
}
}
|
wall3001/Ance
|
app/src/main/java/wall/field/investigation/mvp/model/entity/ScoreItem.java
|
package wall.field.investigation.mvp.model.entity;
/**
* 评分项
* Created by wall on 2018/6/20 10:16
* <EMAIL>
*/
public class ScoreItem {
public String scoreId;
public String scoreName;
public String scoreValue;
public String scoreSummary;
public String scoreState; //0:通过1:需修改2:待审核
public String checkStatus;//首查=0, 复查=1, 复查_已整改=2, 复查_未整改=3
}
|
akarnokd/reactive-streams-impl
|
src/main/java/com/github/akarnokd/rs/impl/ops/SkipUntil.java
|
/*
* Copyright 2011-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.github.akarnokd.rs.impl.ops;
import org.reactivestreams.*;
import com.github.akarnokd.rs.impl.res.FixedResourceContainer;
public final class SkipUntil<T, U> implements Publisher<T> {
final Publisher<? extends T> source;
final Publisher<U> other;
public SkipUntil(Publisher<? extends T> source, Publisher<U> other) {
this.source = source;
this.other = other;
}
@Override
public void subscribe(Subscriber<? super T> child) {
SerializedSubscriber<T> serial = new SerializedSubscriber<>(child);
FixedResourceContainer<Subscription> frc = new FixedResourceContainer<>(2, Subscription::cancel);
SkipUntilSubscriber<T> sus = new SkipUntilSubscriber<>(serial, frc);
other.subscribe(new Subscriber<U>() {
Subscription s;
@Override
public void onSubscribe(Subscription s) {
if (this.s != null) {
s.cancel();
new IllegalStateException("Subscription already set!").printStackTrace();
return;
}
this.s = s;
frc.setResource(1, s);
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(U t) {
s.cancel();
sus.notSkipping = true;
}
@Override
public void onError(Throwable t) {
frc.close();
serial.onError(t);
}
@Override
public void onComplete() {
sus.notSkipping = true;
}
});
source.subscribe(sus);
}
static final class SkipUntilSubscriber<T> implements Subscriber<T>, Subscription {
final Subscriber<? super T> actual;
final FixedResourceContainer<Subscription> frc;
Subscription s;
volatile boolean notSkipping;
boolean notSkippingLocal;
public SkipUntilSubscriber(Subscriber<? super T> actual, FixedResourceContainer<Subscription> frc) {
this.actual = actual;
this.frc = frc;
}
@Override
public void onSubscribe(Subscription s) {
if (this.s != null) {
s.cancel();
new IllegalStateException("Subscription already set!").printStackTrace();
return;
}
this.s = s;
frc.setResource(0, s);
actual.onSubscribe(this);
}
@Override
public void onNext(T t) {
if (notSkippingLocal) {
actual.onNext(t);
} else
if (notSkipping) {
notSkippingLocal = true;
actual.onNext(t);
} else {
s.request(1);
}
}
@Override
public void onError(Throwable t) {
frc.close();
actual.onError(t);
}
@Override
public void onComplete() {
frc.close();
actual.onComplete();
}
@Override
public void request(long n) {
s.request(n);
}
@Override
public void cancel() {
frc.close();
}
}
}
|
maulanayuseph/pikobar-jabarprov-go-id
|
api/vaksin.js
|
import { db } from '../lib/firebase'
function convertToJSON (documentSnapshot) {
const data = documentSnapshot.data()
return {
...data,
published_at: data.published_at.toDate(),
id: documentSnapshot.id
}
}
export async function get () {
const snapshots = await db
.collection('vaccination_content')
.orderBy('order', 'asc')
.get()
if (snapshots.empty) {
return []
}
return snapshots
.docs
/**
* Convert FirebaseFirestore.DocumentSnapshot to POJO
*/
.map(convertToJSON)
}
|
lacc97/media-driver
|
media_driver/agnostic/gen11/hw/mhw_vebox_g11_X.h
|
<gh_stars>1-10
/*
* Copyright (c) 2015-2018, Intel Corporation
*
* 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.
*/
//!
//! \file mhw_vebox_g11_X.h
//! \brief Defines functions for constructing vebox commands on Gen11-based platforms
#ifndef __MHW_VEBOX_G11_X_H__
#define __MHW_VEBOX_G11_X_H__
#include "mhw_vebox_generic.h"
#include "mhw_vebox_hwcmd_g11_X.h"
#define MHW_VEBOX_TIMESTAMP_PER_TICK_IN_NS_G11 83.333f
#if (_DEBUG || _RELEASE_INTERNAL)
#define MHW_VEBOX_IS_VEBOX_SPECIFIED_IN_CONFIG(keyval, VDId, shift, mask, bUseVD) \
do\
{\
int32_t TmpVal = keyval;\
while (TmpVal != 0) \
{\
if (((TmpVal) & (mask)) == (VDId))\
{\
bUseVD = true;\
break;\
}\
TmpVal >>= (shift);\
};\
}while(0)
#endif
const MHW_VEBOX_SETTINGS g_Vebox_Settings_g11 =
{
MHW_MAX_VEBOX_STATES, //!< uiNumInstances
MHW_SYNC_SIZE, //!< uiSyncSize
MHW_PAGE_SIZE, //!< uiDndiStateSize
MHW_PAGE_SIZE, //!< uiIecpStateSize
MHW_PAGE_SIZE * 2, //!< uiGamutStateSize
MHW_PAGE_SIZE, //!< uiVertexTableSize
MHW_PAGE_SIZE, //!< uiCapturePipeStateSize
MHW_PAGE_SIZE * 2, //!< uiGammaCorrectionStateSize
0 //!< ui3DLUTSize
};
class MhwVeboxInterfaceG11 : public MhwVeboxInterfaceGeneric<mhw_vebox_g11_X>
{
public:
// Chroma parameters
typedef struct _MHW_VEBOX_CHROMA_PARAMS
{
uint32_t dwPixRangeThresholdChromaU[MHW_PIXRANGETHRES_NUM];
uint32_t dwPixRangeWeightChromaU[MHW_PIXRANGETHRES_NUM];
uint32_t dwPixRangeThresholdChromaV[MHW_PIXRANGETHRES_NUM];
uint32_t dwPixRangeWeightChromaV[MHW_PIXRANGETHRES_NUM];
uint32_t dwHotPixelThresholdChromaU;
uint32_t dwHotPixelCountChromaU;
uint32_t dwHotPixelThresholdChromaV;
uint32_t dwHotPixelCountChromaV;
}MHW_VEBOX_CHROMA_PARAMS;
MhwVeboxInterfaceG11(
PMOS_INTERFACE pInputInterface);
virtual ~MhwVeboxInterfaceG11() { MHW_FUNCTION_ENTER; }
MOS_STATUS VeboxAdjustBoundary(
PMHW_VEBOX_SURFACE_PARAMS pSurfaceParam,
uint32_t *pdwSurfaceWidth,
uint32_t *pdwSurfaceHeight,
bool bDIEnable);
MOS_STATUS AddVeboxState(
PMOS_COMMAND_BUFFER pCmdBuffer,
PMHW_VEBOX_STATE_CMD_PARAMS pVeboxStateCmdParams,
bool bUseCmBuffer);
virtual MOS_STATUS AddVeboxDiIecp(
PMOS_COMMAND_BUFFER pCmdBuffer,
PMHW_VEBOX_DI_IECP_CMD_PARAMS pVeboxDiIecpCmdParams);
MOS_STATUS AddVeboxDndiState(
PMHW_VEBOX_DNDI_PARAMS pVeboxDndiParams);
MOS_STATUS AddVeboxIecpState(
PMHW_VEBOX_IECP_PARAMS pVeboxIecpParams);
MOS_STATUS AddVeboxGamutState(
PMHW_VEBOX_IECP_PARAMS pVeboxIecpParams,
PMHW_VEBOX_GAMUT_PARAMS pVeboxGamutParams);
MOS_STATUS FindVeboxGpuNodeToUse(
PMHW_VEBOX_GPUNODE_LIMIT pGpuNodeLimit);
MOS_STATUS AddVeboxIecpAceState(
PMHW_VEBOX_IECP_PARAMS pVeboxIecpParams);
MOS_STATUS SetVeboxIecpStateSTE(
mhw_vebox_g11_X::VEBOX_STD_STE_STATE_CMD *pVeboxStdSteState,
PMHW_COLORPIPE_PARAMS pColorPipeParams)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(pVeboxStdSteState);
MHW_CHK_NULL(pColorPipeParams);
MhwVeboxInterfaceGeneric<mhw_vebox_g11_X>::SetVeboxIecpStateSTE(pVeboxStdSteState, pColorPipeParams);
// Enable Skin Score Output surface to be written by Vebox
pVeboxStdSteState->DW1.StdScoreOutput = pColorPipeParams->bEnableLACE && pColorPipeParams->LaceParams.bSTD;
finish:
return eStatus;
}
//!
//! \brief Add VEBOX Scalar States for Gen10+
//! \details Add vebox scalar states
//! \param [in] pVeboxScalarParams
//! Pointer to VEBOX Scalar State Params
//! \return MOS_STATUS
//!
MOS_STATUS AddVeboxScalarState(
PMHW_VEBOX_SCALAR_PARAMS pVeboxScalarParams);
//!
//! \brief Set which vebox can be used by HW
//! \details VPHAL set whehter the VEBOX can be use by HW
//! \param [in] inputVebox0;
//! set whether Vebox0 can be used by HW
//! \param [in] inputVebox01;
//! set whether vebox1 can be use by HW
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
MOS_STATUS SetVeboxInUse(
bool inputVebox0,
bool inputVebox1);
//!
//! \brief Set which vebox can be used by DNDI
//! \details VPHAL set Chroma parameters can be use by DNDI
//! \param [in] chromaParams;
//! Chroma parameters which will be used by DNDI
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
MOS_STATUS SetVeboxChromaParams(
MHW_VEBOX_CHROMA_PARAMS *chromaParams);
//! \brief get the status for vebox's Scalability.
//! \details VPHAL will check whether the veobx support Scalabiltiy.
//! \return bool
//! false or true
bool IsScalabilitySupported();
virtual MOS_STATUS AddVeboxSurfaceControlBits(
PMHW_VEBOX_SURFACE_CNTL_PARAMS pVeboxSurfCntlParams,
uint32_t *pSurfCtrlBits);
//!
//! \brief Create Gpu Context for Vebox
//! \details Create Gpu Context for Vebox
//! \param [in] pOsInterface
//! OS interface
//! \param [in] VeboxGpuContext
//! Vebox Gpu Context
//! \param [in] VeboxGpuNode
//! Vebox Gpu Node
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS CreateGpuContext(
PMOS_INTERFACE pOsInterface,
MOS_GPU_CONTEXT VeboxGpuContext,
MOS_GPU_NODE VeboxGpuNode);
virtual MOS_STATUS AdjustBoundary(
PMHW_VEBOX_SURFACE_PARAMS pSurfaceParam,
uint32_t *pdwSurfaceWidth,
uint32_t *pdwSurfaceHeight,
bool bDIEnable);
private:
uint32_t m_BT2020InvPixelValue[256];
uint32_t m_BT2020FwdPixelValue[256];
uint32_t m_BT2020InvGammaLUT[256];
uint32_t m_BT2020FwdGammaLUT[256];
bool m_vebox0InUse;
bool m_vebox1InUse;
bool m_veboxScalabilitySupported;
uint32_t m_veboxSplitRatio;
MHW_VEBOX_CHROMA_PARAMS m_chromaParams;
//!
//! \brief Set Vebox Iecp State Back-End CSC
//! \details Set Back-End CSC part of the VEBOX IECP States
//! \param [in] pVeboxIecpState
//! Pointer to VEBOX IECP States
//! \param [in] pVeboxIecpParams
//! Pointer to VEBOX IECP State Params
//! \param [in] bEnableFECSC
//! Flag to enable FECSC
//! \return void
//!
void SetVeboxIecpStateBecsc(
mhw_vebox_g11_X::VEBOX_IECP_STATE_CMD *pVeboxIecpState,
PMHW_VEBOX_IECP_PARAMS pVeboxIecpParams,
bool bEnableFECSC);
//!
//! \brief Manual mode H2S
//! \details Manual mode H2S
// Based on WW23'16 algorithm design.
//! \param [in] pVeboxIecpParams
//! Pointer to VEBOX IECP State Params
//! \param [in] pVeboxGamutParams
//! Pointer to VEBOX Gamut State Params
//! \return MOS_STATUS
//!
MOS_STATUS VeboxInterface_H2SManualMode(
PMHW_VEBOX_HEAP pVeboxHeapInput,
PMHW_VEBOX_IECP_PARAMS pVeboxIecpParams,
PMHW_VEBOX_GAMUT_PARAMS pVeboxGamutParams);
//!
//! \brief Back end CSC setting, BT2020 YUV Full/Limited to BT2020 RGB Full (G10 +)
//! \details Back end CSC setting, BT2020 YUV Full/Limited to BT2020 RGB Full
//! \param [in] pVeboxIecpParams
//! Pointer to VEBOX IECP State Params
//! \param [in] pVeboxGamutParams
//! Pointer to VEBOX Gamut State Params
//! \return MOS_STATUS
//!
MOS_STATUS VeboxInterface_BT2020YUVToRGB(
PMHW_VEBOX_HEAP pVeboxHeapInput,
PMHW_VEBOX_IECP_PARAMS pVeboxIecpParams,
PMHW_VEBOX_GAMUT_PARAMS pVeboxGamutParams);
//!
//! \brief init VEBOX IECP States
//! \details init Vebox IECP states STD/E, ACE, TCC, Gamut
//! \param [in] pVeboxIecpStateCmd
//! Pointer to Vebox Interface Structure
//! \return viod
//!
void IecpStateInitialization(
mhw_vebox_g11_X::VEBOX_IECP_STATE_CMD *pVeboxIecpState);
#if (_DEBUG || _RELEASE_INTERNAL)
MOS_STATUS ValidateVeboxScalabilityConfig();
#endif
void SetVeboxSurfaces(
PMHW_VEBOX_SURFACE_PARAMS pSurfaceParam,
PMHW_VEBOX_SURFACE_PARAMS pDerivedSurfaceParam,
PMHW_VEBOX_SURFACE_PARAMS pSkinScoreSurfaceParam,
mhw_vebox_g11_X::VEBOX_SURFACE_STATE_CMD *pVeboxSurfaceState,
bool bIsOutputSurface,
bool bDIEnable);
};
#endif
|
ytsarev/rally
|
rally/benchmark/scenarios/nova/servers.py
|
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
import jsonschema
import random
from rally.benchmark.context import cleaner as context_cleaner
from rally.benchmark.scenarios import base
from rally.benchmark.scenarios.cinder import utils as cinder_utils
from rally.benchmark.scenarios.nova import utils
from rally.benchmark.scenarios import utils as scenario_utils
from rally.benchmark import validation as valid
from rally import exceptions as rally_exceptions
from rally.openstack.common.gettextutils import _ # noqa
from rally.openstack.common import log as logging
from rally import sshutils
LOG = logging.getLogger(__name__)
class NovaServers(utils.NovaScenario,
cinder_utils.CinderScenario):
def __init__(self, *args, **kwargs):
super(NovaServers, self).__init__(*args, **kwargs)
@context_cleaner.cleanup(['nova'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def boot_and_list_server(self, image_id, flavor_id,
detailed=True, **kwargs):
"""Tests booting an image and then listing servers.
This scenario is a very useful tool to measure
the "nova list" command performance.
If you have only 1 user in your context, you will
add 1 server on every iteration. So you will have more
and more servers and will be able to measure the
performance of the "nova list" command depending on
the number of servers owned by users.
"""
server_name = self._generate_random_name(16)
self._boot_server(server_name, image_id, flavor_id, **kwargs)
self._list_servers(detailed)
@context_cleaner.cleanup(['nova'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def boot_and_delete_server(self, image_id, flavor_id,
min_sleep=0, max_sleep=0, **kwargs):
"""Tests booting and then deleting an image."""
server_name = self._generate_random_name(16)
server = self._boot_server(server_name, image_id, flavor_id, **kwargs)
self.sleep_between(min_sleep, max_sleep)
self._delete_server(server)
@context_cleaner.cleanup(['nova', 'cinder'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def boot_server_from_volume_and_delete(self, image_id, flavor_id,
volume_size,
min_sleep=0, max_sleep=0, **kwargs):
"""Tests booting from volume and then deleting an image and volume."""
server_name = self._generate_random_name(16)
volume = self._create_volume(volume_size, imageRef=image_id)
block_device_mapping = {'vda': '%s:::1' % volume.id}
server = self._boot_server(server_name, image_id, flavor_id,
block_device_mapping=block_device_mapping,
**kwargs)
self.sleep_between(min_sleep, max_sleep)
self._delete_server(server)
@context_cleaner.cleanup(['nova'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def boot_runcommand_delete_server(self, image_id, flavor_id,
script, interpreter, network='private',
username='ubuntu', ip_version=4,
retries=60, port=22, **kwargs):
"""Boot server, run a script that outputs JSON, delete server.
Parameters:
script: script to run on the server, must output JSON mapping metric
names to values. See sample script below.
network: Network to choose address to connect to instance from
username: User to SSH to instance as
ip_version: Version of ip protocol to use for connection
returns: Dictionary containing two keys, data and errors. Data is JSON
data output by the script. Errors is raw data from the
script's standard error stream.
Example Script in doc/samples/support/instance_dd_test.sh
"""
server_name = self._generate_random_name(16)
server = self._boot_server(server_name, image_id, flavor_id,
key_name='rally_ssh_key', **kwargs)
if network not in server.addresses:
raise ValueError(
"Can't find cloud network %(network)s, so cannot boot "
"instance for Rally scenario boot-runcommand-delete. "
"Available networks: %(networks)s" % (
dict(network=network,
networks=server.addresses.keys()
)
)
)
server_ip = [ip for ip in server.addresses[network] if
ip["version"] == ip_version][0]["addr"]
ssh = sshutils.SSH(username, server_ip, port=port,
pkey=self.context()["user"]["keypair"]["private"])
ssh.wait()
code, out, err = ssh.execute(interpreter, stdin=open(script, "rb"))
if code:
LOG.error(_("Error running script on instance via SSH. "
"Error: %s") % err)
try:
out = json.loads(out)
except ValueError:
LOG.warning(_("Script %s did not output valid JSON.") % script)
self._delete_server(server)
LOG.debug(_("Output streams from in-instance script execution: "
"stdout: %(stdout)s, stderr: $(stderr)s") % dict(
stdout=out, stderr=err))
return {"data": out, "errors": err}
@context_cleaner.cleanup(['nova'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def boot_and_bounce_server(self, image_id, flavor_id, **kwargs):
"""Tests booting a server then performing stop/start or hard/soft
reboot a number of times.
"""
action_builder = self._bind_actions()
actions = kwargs.get('actions', [])
try:
action_builder.validate(actions)
except jsonschema.exceptions.ValidationError as error:
raise rally_exceptions.InvalidConfigException(
"Invalid server actions configuration \'%(actions)s\' due to: "
"%(error)s" % {'actions': str(actions), 'error': str(error)})
server = self._boot_server(self._generate_random_name(16),
image_id, flavor_id, **kwargs)
for action in action_builder.build_actions(actions, server):
action()
self._delete_server(server)
@context_cleaner.cleanup(['nova', 'glance'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def snapshot_server(self, image_id, flavor_id, **kwargs):
"""Tests Nova instance snapshotting."""
server_name = self._generate_random_name(16)
server = self._boot_server(server_name, image_id, flavor_id, **kwargs)
image = self._create_image(server)
self._delete_server(server)
server = self._boot_server(server_name, image.id, flavor_id, **kwargs)
self._delete_server(server)
self._delete_image(image)
@context_cleaner.cleanup(['nova'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def boot_server(self, image_id, flavor_id, **kwargs):
"""Test VM boot - assumed clean-up is done elsewhere."""
server_name = self._generate_random_name(16)
if 'nics' not in kwargs:
nets = self.clients("nova").networks.list()
if nets:
random_nic = random.choice(nets)
kwargs['nics'] = [{'net-id': random_nic.id}]
self._boot_server(server_name, image_id, flavor_id, **kwargs)
@context_cleaner.cleanup(['nova', 'cinder'])
@valid.add_validator(valid.image_valid_on_flavor("flavor_id", "image_id"))
@base.scenario()
def boot_server_from_volume(self, image_id, flavor_id,
volume_size, **kwargs):
"""Test VM boot from volume - assumed clean-up is done elsewhere."""
server_name = self._generate_random_name(16)
if 'nics' not in kwargs:
nets = self.clients("nova").networks.list()
if nets:
random_nic = random.choice(nets)
kwargs['nics'] = [{'net-id': random_nic.id}]
volume = self._create_volume(volume_size, imageRef=image_id)
block_device_mapping = {'vda': '%s:::1' % volume.id}
self._boot_server(server_name, image_id, flavor_id,
block_device_mapping=block_device_mapping,
**kwargs)
def _bind_actions(self):
actions = ['hard_reboot', 'soft_reboot', 'stop_start',
'rescue_unrescue']
action_builder = scenario_utils.ActionBuilder(actions)
action_builder.bind_action('hard_reboot', self._reboot_server,
soft=False)
action_builder.bind_action('soft_reboot', self._reboot_server,
soft=True)
action_builder.bind_action('stop_start',
self._stop_and_start_server)
action_builder.bind_action('rescue_unrescue',
self._rescue_and_unrescue_server)
return action_builder
def _stop_and_start_server(self, server):
"""Stop and then start the given server.
A stop will be issued on the given server upon which time
this method will wait for the server to become 'SHUTOFF'.
Once the server is SHUTOFF a start will be issued and this
method will wait for the server to become 'ACTIVE' again.
:param server: The server to stop and then start.
"""
self._stop_server(server)
self._start_server(server)
def _rescue_and_unrescue_server(self, server):
"""Rescue and then unrescue the given server.
A rescue will be issued on the given server upon which time
this method will wait for the server to become 'RESCUE'.
Once the server is RESCUE a unrescue will be issued and
this method will wait for the server to become 'ACTIVE'
again.
:param server: The server to rescue and then unrescue.
"""
self._rescue_server(server)
self._unrescue_server(server)
|
electronicvisions/pyplusplus
|
unittests/data/ft_input_static_matrix_to_be_exported.hpp
|
<reponame>electronicvisions/pyplusplus<gh_stars>1-10
// Copyright 2004-2008 <NAME>.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef __ft_input_static_matrix_to_be_exported_hpp__
#define __ft_input_static_matrix_to_be_exported_hpp__
#include <cmath>
#include <string>
#include <iostream>
namespace ft{
template< int rows, int columns >
int sum_impl( const int m[rows][columns] ){
int result = 0;
for( int r = 0; r < rows; ++r ){
for( int c = 0; c < columns; ++c ){
result += m[r][c];
}
}
return result;
}
int sum( int m[2][3]){
return sum_impl<2, 3>( m );
}
int sum_const( int m[2][3]){
return sum_impl<2, 3>( m );
}
struct matrix_sum_t{
virtual int calculate( const int m[3][5] ) const{
return sum_impl<3,5>( m );
}
};
}
#endif//__ft_input_static_matrix_to_be_exported_hpp__
|
nancyanand2807/algorithm-ds
|
spoj/2727.cpp
|
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mp make_pair
#define pb push_back
int main() {
int t; cin>>t;
while(t--){
// char s; cin>>s;
int n,m; cin>>n>>m;
vector<int> ng,nm;
for(int i=0; i<n; i++){
int t; cin>>t;
ng.pb(t);
}
for(int i=0; i<m; i++){
int t; cin>>t;
nm.pb(t);
}
sort(ng.begin(),ng.end());
sort(nm.begin(),nm.end());
while(!ng.empty() and !nm.empty()){
ng.back()<nm.back() ? ng.pop_back(): nm.pop_back();
}
if(nm.empty()){
cout<<"Godzilla\n";
}
else {
cout<<"MechaGodzilla\n";
}
}
return 0;
}
|
sergkh/api-gateway
|
app/forms/UserPermissionForm.scala
|
<filename>app/forms/UserPermissionForm.scala
package forms
import models.RolePermissions
import play.api.data.Forms._
import play.api.data._
import FormConstraints._
object UserPermissionForm {
val createForm = Form(
mapping(
"role" -> role,
"permissions" -> list(permission)
)(RolePermissions.apply)(RolePermissions.unapply)
)
val updateForm = Form(single("permissions" -> list(permission)))
}
|
Ehnryu/archives
|
games/RouglikeS/src/js/entity.js
|
<reponame>Ehnryu/archives
export const BLOCKS_NONE = 0;
export const BLOCKS_MOVEMENT = 1;
export const BLOCKS_LIGHT = 2;
export default class Entity {
constructor(visual) {
this._visual = visual;
this.blocks = BLOCKS_NONE;
}
getVisual() { return this._visual; }
toString() { return this._visual.name; }
describeThe() { return `the ${this}`; }
describeA() {
let first = this._visual.name.charAt(0);
let article = (first.match(/[aeiou]/i) ? "an" : "a");
return `${article} ${this}`;
}
}
String.format.map.the = "describeThe";
String.format.map.a = "describeA";
|
ckcsu-web-2-0/ckcsu-web-2.0
|
node_modules/swig-templates/lib/tags/import.js
|
<reponame>ckcsu-web-2-0/ckcsu-web-2.0<filename>node_modules/swig-templates/lib/tags/import.js
var utils = require('../utils')
/**
* Allows you to import macros from another file directly into your current context.
* The import tag is specifically designed for importing macros into your template with a specific context scope. This is very useful for keeping your macros from overriding template context that is being injected by your server-side page generation.
*
* @alias import
*
* @example
* {% import './formmacros.html' as form %}
* {{ form.input("text", "name") }}
* // => <input type="text" name="name">
*
* @example
* {% import "../shared/tags.html" as tags %}
* {{ tags.stylesheet('global') }}
* // => <link rel="stylesheet" href="/global.css">
*
* @param {string|var} file Relative path from the current template file to the file to import macros from.
* @param {literal} as Literally, "as".
* @param {literal} varname Local-accessible object name to assign the macros to.
*/
exports.compile = function (compiler, args) {
var ctx = args.pop()
var allMacros = utils
.map(args, function (arg) {
return arg.name
})
.join('|')
var out = '_ctx.' + ctx + ' = {};\n var _output = "";\n'
var replacements = utils.map(args, function (arg) {
return {
ex: new RegExp('_ctx.' + arg.name + '(\\W)(?!' + allMacros + ')', 'g'),
re: '_ctx.' + ctx + '.' + arg.name + '$1'
}
})
// Replace all occurrences of all macros in this file with
// proper namespaced definitions and calls
utils.each(args, function (arg) {
var c = arg.compiled
utils.each(replacements, function (re) {
c = c.replace(re.ex, re.re)
})
out += c
})
return out
}
exports.parse = function (str, line, parser, types, stack, opts, swig) {
var compiler = require('../parser').compile
var parseOpts = { resolveFrom: opts.filename }
var compileOpts = utils.extend({}, opts, parseOpts)
var tokens
var ctx
parser.on(types.STRING, function (token) {
var self = this
if (!tokens) {
tokens = swig.parseFile(
token.match.replace(/^("|')|("|')$/g, ''),
parseOpts
).tokens
utils.each(tokens, function (token) {
var out = ''
var macroName
if (!token || token.name !== 'macro' || !token.compile) {
return
}
macroName = token.args[0]
out +=
token.compile(compiler, token.args, token.content, [], compileOpts) +
'\n'
self.out.push({ compiled: out, name: macroName })
})
return
}
throw new Error(
'Unexpected string ' + token.match + ' on line ' + line + '.'
)
})
parser.on(types.VAR, function (token) {
var self = this
if (!tokens || ctx) {
throw new Error(
'Unexpected variable "' + token.match + '" on line ' + line + '.'
)
}
if (token.match === 'as') {
return
}
ctx = token.match
self.out.push(ctx)
return false
})
return true
}
exports.block = true
|
alonbltest/wix-style-react
|
src/LabelledElement/LabelledElement.meta.js
|
import LabelledElement from './LabelledElement';
import Registry from '@ui-autotools/registry';
const metadata = Registry.getComponentMetadata(LabelledElement);
metadata.exportedFrom({
path: 'src/LabelledElement/LabelledElement.js',
});
|
nistefan/cmssw
|
CalibFormats/SiPixelObjects/src/PixelFEDConfig.cc
|
//
// This class stores the information about a FED.
// This include the number, crate, and base address
//
//
#include "CalibFormats/SiPixelObjects/interface/PixelFEDConfig.h"
#include "CalibFormats/SiPixelObjects/interface/PixelTimeFormatter.h"
#include <fstream>
#include <iostream>
#include <map>
#include <cassert>
#include <stdexcept>
using namespace pos;
using namespace std;
PixelFEDConfig::PixelFEDConfig(std::vector<std::vector<std::string> >& tableMat ) : PixelConfigBase(" "," "," "){
std::string mthn = "[PixelFEDConfig::PixelFEDConfig()]\t\t\t " ;
std::vector< std::string > ins = tableMat[0];
std::map<std::string , int > colM;
std::vector<std::string > colNames;
/*
EXTENSION_TABLE_NAME: FED_CRATE_CONFIG (VIEW: CONF_KEY_FED_CRATE_CONFIGV)
CONFIG_KEY NOT NULL VARCHAR2(80)
KEY_TYPE NOT NULL VARCHAR2(80)
KEY_ALIAS NOT NULL VARCHAR2(80)
VERSION VARCHAR2(40)
KIND_OF_COND NOT NULL VARCHAR2(40)
PIXEL_FED NOT NULL NUMBER(38)
CRATE_NUMBER NOT NULL NUMBER(38)
VME_ADDR NOT NULL VARCHAR2(200)
*/
colNames.push_back("CONFIG_KEY" );
colNames.push_back("KEY_TYPE" );
colNames.push_back("KEY_ALIAS" );
colNames.push_back("VERSION" );
colNames.push_back("KIND_OF_COND" );
colNames.push_back("PIXEL_FED" );
colNames.push_back("CRATE_NUMBER" );
colNames.push_back("VME_ADDR" );
/*
colNames.push_back("PIXEL_FED" ); //0
colNames.push_back("CRATE_NUMBER" ); //1
colNames.push_back("VME_ADDRS_HEX"); //2
*/
for(unsigned int c = 0 ; c < tableMat[0].size() ; c++)
{
for(unsigned int n=0; n<colNames.size(); n++)
{
if(tableMat[0][c] == colNames[n])
{
colM[colNames[n]] = c;
break;
}
}
}//end for
/*
for(unsigned int n=0; n<colNames.size(); n++)
{
if(colM.find(colNames[n]) == colM.end())
{
std::cerr << __LINE__ << "]\t" << mthn << "Couldn't find in the database the column with name " << colNames[n] << std::endl;
assert(0);
}
}
*/
std::string fedname = "";
unsigned int fednum = 0;
fedconfig_.clear();
bool flag = false;
for(unsigned int r = 1 ; r < tableMat.size() ; r++){ //Goes to every row of the Matrix
fedname = tableMat[r][colM["PIXEL_FED"]]; //This is not going to work if you change in the database "PxlFed_#" in the FED column.Im removing "PlxFed_" and store the number
//becuase the PixelFecConfig class ask for the fec number not the name.
// 01234567
// PxlFED_XX
// fedname.erase(0,7);
fednum = (unsigned int)atoi(fedname.c_str()) ;
if(fedconfig_.empty())
{
PixelFEDParameters tmp;
unsigned int vme_base_address = 0 ;
vme_base_address = strtoul(tableMat[r][colM["VME_ADDR"]].c_str(), nullptr, 16);
// string hexVMEAddr = tableMat[r][colM["VME_ADDRS_HEX"]] ;
// sscanf(hexVMEAddr.c_str(), "%x", &vme_base_address) ;
tmp.setFEDParameters( fednum, (unsigned int)atoi(tableMat[r][colM["CRATE_NUMBER"]].c_str()) ,
vme_base_address);
fedconfig_.push_back(tmp);
}
else
{
for( unsigned int y = 0; y < fedconfig_.size() ; y++)
{
if (fedconfig_[y].getFEDNumber() == fednum) // This is to check if there are Pixel Feds already in the vector because
{ // in the view of the database that I'm reading there are many repeated entries (AS FAR AS THESE PARAMS ARE CONCERNED).
flag = true; // This ensure that there are no objects in the fedconfig vector with repeated values.
break;
}
else flag = false;
}
if(flag == false)
{
PixelFEDParameters tmp;
tmp.setFEDParameters( fednum, (unsigned int)atoi(tableMat[r][colM["CRATE_NUMBER"]].c_str()) ,
(unsigned int)strtoul(tableMat[r][colM["VME_ADDR"]].c_str(), nullptr, 16));
fedconfig_.push_back(tmp);
}
}//end else
}//end for r
/*
std::cout << __LINE__ << "]\t" << mthn << std::endl;
for( unsigned int x = 0 ; x < fedconfig_.size() ; x++)
{
std::cout<< __LINE__ << "]\t" << mthn << fedconfig_[x] << std::endl;
}
std::cout<< __LINE__ << "]\t" << mthn << fedconfig_.size() << std::endl;
*/
}//end Constructor
//*****************************************************************************************************
PixelFEDConfig::PixelFEDConfig(std::string filename):
PixelConfigBase(" "," "," "){
std::string mthn = "[PixelFEDConfig::PixelFEDConfig()]\t\t\t " ;
std::ifstream in(filename.c_str());
if (!in.good()){
std::cout << __LINE__ << "]\t" << mthn << "Could not open: " << filename.c_str() << std::endl;
throw std::runtime_error("Failed to open file "+filename);
}
else {
std::cout << __LINE__ << "]\t" << mthn << "Opened: " << filename.c_str() << std::endl;
}
std::string dummy;
in >> dummy;
in >> dummy;
in >> dummy;
in >> dummy;
in >> dummy;
in >> dummy;
do {
unsigned int fednumber;
unsigned int crate;
unsigned int vme_base_address;
in >> fednumber >> crate >> std::hex >> vme_base_address >> std::dec;
if (!in.eof() ){
// std::cout << __LINE__ << "]\t" << mthn << std::dec << fednumber <<" "<< crate << " 0x"
// << std::hex << vme_base_address<<std::dec<<std::endl;
PixelFEDParameters tmp;
tmp.setFEDParameters(fednumber , crate , vme_base_address);
fedconfig_.push_back(tmp);
}
}
while (!in.eof());
in.close();
}
//std::ostream& operator<<(std::ostream& s, const PixelFEDConfig& table){
//for (unsigned int i=0;i<table.translationtable_.size();i++){
// s << table.translationtable_[i]<<std::endl;
// }
// return s;
//}
PixelFEDConfig::~PixelFEDConfig() {}
void PixelFEDConfig::writeASCII(std::string dir) const {
std::string mthn = "[PixelFEDConfig::writeASCII()]\t\t\t\t " ;
if (dir!="") dir+="/";
string filename=dir+"fedconfig.dat";
ofstream out(filename.c_str());
if(!out.good()){
cout << __LINE__ << "]\t" << mthn << "Could not open file: " << filename << endl;
assert(0);
}
out <<" #FED number crate vme base address" <<endl;
for(unsigned int i=0;i<fedconfig_.size();i++){
out << fedconfig_[i].getFEDNumber()<<" "
<< fedconfig_[i].getCrate()<<" "
<< "0x"<<hex<<fedconfig_[i].getVMEBaseAddress()<<dec<<endl;
}
out.close();
}
unsigned int PixelFEDConfig::getNFEDBoards() const{
return fedconfig_.size();
}
unsigned int PixelFEDConfig::getFEDNumber(unsigned int i) const{
assert(i<fedconfig_.size());
return fedconfig_[i].getFEDNumber();
}
unsigned int PixelFEDConfig::getCrate(unsigned int i) const{
assert(i<fedconfig_.size());
return fedconfig_[i].getCrate();
}
unsigned int PixelFEDConfig::getVMEBaseAddress(unsigned int i) const{
assert(i<fedconfig_.size());
return fedconfig_[i].getVMEBaseAddress();
}
unsigned int PixelFEDConfig::crateFromFEDNumber(unsigned int fednumber) const{
std::string mthn = "[PixelFEDConfig::crateFromFEDNumber()]\t\t\t " ;
for(unsigned int i=0;i<fedconfig_.size();i++){
if (fedconfig_[i].getFEDNumber()==fednumber) return fedconfig_[i].getCrate();
}
std::cout << __LINE__ << "]\t" << mthn << "Could not find FED number: " << fednumber << std::endl;
assert(0);
return 0;
}
unsigned int PixelFEDConfig::VMEBaseAddressFromFEDNumber(unsigned int fednumber) const{
std::string mthn = "[PixelFEDConfig::VMEBaseAddressFromFEDNumber()]\t\t " ;
for(unsigned int i=0;i<fedconfig_.size();i++){
if (fedconfig_[i].getFEDNumber()==fednumber) return fedconfig_[i].getVMEBaseAddress();
}
std::cout << __LINE__ << "]\t" << mthn << "Could not find FED number: " << fednumber << std::endl;
assert(0);
return 0;
}
unsigned int PixelFEDConfig::FEDNumberFromCrateAndVMEBaseAddress(unsigned int crate, unsigned int vmebaseaddress) const {
std::string mthn = "[PixelFEDConfig::FEDNumberFromCrateAndVMEBaseAddress()]\t " ;
for(unsigned int i=0;i<fedconfig_.size();i++){
if (fedconfig_[i].getCrate()==crate&&
fedconfig_[i].getVMEBaseAddress()==vmebaseaddress) return fedconfig_[i].getFEDNumber();
}
std::cout << __LINE__ << "]\t" << mthn << "Could not find FED crate and address: "<< crate << ", " << vmebaseaddress << std::endl;
assert(0);
return 0;
}
//=============================================================================================
void PixelFEDConfig::writeXMLHeader(pos::PixelConfigKey key,
int version,
std::string path,
std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "[PixelFEDConfig::::writeXMLHeader()]\t\t\t " ;
std::stringstream fullPath ;
fullPath << path << "/Pixel_FedCrateConfig_" << PixelTimeFormatter::getmSecTime() << ".xml" ;
cout << __LINE__ << "]\t" << mthn << "Writing to: " << fullPath.str() << endl ;
outstream->open(fullPath.str().c_str()) ;
*outstream << "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" << endl ;
*outstream << "<ROOT xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" << endl ;
*outstream << " <HEADER>" << endl ;
*outstream << " <TYPE>" << endl ;
*outstream << " <EXTENSION_TABLE_NAME>FED_CRATE_CONFIG</EXTENSION_TABLE_NAME>" << endl ;
*outstream << " <NAME>Pixel FED Crate Configuration</NAME>" << endl ;
*outstream << " </TYPE>" << endl ;
*outstream << " <RUN>" << endl ;
*outstream << " <RUN_NAME>Pixel FED Crate Configuration</RUN_NAME>" << endl ;
*outstream << " <RUN_BEGIN_TIMESTAMP>" << pos::PixelTimeFormatter::getTime() << "</RUN_BEGIN_TIMESTAMP>" << endl ;
*outstream << " <LOCATION>CERN P5</LOCATION>" << endl ;
*outstream << " </RUN>" << endl ;
*outstream << " </HEADER>" << endl ;
*outstream << " " << endl ;
*outstream << " <DATA_SET>" << endl ;
*outstream << " <PART>" << endl ;
*outstream << " <NAME_LABEL>CMS-PIXEL-ROOT</NAME_LABEL>" << endl ;
*outstream << " <KIND_OF_PART>Detector ROOT</KIND_OF_PART>" << endl ;
*outstream << " </PART>" << endl ;
*outstream << " <VERSION>" << version << "</VERSION>" << endl ;
*outstream << " <COMMENT_DESCRIPTION>" << getComment() << "</COMMENT_DESCRIPTION>" << endl ;
*outstream << " <CREATED_BY_USER>" << getAuthor() << "</CREATED_BY_USER>" << endl ;
*outstream << " " << endl ;
}
//=============================================================================================
void PixelFEDConfig::writeXML(std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "[PixelFEDConfig::writeXML()]\t\t\t " ;
for(unsigned int i=0;i<fedconfig_.size();i++){
*outstream << " <DATA>" << endl ;
*outstream << " <PIXEL_FED>" << fedconfig_[i].getFEDNumber() << "</PIXEL_FED>" << endl ;
*outstream << " <CRATE_NUMBER>" << fedconfig_[i].getCrate() << "</CRATE_NUMBER>" << endl ;
*outstream << " <VME_ADDR>" << "0x" << hex << fedconfig_[i].getVMEBaseAddress() << dec << "</VME_ADDR>" << endl ;
*outstream << " </DATA>" << endl ;
*outstream << "" << endl ;
}
}
//=============================================================================================
void PixelFEDConfig::writeXMLTrailer(std::ofstream *outstream,
std::ofstream *out1stream,
std::ofstream *out2stream) const
{
std::string mthn = "[PixelFEDConfig::writeXMLTrailer()]\t\t\t " ;
*outstream << " </DATA_SET>" << endl ;
*outstream << "</ROOT> " << endl ;
outstream->close() ;
}
|
SpruceHealth/ReactiveCocoa
|
ReactiveCocoaFramework/ReactiveCocoa/NSString+RACSupport.h
|
<reponame>SpruceHealth/ReactiveCocoa
//
// NSString+RACSupport.h
// ReactiveCocoa
//
// Created by <NAME> on 5/11/12.
// Copyright (c) 2012 GitHub, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "RACDeprecated.h"
@class RACScheduler;
@class RACSequence;
@class RACSignal;
@interface NSString (RACSupport)
/// Enumerates substrings in the receiver.
///
/// Mutating the string will not affect the signal after it's been created.
///
/// range - The range to enumerate over.
/// options - Options specifying types of substrings and enumeration styles.
///
/// Returns a signal which will send tuples of three values: the substring, the
/// `NSRange` of the substring, and the "enclosing range" of the substring
/// (which includes separator or filler characters).
- (RACSignal *)rac_substringsInRange:(NSRange)range options:(NSStringEnumerationOptions)options;
// Reads in the contents of the given URL using +[NSString
// stringWithContentsOfURL:usedEncoding:error:].
//
// Returns a signal which will send a tuple containing the `NSString` of the
// URL's content, and an `NSNumber`-boxed `NSStringEncoding` indicating the
// encoding used to read it, then complete.
+ (RACSignal *)rac_contentsAndEncodingOfURL:(NSURL *)URL;
@end
@interface NSString (RACSupportDeprecated)
@property (nonatomic, copy, readonly) RACSequence *rac_sequence RACDeprecated("Use -rac_substringsInRange:options: instead");
+ (RACSignal *)rac_readContentsOfURL:(NSURL *)URL usedEncoding:(NSStringEncoding *)encoding scheduler:(RACScheduler *)scheduler RACDeprecated("Use +rac_contentsAndEncodingOfURL: instead");
@end
|
nymanjens/musik
|
app/js/shared/src/main/scala/hydro/flux/react/uielements/input/InputBase.scala
|
<reponame>nymanjens/musik
package hydro.flux.react.uielements.input
import japgolly.scalajs.react._
import org.scalajs.dom.console
/**
* Contains base traits to be used by input components that describe a single value.
*
* Aggregate input values are not supported.
*/
object InputBase {
/** A reference to an input component. */
trait Reference[Value] {
def apply(): Proxy[Value]
}
/** Proxy that allows client code of an input component to interact with its value. */
trait Proxy[Value] {
/** Returns the current value or None if this field is invalidly formatted. */
def value: Option[Value]
/** Returns the current value or the default if this field is invalidly formatted. */
def valueOrDefault: Value
/**
* Sets the value of the input component and returns the value after this change.
*
* The return value may be different from the input if the input is invalid for this
* field.
*/
def setValue(value: Value): Value
final def valueIsValid: Boolean = value.isDefined
/** Focuses the input field. */
def focus(): Unit = {
console.log("focus() not implemented")
throw new UnsupportedOperationException()
}
def registerListener(listener: Listener[Value]): Unit
def deregisterListener(listener: Listener[Value]): Unit
}
object Proxy {
def nullObject[Value](): Proxy[Value] = new NullObject
private final class NullObject[Value]() extends Proxy[Value] {
override def value = None
override def valueOrDefault = null.asInstanceOf[Value]
override def setValue(value: Value) = value
override def registerListener(listener: Listener[Value]) = {}
override def deregisterListener(listener: Listener[Value]) = {}
}
}
trait Listener[-Value] {
/** Gets called every time this field gets updated. This includes updates that are not done by the user. */
def onChange(newValue: Value, directUserChange: Boolean): Callback
}
object Listener {
def nullInstance[Value] = new Listener[Value] {
override def onChange(newValue: Value, directUserChange: Boolean) = Callback.empty
}
}
}
|
flashypepo/myMicropython-Examples
|
robotcar/robot_client.py
|
# project: a client running on a device (Mac/Win/Linux)
# connected to a server, running on the Huzzah ESP8266
# 2017-0716 source: https://forums.adafruit.com/viewtopic.php?f=60&t=117874
import socket
def run():
host = '192.168.178.24' # host ip
#MAC-test: host = '192.168.178.14' #host ip-address
port = 5000
mySocket = socket.socket()
mySocket.connect((host, port))
print('Client connected to host: {0}, port: {1} '.format(host, port))
# get user command
# 2017-0716: 'f' = go forward, 'b' = go backwards,
# 'l'=turn left, 'r'= turn right
# 's' = stop
message = input(" -> ")
# as long as user command is not 'q', send command to server
while message != 'q':
mySocket.send(message.encode()) # send command to server
data = mySocket.recv(1024).decode()
print('Received from server: ' + data)
message = input(" -> ")
mySocket.close()
if __name__ == '__main__':
run()
|
sidav/shadow-of-the-wyrm
|
engine/generators/include/SeaGenerator.hpp
|
#pragma once
#include "Generator.hpp"
class SeaGenerator : public SOTW::Generator
{
public:
SeaGenerator(const std::string& map_exit_id);
virtual MapPtr generate(const Dimensions& dim) override;
};
|
IreneMercy/Joy-Village-Backup
|
joy/migrations/0015_about.py
|
# Generated by Django 2.2.10 on 2020-04-03 08:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('joy', '0014_auto_20200401_1206'),
]
operations = [
migrations.CreateModel(
name='About',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('introtext', models.CharField(max_length=255)),
('missionheading', models.CharField(max_length=30)),
('mission', models.CharField(max_length=255)),
('visionheading', models.CharField(max_length=30)),
('visiontext', models.CharField(max_length=255)),
],
),
]
|
lechium/tvOS144Headers
|
System/Library/PrivateFrameworks/GeoServices.framework/GEOETARoute.h
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 14, 2021 at 2:21:49 PM Mountain Standard Time
* Operating System: Version 14.4 (Build 18K802)
* Image Source: /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
#import <GeoServices/GeoServices-Structs.h>
#import <ProtocolBuffer/PBCodable.h>
#import <libobjc.A.dylib/NSCopying.h>
@class PBDataReader, PBUnknownFields, GEOWaypointInfo, NSMutableArray, GEONavigabilityInfo, NSData, GEOTrafficBannerText;
@interface GEOETARoute : PBCodable <NSCopying> {
PBDataReader* _reader;
PBUnknownFields* _unknownFields;
SCD_Struct_GE17* _incidentEndOffsetsInETARoutes;
SCD_Struct_GE17* _incidentIndexs;
SCD_Struct_GE17* _trafficColorOffsets;
SCD_Struct_GE17* _trafficColors;
GEOWaypointInfo* _destinationWaypointInfo;
NSMutableArray* _enrouteNotices;
NSMutableArray* _incidentOnRouteInfos;
NSMutableArray* _incidentsOffReRoutes;
NSMutableArray* _incidentsOnETARoutes;
NSMutableArray* _incidentsOnReRoutes;
NSMutableArray* _invalidSectionZilchPoints;
GEONavigabilityInfo* _navigabilityInfo;
GEOWaypointInfo* _originWaypointInfo;
NSMutableArray* _reroutedRoutes;
NSData* _routeID;
NSMutableArray* _steps;
GEOTrafficBannerText* _trafficBannerText;
NSMutableArray* _trafficColorInfos;
NSMutableArray* _zilchPoints;
unsigned _readerMarkPos;
unsigned _readerMarkLength;
os_unfair_lock_s _readerLock;
unsigned _historicTravelTime;
unsigned _staticTravelTime;
unsigned _travelTimeAggressiveEstimate;
unsigned _travelTimeBestEstimate;
unsigned _travelTimeConservativeEstimate;
BOOL _routeNoLongerValid;
struct {
unsigned has_historicTravelTime : 1;
unsigned has_staticTravelTime : 1;
unsigned has_travelTimeAggressiveEstimate : 1;
unsigned has_travelTimeBestEstimate : 1;
unsigned has_travelTimeConservativeEstimate : 1;
unsigned has_routeNoLongerValid : 1;
unsigned read_unknownFields : 1;
unsigned read_incidentEndOffsetsInETARoutes : 1;
unsigned read_incidentIndexs : 1;
unsigned read_trafficColorOffsets : 1;
unsigned read_trafficColors : 1;
unsigned read_destinationWaypointInfo : 1;
unsigned read_enrouteNotices : 1;
unsigned read_incidentOnRouteInfos : 1;
unsigned read_incidentsOffReRoutes : 1;
unsigned read_incidentsOnETARoutes : 1;
unsigned read_incidentsOnReRoutes : 1;
unsigned read_invalidSectionZilchPoints : 1;
unsigned read_navigabilityInfo : 1;
unsigned read_originWaypointInfo : 1;
unsigned read_reroutedRoutes : 1;
unsigned read_routeID : 1;
unsigned read_steps : 1;
unsigned read_trafficBannerText : 1;
unsigned read_trafficColorInfos : 1;
unsigned read_zilchPoints : 1;
unsigned wrote_anyField : 1;
} _flags;
}
@property (nonatomic,readonly) double expectedTime;
@property (nonatomic,readonly) BOOL hasRouteID;
@property (nonatomic,retain) NSData * routeID;
@property (nonatomic,retain) NSMutableArray * steps;
@property (nonatomic,retain) NSMutableArray * zilchPoints;
@property (assign,nonatomic) BOOL hasRouteNoLongerValid;
@property (assign,nonatomic) BOOL routeNoLongerValid;
@property (nonatomic,retain) NSMutableArray * reroutedRoutes;
@property (nonatomic,retain) NSMutableArray * invalidSectionZilchPoints;
@property (nonatomic,readonly) unsigned long long trafficColorsCount;
@property (nonatomic,readonly) unsigned* trafficColors;
@property (nonatomic,readonly) unsigned long long trafficColorOffsetsCount;
@property (nonatomic,readonly) unsigned* trafficColorOffsets;
@property (nonatomic,retain) NSMutableArray * incidentsOnETARoutes;
@property (nonatomic,retain) NSMutableArray * incidentsOnReRoutes;
@property (nonatomic,retain) NSMutableArray * incidentsOffReRoutes;
@property (nonatomic,readonly) unsigned long long incidentIndexsCount;
@property (nonatomic,readonly) unsigned* incidentIndexs;
@property (nonatomic,readonly) unsigned long long incidentEndOffsetsInETARoutesCount;
@property (nonatomic,readonly) unsigned* incidentEndOffsetsInETARoutes;
@property (nonatomic,readonly) BOOL hasTrafficBannerText;
@property (nonatomic,retain) GEOTrafficBannerText * trafficBannerText;
@property (assign,nonatomic) BOOL hasHistoricTravelTime;
@property (assign,nonatomic) unsigned historicTravelTime;
@property (assign,nonatomic) BOOL hasTravelTimeAggressiveEstimate;
@property (assign,nonatomic) unsigned travelTimeAggressiveEstimate;
@property (assign,nonatomic) BOOL hasTravelTimeBestEstimate;
@property (assign,nonatomic) unsigned travelTimeBestEstimate;
@property (assign,nonatomic) BOOL hasTravelTimeConservativeEstimate;
@property (assign,nonatomic) unsigned travelTimeConservativeEstimate;
@property (assign,nonatomic) BOOL hasStaticTravelTime;
@property (assign,nonatomic) unsigned staticTravelTime;
@property (nonatomic,retain) NSMutableArray * enrouteNotices;
@property (nonatomic,retain) NSMutableArray * trafficColorInfos;
@property (nonatomic,retain) NSMutableArray * incidentOnRouteInfos;
@property (nonatomic,readonly) BOOL hasOriginWaypointInfo;
@property (nonatomic,retain) GEOWaypointInfo * originWaypointInfo;
@property (nonatomic,readonly) BOOL hasDestinationWaypointInfo;
@property (nonatomic,retain) GEOWaypointInfo * destinationWaypointInfo;
@property (nonatomic,readonly) BOOL hasNavigabilityInfo;
@property (nonatomic,retain) GEONavigabilityInfo * navigabilityInfo;
@property (nonatomic,readonly) PBUnknownFields * unknownFields;
+(BOOL)isValid:(id)arg1 ;
+(Class)zilchPointsType;
+(Class)stepType;
+(Class)trafficColorInfoType;
+(Class)enrouteNoticeType;
+(Class)incidentOnRouteInfoType;
+(Class)reroutedRouteType;
+(Class)invalidSectionZilchPointsType;
+(Class)incidentsOnETARouteType;
+(Class)incidentsOnReRoutesType;
+(Class)incidentsOffReRoutesType;
-(BOOL)isEqual:(id)arg1 ;
-(unsigned long long)hash;
-(id)copyWithZone:(NSZone*)arg1 ;
-(id)description;
-(id)init;
-(void)dealloc;
-(id)initWithData:(id)arg1 ;
-(id)initWithDictionary:(id)arg1 ;
-(id)dictionaryRepresentation;
-(BOOL)readFrom:(id)arg1 ;
-(void)writeTo:(id)arg1 ;
-(void)mergeFrom:(id)arg1 ;
-(void)copyTo:(id)arg1 ;
-(NSData *)routeID;
-(NSMutableArray *)steps;
-(void)readAll:(BOOL)arg1 ;
-(id)jsonRepresentation;
-(id)initWithJSON:(id)arg1 ;
-(PBUnknownFields *)unknownFields;
-(void)clearUnknownFields:(BOOL)arg1 ;
-(unsigned long long)stepsCount;
-(void)setRouteID:(NSData *)arg1 ;
-(void)setZilchPoints:(NSMutableArray *)arg1 ;
-(NSMutableArray *)zilchPoints;
-(void)addZilchPoints:(id)arg1 ;
-(void)addStep:(id)arg1 ;
-(unsigned long long)zilchPointsCount;
-(void)clearZilchPoints;
-(id)zilchPointsAtIndex:(unsigned long long)arg1 ;
-(void)clearSteps;
-(id)stepAtIndex:(unsigned long long)arg1 ;
-(void)setSteps:(NSMutableArray *)arg1 ;
-(void)setTravelTimeAggressiveEstimate:(unsigned)arg1 ;
-(void)setTravelTimeConservativeEstimate:(unsigned)arg1 ;
-(unsigned)travelTimeAggressiveEstimate;
-(void)setHasTravelTimeAggressiveEstimate:(BOOL)arg1 ;
-(BOOL)hasTravelTimeAggressiveEstimate;
-(unsigned)travelTimeConservativeEstimate;
-(void)setHasTravelTimeConservativeEstimate:(BOOL)arg1 ;
-(BOOL)hasTravelTimeConservativeEstimate;
-(NSMutableArray *)reroutedRoutes;
-(double)expectedTime;
-(unsigned)historicTravelTime;
-(unsigned)staticTravelTime;
-(unsigned long long)incidentIndexsCount;
-(unsigned)incidentIndexAtIndex:(unsigned long long)arg1 ;
-(NSMutableArray *)enrouteNotices;
-(BOOL)hasHistoricTravelTime;
-(void)addTrafficColor:(unsigned)arg1 ;
-(void)addTrafficColorOffset:(unsigned)arg1 ;
-(unsigned long long)trafficColorsCount;
-(void)clearTrafficColors;
-(unsigned)trafficColorAtIndex:(unsigned long long)arg1 ;
-(unsigned long long)trafficColorOffsetsCount;
-(void)clearTrafficColorOffsets;
-(unsigned)trafficColorOffsetAtIndex:(unsigned long long)arg1 ;
-(BOOL)hasRouteID;
-(unsigned*)trafficColors;
-(void)setTrafficColors:(unsigned*)arg1 count:(unsigned long long)arg2 ;
-(unsigned*)trafficColorOffsets;
-(void)setTrafficColorOffsets:(unsigned*)arg1 count:(unsigned long long)arg2 ;
-(void)addIncidentIndex:(unsigned)arg1 ;
-(void)clearIncidentIndexs;
-(unsigned*)incidentIndexs;
-(void)setIncidentIndexs:(unsigned*)arg1 count:(unsigned long long)arg2 ;
-(GEOWaypointInfo *)originWaypointInfo;
-(GEOWaypointInfo *)destinationWaypointInfo;
-(void)setOriginWaypointInfo:(GEOWaypointInfo *)arg1 ;
-(void)setDestinationWaypointInfo:(GEOWaypointInfo *)arg1 ;
-(BOOL)hasOriginWaypointInfo;
-(BOOL)hasDestinationWaypointInfo;
-(void)addTrafficColorInfo:(id)arg1 ;
-(void)setHistoricTravelTime:(unsigned)arg1 ;
-(void)setStaticTravelTime:(unsigned)arg1 ;
-(void)addEnrouteNotice:(id)arg1 ;
-(void)addIncidentOnRouteInfo:(id)arg1 ;
-(unsigned long long)trafficColorInfosCount;
-(void)clearTrafficColorInfos;
-(id)trafficColorInfoAtIndex:(unsigned long long)arg1 ;
-(unsigned long long)enrouteNoticesCount;
-(void)clearEnrouteNotices;
-(id)enrouteNoticeAtIndex:(unsigned long long)arg1 ;
-(unsigned long long)incidentOnRouteInfosCount;
-(void)clearIncidentOnRouteInfos;
-(id)incidentOnRouteInfoAtIndex:(unsigned long long)arg1 ;
-(NSMutableArray *)trafficColorInfos;
-(void)setTrafficColorInfos:(NSMutableArray *)arg1 ;
-(void)setHasHistoricTravelTime:(BOOL)arg1 ;
-(void)setHasStaticTravelTime:(BOOL)arg1 ;
-(BOOL)hasStaticTravelTime;
-(void)setEnrouteNotices:(NSMutableArray *)arg1 ;
-(NSMutableArray *)incidentOnRouteInfos;
-(void)setIncidentOnRouteInfos:(NSMutableArray *)arg1 ;
-(unsigned long long)stepIndexOfStepWithID:(unsigned)arg1 ;
-(double)remainingTimeFromStepID:(unsigned)arg1 toEndStepID:(unsigned)arg2 currentStepRemainingDistance:(double)arg3 ;
-(double)remainingTimeAlongRoute:(unsigned)arg1 currentStepRemainingDistance:(double)arg2 ;
-(NSMutableArray *)incidentsOnReRoutes;
-(unsigned long long)incidentEndOffsetsInETARoutesCount;
-(unsigned*)incidentEndOffsetsInETARoutes;
-(NSMutableArray *)incidentsOnETARoutes;
-(unsigned)travelTimeBestEstimate;
-(GEOTrafficBannerText *)trafficBannerText;
-(GEONavigabilityInfo *)navigabilityInfo;
-(BOOL)routeNoLongerValid;
-(id)incidentsOnETARouteAtIndex:(unsigned long long)arg1 ;
-(id)incidentsOnReRoutesAtIndex:(unsigned long long)arg1 ;
-(void)setTravelTimeBestEstimate:(unsigned)arg1 ;
-(void)setHasTravelTimeBestEstimate:(BOOL)arg1 ;
-(BOOL)hasTravelTimeBestEstimate;
-(NSMutableArray *)invalidSectionZilchPoints;
-(void)setRouteNoLongerValid:(BOOL)arg1 ;
-(void)addReroutedRoute:(id)arg1 ;
-(void)addInvalidSectionZilchPoints:(id)arg1 ;
-(void)addIncidentsOnETARoute:(id)arg1 ;
-(void)addIncidentsOnReRoutes:(id)arg1 ;
-(void)addIncidentsOffReRoutes:(id)arg1 ;
-(void)addIncidentEndOffsetsInETARoute:(unsigned)arg1 ;
-(void)setTrafficBannerText:(GEOTrafficBannerText *)arg1 ;
-(void)setNavigabilityInfo:(GEONavigabilityInfo *)arg1 ;
-(unsigned long long)reroutedRoutesCount;
-(void)clearReroutedRoutes;
-(id)reroutedRouteAtIndex:(unsigned long long)arg1 ;
-(unsigned long long)invalidSectionZilchPointsCount;
-(void)clearInvalidSectionZilchPoints;
-(id)invalidSectionZilchPointsAtIndex:(unsigned long long)arg1 ;
-(unsigned long long)incidentsOnETARoutesCount;
-(void)clearIncidentsOnETARoutes;
-(unsigned long long)incidentsOnReRoutesCount;
-(void)clearIncidentsOnReRoutes;
-(unsigned long long)incidentsOffReRoutesCount;
-(void)clearIncidentsOffReRoutes;
-(id)incidentsOffReRoutesAtIndex:(unsigned long long)arg1 ;
-(void)clearIncidentEndOffsetsInETARoutes;
-(unsigned)incidentEndOffsetsInETARouteAtIndex:(unsigned long long)arg1 ;
-(void)setHasRouteNoLongerValid:(BOOL)arg1 ;
-(BOOL)hasRouteNoLongerValid;
-(void)setReroutedRoutes:(NSMutableArray *)arg1 ;
-(void)setInvalidSectionZilchPoints:(NSMutableArray *)arg1 ;
-(void)setIncidentsOnETARoutes:(NSMutableArray *)arg1 ;
-(void)setIncidentsOnReRoutes:(NSMutableArray *)arg1 ;
-(NSMutableArray *)incidentsOffReRoutes;
-(void)setIncidentsOffReRoutes:(NSMutableArray *)arg1 ;
-(void)setIncidentEndOffsetsInETARoutes:(unsigned*)arg1 count:(unsigned long long)arg2 ;
-(BOOL)hasTrafficBannerText;
-(BOOL)hasNavigabilityInfo;
@end
|
johnoel/tagest
|
21mt/src/gcomp.cpp
|
#include "precomp.h"
double normal_dev(const double x, const double mu, const double sigma);
#define TRACE(object) clogf << "line " << __LINE__ << ", file "\
<< __FILE__ << ", " << #object " = " << object << endl;
#define TTRACE(o1,o2) clogf << "line " << __LINE__ << ", file "\
<< __FILE__ << ", " << #o1 " = " << o1<< ", " << #o2 " = " << o2 << endl;
extern ofstream clogf;
double randn(long int& n);
adstring recruitment_file_name(year_month& date); //, char* _directory);
int move_corner(const int x, const int edge);
void linbcg::g_comp(par_t& param, const dmatrix& recruitment)
{
//TRACE(g_)
double dt = 1.0/param.m_ipar[6];
for (int i = 1; i <= m_; i++)
{
int j1 = recruitment(i).indexmin();
int j2 = recruitment(i).indexmax();
//cout << j0 << " & " << jN << endl;
for (int j = j1; j <= j2; j++)
{
g_((j - 1) * m_ + i) = recruitment(i, j);
} // for j
}//for i
//TRACE(g_)
}
void par_t_reg::population_initialize(dmatrix& pop,
const double init_pop)
{
int ncell = 0;
for (int i = 1; i <= m; i++)
{
int jlb = pop(i).indexmin();
int jub = pop(i).indexmax();
for (int j = jlb; j <= jub; j++)
{
if (gridmap(i,j) > 0)
{
pop(i,j) = init_pop;
ncell++;
}
else
pop(i,j) = 0.0;
}
}
}
#include <values.h>
double min(const dmatrix& t)
{
double x = MAXDOUBLE;
int i1 = t.rowmin();
int i2 = t.rowmax();
for (int i = i1; i <= i2; i++)
{
double tmp = min(t(i));
if (tmp < x)
x = tmp;
}
return(x);
}
#include <values.h>
void par_t_reg::recruit_comp(dmatrix& r, const dmatrix& pop,
const year_month& date, double& spawning_biomass)
{
spawning_biomass = 0.0;
double popmin = MAXDOUBLE;
double eps = 0.00001;
int mode_flag_m_ipar = 131;
int mode_flag = m_ipar[mode_flag_m_ipar];
if (mode_flag == 0)
{
double rcell = mort/1714.0;
for (int i = 1; i <= m; i++)
{
int jlb = r(i).indexmin();
int jub = r(i).indexmax();
for (int j = jlb; j <= jub; j++)
{
if (gridmap(i,j) > 0)
{
if (pop(i,j) < popmin)
popmin = pop(i,j);
if (pop(i,j) > eps)
{
r(i,j) = rcell;
spawning_biomass += pop(i,j);
}
}
else
r(i,j) = 0.0;
}
}
TRACE(popmin)
TRACE(sum(r))
}
else if (mode_flag == 3)
{
//i = move_corner(int(t.Long.value()),sw_long);
//j = move_corner(int(t.Lat.value()),sw_lat);
int sw_long = (int)sw_coord.long_value();
int sw_lat = (int)sw_coord.lat_value();
int i1 = move_corner(m_ipar(126),sw_long);
int j1 = move_corner(m_ipar(127),sw_lat);
int i2 = move_corner(m_ipar(128),sw_long);
int j2 = move_corner(m_ipar(129),sw_lat);
int ilb = max(1,i1);
int iub = min(m,i2);
double ncell = 0.0;
double rcell = (double)m_ipar(132)*mort;
for (int i = i1; i <= i2; i++)
{
int jlb = max(r(i).indexmin(),j1);
int jub = min(r(i).indexmax(),j2);
for (int j = jlb; j <= jub; j++)
{
if (gridmap(i,j) > 0)
{
ncell ++;
if (pop(i,j) < popmin)
popmin = pop(i,j);
if (pop(i,j) > eps)
{
r(i,j) = rcell;
spawning_biomass += pop(i,j);
}
}
else
r(i,j) = 0.0;
}
}
double rncell = 1.0/ncell;
r = r*rncell;
}
else if (mode_flag ==4)
{
dmatrix sst(1,m,jlb,jub);
int month = date.get_month_value();
const int oblen = 20;
char ob2[oblen];
ostrstream sob2(ob2,oblen);
#ifdef unix
sob2 << "../nodc00" << setw(2) << setfill('0') << month << ".sst" << '\0';
#else
sob2 << "..\\nodc00" << setw(2) << setfill('0') << month << ".sst" << '\0';
#endif
ifstream sstf(ob2);
if (!sstf)
{
cerr << "Error opening sst input file"
<<"'" << ob2 << "'" << endl;
exit(1);
}
sstf >> sst;
clogf << "read sst from " << ob2 << endl;
double tmin = m_ipar(133);
double tmax = m_ipar(134);
double ncell = 0.0;
double rcell = (double)m_ipar(132)*mort;
for (int i = 1; i <= m; i++)
{
int j1 = r(i).indexmin();
int j2 = r(i).indexmax();
for (int j = j1; j <= j2; j++)
{
if ( (gridmap(i,j) > 0) &&
(sst(i,j) >= tmin) && (sst(i,j) < tmax) )
{
ncell ++;
if (pop(i,j) < popmin)
popmin = pop(i,j);
if (pop(i,j) > eps)
{
r(i,j) = rcell;
spawning_biomass += pop(i,j);
}
}
else
r(i,j) = 0.0;
}
}
TRACE(ncell)
double rncell = 1.0/ncell;
//TRACE(sum(r))
r = r*rncell;
//TRACE(sum(r))
}
else if (mode_flag == 5)
{
dmatrix sst(1,m,jlb,jub);
int month = date.get_month_value();
const int oblen = 20;
char ob2[oblen];
ostrstream sob2(ob2,oblen);
#ifdef unix
sob2 << "../nodc00" << setw(2) << setfill('0') << month << ".sst" << '\0';
#else
sob2 << "..\\nodc00" << setw(2) << setfill('0') << month << ".sst" << '\0';
#endif
ifstream sstf(ob2);
if (!sstf)
{
cerr << "Error opening sst input file"
<<"'" << ob2 << "'" << endl;
exit(1);
}
sstf >> sst;
clogf << "read sst from " << ob2 << endl;
double tmin = m_ipar(133);
double tmax = m_ipar(134);
double ncell = 0.0;
double rcell = (double)m_ipar(132)*mort;
TRACE(rcell)
double d_bh = 0.5/rcell; // maximum at 1/n equilibrium
double c_bh = exp(d_bh*rcell); // replacement at equilibrium
TTRACE(d_bh,c_bh)
for (int i = 1; i <= m; i++)
{
int j1 = r(i).indexmin();
int j2 = r(i).indexmax();
for (int j = j1; j <= j2; j++)
{
if ( (gridmap(i,j) > 0) &&
(sst(i,j) >= tmin) && (sst(i,j) < tmax) )
{
ncell ++;
if (pop(i,j) < popmin)
popmin = pop(i,j);
if (pop(i,j) > eps)
{
r(i,j) = c_bh*exp(-d_bh*pop(i,j));
spawning_biomass += pop(i,j);
}
}
else
r(i,j) = 0.0;
}
}
TRACE(ncell)
double rncell = 1.0/ncell;
//TRACE(sum(r))
r = r*rncell;
//TRACE(sum(r))
}
/*
else if (mode_flag == 1)
{
int n = _get_n();
dvector average_recruitment(1,n);
double rmax = 0.0;
for (int j = 1; j <= n; j++)
{
double latitude= sw_lat + (deltay*double(j))/60.0;
average_recruitment(j) = normal_dev(latitude, 0.0, 5.0);
if (average_recruitment(j) > rmax)
rmax = average_recruitment(j);
}
average_recruitment /= rmax;
double rmean = (double)m_ipar[mode_flag_m_ipar+1];
double rsig = (double)m_ipar[mode_flag_m_ipar+2]/100.0;
long seed = m_ipar[40];
for (int i = 1; i <= m; i++)
{
int jlb = g(i).indexmin();
int jub = g(i).indexmax();
for (int j = jlb; j <= jub; j++)
{
if (gridmap(i,j) > 0)
{
g(i,j) = rmean*average_recruitment(j)*exp(rsig*randn(seed));
}
else
g(i,j) = 0.0;
}
}
adstring rfile = recruitment_file_name(date);
ofstream rf(rfile);
rf << g << endl;
m_ipar[40] = seed;
}
else if (mode_flag == 2)
{
adstring rfile = recruitment_file_name(date);
ifstream rf(rfile);
rf >> g;
if (!rf)
{
cerr << "Error reading file "<< rfile << " in gcomp" << endl;
clogf << "Error reading file "<< rfile << " in gcomp" << endl;
exit(1);
}
}
*/
else
{
cerr << "Unknown mode flag ** (" << mode_flag << ") passed to gcomp." << endl;
clogf << "Unknown mode flag ** (" << mode_flag << ") passed to gcomp." << endl;
exit(1);
}
}
double normal_dev(const double x, const double mu, const double sigma)
{
double v = 0.0;
double t = (x-mu)/sigma;
if (t < 80.0)
{
v = exp(-t*t)/sqrt(6.2831853 * sigma);
}
return(v);
}
adstring recruitment_file_name(year_month& date) //, char* _directory)
{
/*
adstring directory;
if (_directory)
directory = adstring(_directory);
else
{
directory = "..\\";
#if defined __GNUC__ || __SUN__
directory = "../";
#endif
}
*/
int month = date.get_month().get_value();
char month_str[3];
sprintf(month_str,"%02d",month);
char year_str[3];
//sprintf(year_str,"%02d",date.get_year());
sprintf(year_str,"%02d",0);
adstring file_name = adstring(year_str)+month_str+".rec";
//TRACE(file_name)
#if defined __SUN__ || __GNUC__
file_name.to_lower();
#endif
return (file_name);
}
|
eseidel/native_client_patches
|
tools/modular-build/examples/libhello/libhello.h
|
/*
* Copyright 2010 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
void say_hello(void);
|
algalopez/MyCon
|
app/src/main/java/com/algalopez/mycon/wifi/presentation/wifi/WifiFragment.java
|
package com.algalopez.mycon.wifi.presentation.wifi;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import com.algalopez.mycon.R;
import com.algalopez.mycon.common.Executor;
import com.algalopez.mycon.wifi.data.IWifiDbRepo;
import com.algalopez.mycon.wifi.data.IWifiManagerRepo;
import com.algalopez.mycon.wifi.data.WifiDbRepo;
import com.algalopez.mycon.wifi.data.WifiManagerRepo;
import com.algalopez.mycon.wifi.domain.model.DeviceEntity;
import com.algalopez.mycon.wifi.domain.model.WifiEntity;
import java.util.ArrayList;
public class WifiFragment extends Fragment implements IWifiView {
private static final String LOGTAG = "WifiFragment";
private View mRootView;
// Presenter
private WifiPresenter mPresenter;
// Stored data
private IWifiDbRepo mWifiDbRepo;
// New data
private IWifiManagerRepo mWifiManagerRepo;
// Executor
Executor mExecutor;
// Activity callbacks
OnFragmentInteractionListener mFragmentListener;
/* *********************************************************************************************
* CONSTRUCTION
* *********************************************************************************************
*/
public WifiFragment() {
}
/* *********************************************************************************************
* FRAGMENT LIFECYCLE
* *********************************************************************************************
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_wifi, container, false);
mExecutor = new Executor();
mWifiDbRepo = new WifiDbRepo(getContext());
mWifiManagerRepo = new WifiManagerRepo(getContext());
mPresenter = new WifiPresenter(mExecutor, mWifiDbRepo, mWifiManagerRepo);
WifiAdapter connectedDevicesAdapter = new WifiAdapter(null, null);
RecyclerView connectedDevicesList = (RecyclerView) mRootView.findViewById(R.id.wifi_connected_devices_rv);
connectedDevicesList.setAdapter(connectedDevicesAdapter);
return mRootView;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onResume() {
super.onResume();
mPresenter.attachView(this);
}
@Override
public void onPause() {
super.onPause();
mPresenter.detachView();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mFragmentListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mFragmentListener = null;
}
/* *********************************************************************************************
* LISTENERS
* *********************************************************************************************
*/
private ImageButton.OnClickListener getOnRefreshListener(){
return new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(LOGTAG, "Refresh clicked");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getContext().getResources().getString(R.string.dialog_update_title));
builder.setMessage(getResources().getString(R.string.dialog_update_message));
builder.setPositiveButton(getResources().getText(R.string.ok), getOnRefreshOkListener());
builder.setNegativeButton(getResources().getString(R.string.cancel), null);
Dialog dialog = builder.create();
dialog.show();
}
};
}
private OnClickWifiListener getOnWifiDetailListener(WifiEntity wifiEntity){
return new OnClickWifiListener(wifiEntity) {
@Override
public void onClick(View view) {
Log.d(LOGTAG, "Wifi clicked (new)");
mFragmentListener.onWifiSelected(this.mWifiEntity);
}
};
}
//
private WifiAdapter.RecyclerListener getOnDeviceDetailListener() {
return new WifiAdapter.RecyclerListener() {
@Override
public void OnItemClickListener(DeviceEntity deviceEntity) {
Log.d(LOGTAG, "Item with id " + deviceEntity.getID() + " clicked");
mFragmentListener.onDeviceSelected(deviceEntity);
}
};
}
// Clicked OK in refresh dialog
private DialogInterface.OnClickListener getOnRefreshOkListener() {
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
mPresenter.updateWifi();
}
};
}
/* *********************************************************************************************
* VIEW INTERFACE
* *********************************************************************************************
*/
@Override
public void showProgress(int percentage) {
}
@Override
public void showError(String message) {
}
@Override
public void showConnectedDevices(ArrayList<DeviceEntity> connectedDevices) {
// Set item listeners
WifiAdapter connectedDevicesAdapter = new WifiAdapter(connectedDevices, getOnDeviceDetailListener());
RecyclerView connectedDevicesList = (RecyclerView) mRootView.findViewById(R.id.wifi_connected_devices_rv);
connectedDevicesList.setAdapter(connectedDevicesAdapter);
connectedDevicesList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
}
@Override
public void showWifiInfo(WifiEntity wifiEntity) {
TextView wifiSSID = (TextView) mRootView.findViewById(R.id.fragment_wifi_ssid_tv);
wifiSSID.setText(wifiEntity.getSSID());
// Set listener to wifi details
mRootView.findViewById(R.id.fragment_wifi_details_ib).setOnClickListener(getOnWifiDetailListener(wifiEntity));
// Set listener to update button
mRootView.findViewById(R.id.fragment_wifi_refresh_ib).setOnClickListener(getOnRefreshListener());
}
/* *********************************************************************************************
* ACTIVITY CALLBACK
* *********************************************************************************************
*/
interface OnFragmentInteractionListener {
void onWifiSelected(WifiEntity wifiEntity);
void onDeviceSelected(DeviceEntity deviceEntity);
}
/* *********************************************************************************************
* OTHERS
* *********************************************************************************************
*/
private abstract class OnClickWifiListener implements ImageButton.OnClickListener{
protected WifiEntity mWifiEntity;
private OnClickWifiListener(WifiEntity wifiEntity){
this.mWifiEntity = wifiEntity;
}
abstract public void onClick(View view);
}
}
|
viniciusvss120/animais-fantasticos
|
javaScript/automacao-Frontend/animais-eslint/node_modules/@babel/plugin-proposal-private-property-in-object/lib/index.js
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _pluginSyntaxPrivatePropertyInObject = require("@babel/plugin-syntax-private-property-in-object");
var _helperCreateClassFeaturesPlugin = require("@babel/helper-create-class-features-plugin");
var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
var _default = (0, _helperPluginUtils.declare)(({
assertVersion,
types: t,
template
}, {
loose
}) => {
assertVersion(7);
const classWeakSets = new WeakMap();
const fieldsWeakSets = new WeakMap();
function unshadow(name, targetScope, scope) {
while (scope !== targetScope) {
if (scope.hasOwnBinding(name)) scope.rename(name);
scope = scope.parent;
}
}
function injectToFieldInit(fieldPath, expr, before = false) {
if (fieldPath.node.value) {
if (before) {
fieldPath.get("value").insertBefore(expr);
} else {
fieldPath.get("value").insertAfter(expr);
}
} else {
fieldPath.set("value", t.unaryExpression("void", expr));
}
}
function injectInitialization(classPath, init) {
let firstFieldPath;
let consturctorPath;
for (const el of classPath.get("body.body")) {
if ((el.isClassProperty() || el.isClassPrivateProperty()) && !el.node.static) {
firstFieldPath = el;
break;
}
if (!consturctorPath && el.isClassMethod({
kind: "constructor"
})) {
consturctorPath = el;
}
}
if (firstFieldPath) {
injectToFieldInit(firstFieldPath, init, true);
} else {
(0, _helperCreateClassFeaturesPlugin.injectInitialization)(classPath, consturctorPath, [t.expressionStatement(init)]);
}
}
function getWeakSetId(weakSets, outerClass, reference, name = "", inject) {
let id = classWeakSets.get(reference.node);
if (!id) {
id = outerClass.scope.generateUidIdentifier(`${name || ""} brandCheck`);
classWeakSets.set(reference.node, id);
inject(reference, template.expression.ast`${t.cloneNode(id)}.add(this)`);
const newExpr = t.newExpression(t.identifier("WeakSet"), []);
(0, _helperAnnotateAsPure.default)(newExpr);
outerClass.insertBefore(template.ast`var ${id} = ${newExpr}`);
}
return t.cloneNode(id);
}
return {
name: "proposal-private-property-in-object",
inherits: _pluginSyntaxPrivatePropertyInObject.default.default,
pre() {
(0, _helperCreateClassFeaturesPlugin.enableFeature)(this.file, _helperCreateClassFeaturesPlugin.FEATURES.privateIn, loose);
},
visitor: {
BinaryExpression(path) {
const {
node
} = path;
if (node.operator !== "in") return;
if (!t.isPrivateName(node.left)) return;
const {
name
} = node.left.id;
let privateElement;
const outerClass = path.findParent(path => {
if (!path.isClass()) return false;
privateElement = path.get("body.body").find(({
node
}) => t.isPrivate(node) && node.key.id.name === name);
return !!privateElement;
});
if (outerClass.parentPath.scope.path.isPattern()) {
outerClass.replaceWith(template.ast`(() => ${outerClass.node})()`);
return;
}
if (privateElement.isMethod()) {
if (privateElement.node.static) {
if (outerClass.node.id) {
unshadow(outerClass.node.id.name, outerClass.scope, path.scope);
} else {
outerClass.set("id", path.scope.generateUidIdentifier("class"));
}
path.replaceWith(template.expression.ast`
${t.cloneNode(outerClass.node.id)} === ${path.node.right}
`);
} else {
var _outerClass$node$id;
const id = getWeakSetId(classWeakSets, outerClass, outerClass, (_outerClass$node$id = outerClass.node.id) == null ? void 0 : _outerClass$node$id.name, injectInitialization);
path.replaceWith(template.expression.ast`${id}.has(${path.node.right})`);
}
} else {
const id = getWeakSetId(fieldsWeakSets, outerClass, privateElement, privateElement.node.key.id.name, injectToFieldInit);
path.replaceWith(template.expression.ast`${id}.has(${path.node.right})`);
}
}
}
};
});
exports.default = _default;
|
karupayun/orbit
|
OrbitLinuxTracing/UprobesFunctionCallManagerTest.cpp
|
<gh_stars>0
// Copyright (c) 2020 The Orbit 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 <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include "UprobesFunctionCallManager.h"
namespace LinuxTracing {
TEST(UprobesFunctionCallManager, OneUprobe) {
constexpr pid_t tid = 42;
std::optional<FunctionCall> processed_function_call;
UprobesFunctionCallManager function_call_manager;
function_call_manager.ProcessUprobes(tid, 100, 1);
processed_function_call = function_call_manager.ProcessUretprobes(tid, 2, 3);
ASSERT_TRUE(processed_function_call.has_value());
EXPECT_EQ(processed_function_call.value().GetTid(), tid);
EXPECT_EQ(processed_function_call.value().GetVirtualAddress(), 100);
EXPECT_EQ(processed_function_call.value().GetBeginTimestampNs(), 1);
EXPECT_EQ(processed_function_call.value().GetEndTimestampNs(), 2);
EXPECT_EQ(processed_function_call.value().GetDepth(), 0);
EXPECT_EQ(processed_function_call.value().GetIntegerReturnValue(), 3);
}
TEST(UprobesFunctionCallManager, TwoNestedUprobesAndAnotherUprobe) {
constexpr pid_t tid = 42;
std::optional<FunctionCall> processed_function_call;
UprobesFunctionCallManager function_call_manager;
function_call_manager.ProcessUprobes(tid, 100, 1);
function_call_manager.ProcessUprobes(tid, 200, 2);
processed_function_call = function_call_manager.ProcessUretprobes(tid, 3, 4);
ASSERT_TRUE(processed_function_call.has_value());
EXPECT_EQ(processed_function_call.value().GetTid(), tid);
EXPECT_EQ(processed_function_call.value().GetVirtualAddress(), 200);
EXPECT_EQ(processed_function_call.value().GetBeginTimestampNs(), 2);
EXPECT_EQ(processed_function_call.value().GetEndTimestampNs(), 3);
EXPECT_EQ(processed_function_call.value().GetDepth(), 1);
EXPECT_EQ(processed_function_call.value().GetIntegerReturnValue(), 4);
processed_function_call = function_call_manager.ProcessUretprobes(tid, 4, 5);
ASSERT_TRUE(processed_function_call.has_value());
EXPECT_EQ(processed_function_call.value().GetTid(), tid);
EXPECT_EQ(processed_function_call.value().GetVirtualAddress(), 100);
EXPECT_EQ(processed_function_call.value().GetBeginTimestampNs(), 1);
EXPECT_EQ(processed_function_call.value().GetEndTimestampNs(), 4);
EXPECT_EQ(processed_function_call.value().GetDepth(), 0);
EXPECT_EQ(processed_function_call.value().GetIntegerReturnValue(), 5);
function_call_manager.ProcessUprobes(tid, 300, 5);
processed_function_call = function_call_manager.ProcessUretprobes(tid, 6, 7);
ASSERT_TRUE(processed_function_call.has_value());
EXPECT_EQ(processed_function_call.value().GetTid(), tid);
EXPECT_EQ(processed_function_call.value().GetVirtualAddress(), 300);
EXPECT_EQ(processed_function_call.value().GetBeginTimestampNs(), 5);
EXPECT_EQ(processed_function_call.value().GetEndTimestampNs(), 6);
EXPECT_EQ(processed_function_call.value().GetDepth(), 0);
EXPECT_EQ(processed_function_call.value().GetIntegerReturnValue(), 7);
}
TEST(UprobesFunctionCallManager, TwoUprobesDifferentThreads) {
constexpr pid_t tid = 42;
constexpr pid_t tid2 = 111;
std::optional<FunctionCall> processed_function_call;
UprobesFunctionCallManager function_call_manager;
function_call_manager.ProcessUprobes(tid, 100, 1);
function_call_manager.ProcessUprobes(tid2, 200, 2);
processed_function_call = function_call_manager.ProcessUretprobes(tid, 3, 4);
ASSERT_TRUE(processed_function_call.has_value());
EXPECT_EQ(processed_function_call.value().GetTid(), tid);
EXPECT_EQ(processed_function_call.value().GetVirtualAddress(), 100);
EXPECT_EQ(processed_function_call.value().GetBeginTimestampNs(), 1);
EXPECT_EQ(processed_function_call.value().GetEndTimestampNs(), 3);
EXPECT_EQ(processed_function_call.value().GetDepth(), 0);
EXPECT_EQ(processed_function_call.value().GetIntegerReturnValue(), 4);
processed_function_call = function_call_manager.ProcessUretprobes(tid2, 4, 5);
ASSERT_TRUE(processed_function_call.has_value());
EXPECT_EQ(processed_function_call.value().GetTid(), tid2);
EXPECT_EQ(processed_function_call.value().GetVirtualAddress(), 200);
EXPECT_EQ(processed_function_call.value().GetBeginTimestampNs(), 2);
EXPECT_EQ(processed_function_call.value().GetEndTimestampNs(), 4);
EXPECT_EQ(processed_function_call.value().GetDepth(), 0);
EXPECT_EQ(processed_function_call.value().GetIntegerReturnValue(), 5);
}
TEST(UprobesFunctionCallManager, OnlyUretprobe) {
constexpr pid_t tid = 42;
std::optional<FunctionCall> processed_function_call;
UprobesFunctionCallManager function_call_manager;
processed_function_call = function_call_manager.ProcessUretprobes(tid, 2, 3);
ASSERT_FALSE(processed_function_call.has_value());
}
} // namespace LinuxTracing
|
hejamu/gromacs
|
src/gromacs/utility/baseversion.h
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2014,2015,2018,2019,2020, by the GROMACS development team, led by
* <NAME>, <NAME>, <NAME>, and <NAME>,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \file
* \brief
* Declares functions to get basic version information.
*
* \author <NAME> <<EMAIL>>
* \inpublicapi
* \ingroup module_utility
*/
#ifndef GMX_UTILITY_BASEVERSION_H
#define GMX_UTILITY_BASEVERSION_H
/*! \brief
* Version string, containing the version, date, and abbreviated hash.
*
* This can be a plain version if git version info was disabled during the
* build.
* The returned string used to start with a literal word `VERSION` before
* \Gromacs 2016, but no longer does.
*
* \ingroup module_utility
*/
const char* gmx_version();
/*! \brief
* Full git hash of the latest commit.
*
* If git version info was disabled during the build, returns an empty string.
*
* \ingroup module_utility
*/
const char* gmx_version_git_full_hash();
/*! \brief
* Full git hash of the latest commit in a central \Gromacs repository.
*
* If git version info was disabled during the build, returns an empty string.
* Also, if the latest commit was from a central repository, the return value
* is an empty string.
*
* \ingroup module_utility
*/
const char* gmx_version_git_central_base_hash();
/*! \brief
* Defined if ``libgromacs`` has been compiled in double precision.
*
* Allows detecting the compiled precision of the library through checking the
* presence of the symbol, e.g., from autoconf or other types of build systems.
*
* \ingroup module_utility
*/
void gmx_is_double_precision();
/*! \brief
* Defined if ``libgromacs`` has been compiled in single/mixed precision.
*
* Allows detecting the compiled precision of the library through checking the
* presence of the symbol, e.g., from autoconf or other types of build systems.
*
* \ingroup module_utility
*/
void gmx_is_single_precision();
/*! \brief Return a string describing what kind of GPU suport was configured in the build.
*
* Currently returns correctly for CUDA, OpenCL and SYCL.
* Needs to be updated when adding new acceleration options.
*/
const char* getGpuImplementationString();
/*! \brief
* DOI string, or empty when not a release build.
*/
const char* gmxDOI();
/*! \brief
* Hash of the complete source released in the tarball.
*
* Empty when not a release tarball build.
*/
const char* gmxReleaseSourceChecksum();
/*! \brief
* Hash of the complete source actually used when building.
*
* Always computed when building from tarball.
*/
const char* gmxCurrentSourceChecksum();
#endif
|
gremlin/chaosk
|
src/components/Loader.js
|
<filename>src/components/Loader.js
import PropTypes from 'prop-types'
import { keyframes } from '@emotion/react'
import clsx from 'clsx'
const loaderRotateKeyframes = keyframes({
'100%': {
transform: 'rotate(360deg)',
},
})
const loaderCircleKeyframes = keyframes({
'0%': {
strokeDasharray: '1, 200',
strokeDashoffset: 0,
},
'50%': {
strokeDasharray: '89, 200',
strokeDashoffset: '-35px',
},
'100%': {
strokeDasharray: '89, 200',
strokeDashoffset: '-124px',
},
})
const Loader = ({ className, ...rest }) => (
<span
css={{
position: 'relative',
width: '1em',
height: '1em',
display: 'inline-block',
verticalAlign: 'middle',
'&::before': {
content: "''",
display: 'block',
paddingTop: '100%',
},
}}
className={clsx('CK__Loader', className)}
{...rest}
>
<svg
css={{
animation: `${loaderRotateKeyframes} 1.5s linear infinite`,
height: '100%',
transformOrigin: 'center center',
width: '100%',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
margin: 'auto',
}}
viewBox="25 25 50 50"
>
<circle
css={{
strokeDasharray: '1, 200',
strokeDashoffset: 0,
animation: `${loaderCircleKeyframes} 1.5s ease-in-out infinite`,
strokeLinecap: 'round',
stroke: 'currentColor',
fill: 'none',
strokeWidth: 2,
}}
cx="50"
cy="50"
r="20"
strokeMiterlimit="10"
/>
</svg>
</span>
)
Loader.propTypes = {
className: PropTypes.string,
}
export default Loader
|
nano-go/JCandy-Lang
|
src/main/java/com/nano/candy/interpreter/i2/builtin/type/MapObj.java
|
package com.nano.candy.interpreter.i2.builtin.type;
import com.nano.candy.interpreter.i2.builtin.CandyClass;
import com.nano.candy.interpreter.i2.builtin.CandyObject;
import com.nano.candy.interpreter.i2.builtin.type.MapObj;
import com.nano.candy.interpreter.i2.builtin.type.error.ArgumentError;
import com.nano.candy.interpreter.i2.builtin.type.error.TypeError;
import com.nano.candy.interpreter.i2.builtin.utils.ObjectHelper;
import com.nano.candy.interpreter.i2.cni.CNIEnv;
import com.nano.candy.interpreter.i2.cni.NativeClass;
import com.nano.candy.interpreter.i2.cni.NativeClassRegister;
import com.nano.candy.interpreter.i2.cni.NativeMethod;
import com.nano.candy.std.Names;
@NativeClass(name = "Map", isInheritable=true)
public final class MapObj extends CandyObject {
public static final CandyClass MAP_CLASS =
NativeClassRegister.generateNativeClass(MapObj.class);
private static final int DEFAULT_INIT_CAPACITY = 16;
private static final int MAXIMUM_CAPACITY = 1 << 30;
private static final float LOAD_FACTOR = 0.75f;
public static class Entry {
final int hash;
final CandyObject key;
CandyObject value;
Entry next;
public Entry(CandyObject key, CandyObject value, int hash) {
this.key = key;
this.value = value;
this.hash = hash;
}
public CandyObject getKey() {
return key;
}
public CandyObject getValue() {
return value;
}
public int getHash() {
return hash;
}
protected Entry findByKey(CNIEnv env, CandyObject key, int hash) {
Entry entry = this;
do {
if (entry.equals(env, key, hash)) {
return entry;
}
entry = entry.next;
} while (entry != null);
return null;
}
protected boolean equals(CNIEnv env, CandyObject key, int hash) {
return this.hash == hash &&
this.key.callEquals(env, key).value();
}
}
private static int hash(CNIEnv env, CandyObject obj) {
int hash = (int) obj.callHashCode(env).value;
return (hash >> 16) ^ hash;
}
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
private Entry[] table;
private int size;
private int initCapacity;
private int threadshould;
protected MapObj() {
super(MAP_CLASS);
this.initCapacity = DEFAULT_INIT_CAPACITY;
}
public MapObj(long initCapacity) {
super(MAP_CLASS);
setInitCapacity(initCapacity);
}
private void setInitCapacity(long initCapacity) {
if (initCapacity < 0 || initCapacity > MAXIMUM_CAPACITY) {
new ArgumentError("Illegal inital capacity: " + initCapacity)
.throwSelfNative();
}
this.initCapacity = tableSizeFor((int) initCapacity);
this.threadshould = (int) (this.initCapacity*LOAD_FACTOR);
}
private void ensureTableSize() {
if (table == null) {
table = new Entry[initCapacity];
}
if (this.size >= threadshould) {
resize();
}
}
private void resize() {
int newSize = table.length*2;
this.threadshould = (int) (newSize*LOAD_FACTOR);
MapObj.Entry[] oldTable = this.table;
this.table = new MapObj.Entry[newSize];
for (MapObj.Entry entry : oldTable) {
putEntry(entry);
}
}
private void putEntry(MapObj.Entry entry) {
Entry e = entry;
while (e != null) {
Entry n = e.next;
int index = e.hash & (this.table.length-1);
if (table[index] != null) {
e.next = table[index];
} else e.next = null;
table[index] = e;
e = n;
}
}
public CandyObject put(CNIEnv env, CandyObject key, CandyObject value) {
if (value == null) {
value = NullPointer.nil();
}
ensureTableSize();
int hash = hash(env, key);
int index = hash & (this.table.length-1);
Entry entry;
if (table[index] != null &&
(entry = table[index].findByKey(env, key, hash)) != null) {
CandyObject previousValue = entry.value;
entry.value = value;
return previousValue;
}
Entry newEntry = new Entry(key, value, hash);
newEntry.next = table[index];
table[index] = newEntry;
this.size ++;
return null;
}
public CandyObject putIfAbsent(CNIEnv env, CandyObject key, CandyObject value) {
if (value == null) {
value = NullPointer.nil();
}
ensureTableSize();
int hash = hash(env, key);
int index = hash & (this.table.length-1);
Entry entry;
if (table[index] != null &&
(entry = table[index].findByKey(env, key, hash)) != null) {
return entry.value;
}
Entry newEntry = new Entry(key, value, hash);
newEntry.next = table[index];
table[index] = newEntry;
this.size ++;
return null;
}
public CandyObject putAll(CNIEnv env, MapObj map) {
EntryIterator i = new EntryIterator(map.table);
while (i.hasNext(env)) {
put(env, i.currentEntry.key, i.currentEntry.value);
i.next(env);
}
return this;
}
public CandyObject get(CNIEnv env, CandyObject key) {
return getOrDefault(env, key, null);
}
public CandyObject getOrDefault(CNIEnv env, CandyObject key, CandyObject def) {
if (table == null) return null;
Entry entry;
int hash = hash(env, key);
int index = hash & (this.table.length-1);
if (table[index] != null &&
(entry = table[index].findByKey(env, key, hash)) != null) {
return entry.value;
}
return def;
}
public boolean contains(CNIEnv env, CandyObject key) {
return get(env, key) != null;
}
public CandyObject remove(CNIEnv env, CandyObject key) {
if (table == null) return null;
int hash = hash(env, key);
int index = hash & (this.table.length-1);
Entry previous = null;
Entry entry = table[index];
while (entry != null) {
if (entry.equals(env, key, hash)) {
if (previous == null) {
table[index] = null;
} else {
previous.next = entry.next;
}
size --;
break;
}
previous = entry;
entry = entry.next;
}
return entry != null ? entry.value : null;
}
public void clear() {
if (table != null && size != 0) {
size = 0;
for (int i = 0; i < table.length; i ++)
table[i] = null;
}
}
@NativeMethod(name = Names.METHOD_INITALIZER, argc = 1)
public CandyObject init(CNIEnv env, CandyObject[] args) {
setInitCapacity(ObjectHelper.asInteger(args[0]));
return this;
}
@NativeMethod(name = "get", argc = 1)
public CandyObject get(CNIEnv env, CandyObject[] args) {
return get(env, args[0]);
}
@NativeMethod(name = "getOrDefault", argc = 2)
public CandyObject getOrDefault(CNIEnv env, CandyObject[] args) {
return getOrDefault(env, args[0], args[1]);
}
@Override
public CandyObject getItem(CNIEnv env, CandyObject key) {
return ObjectHelper.preventNull(get(env, key));
}
@NativeMethod(name = "put", argc = 2)
public CandyObject put(CNIEnv env, CandyObject[] args) {
return put(env, args[0], args[1]);
}
@NativeMethod(name = "putIfAbsent", argc = 2)
public CandyObject putIfAbsent(CNIEnv env, CandyObject[] args) {
return putIfAbsent(env, args[0], args[1]);
}
@NativeMethod(name = "putAll", argc = 1)
public CandyObject putAll(CNIEnv env, CandyObject[] args) {
TypeError.checkTypeMatched(MAP_CLASS, args[0]);
return putAll(env, (MapObj) args[0]);
}
@Override
public CandyObject setItem(CNIEnv env, CandyObject key, CandyObject value) {
put(env, key, value);
return value;
}
@NativeMethod(name = "remove", argc = 1)
public CandyObject remove(CNIEnv env, CandyObject[] args) {
return remove(env, args[0]);
}
@NativeMethod(name = "contains", argc = 1)
public CandyObject contains(CNIEnv env, CandyObject[] args) {
return BoolObj.valueOf(contains(env, args[0]));
}
@NativeMethod(name = "length", argc = 0)
public CandyObject size(CNIEnv env, CandyObject[] args) {
return IntegerObj.valueOf(size);
}
@NativeMethod(name = "isEmpty", argc = 0)
public CandyObject isEmpty(CNIEnv env, CandyObject[] args) {
return BoolObj.valueOf(size == 0);
}
@NativeMethod(name = "clear", argc = 0)
public CandyObject clear(CNIEnv env, CandyObject[] args) {
clear();
return null;
}
@Override
public StringObj str(CNIEnv env) {
EntryIterator i = new EntryIterator(this.table);
if (!i.hasNext(env)) {
return StringObj.valueOf("{}");
}
StringBuilder builder = new StringBuilder("{");
while (true) {
String key = i.currentEntry.key.callStr(env).value();
String value = i.currentEntry.value.callStr(env).value();
builder.append(key).append(": ").append(value);
i.moveToNext();
if (!i.hasNext(env)) {
return StringObj.valueOf(builder.append("}").toString());
}
builder.append(", ");
}
}
@Override
public BoolObj equals(CNIEnv env, CandyObject operand) {
if (this == operand) {
return BoolObj.TRUE;
}
if (operand instanceof MapObj) {
MapObj map = (MapObj) operand;
if (map.size != this.size) {
return BoolObj.FALSE;
}
EntryIterator i = new EntryIterator(this.table);
while (i.hasNext(env)) {
CandyObject value = map.get(env, i.currentEntry.key);
if (value == null ||
!value.callEquals(env, i.currentEntry.value).value()) {
return BoolObj.FALSE;
}
i.moveToNext();
}
}
return BoolObj.TRUE;
}
@Override
public CandyObject iterator(CNIEnv env) {
return new EntryIterator(this.table);
}
private static class EntryIterator extends IteratorObj {
private static final Entry[] EMPTY_ENTRY = new Entry[0];
private Entry[] table;
private Entry currentEntry;
private int index;
public EntryIterator(Entry[] table) {
this.table = table == null ? EMPTY_ENTRY : table;
moveToNext();
}
private void moveToNext() {
if (currentEntry != null) {
currentEntry = currentEntry.next;
if (currentEntry != null) {
return;
}
}
while (index < table.length) {
if (table[index] != null) {
currentEntry = table[index ++];
break;
}
index ++;
}
}
@Override
public boolean hasNext(CNIEnv env) {
return currentEntry != null;
}
@Override
public CandyObject next(CNIEnv env) {
TupleObj tupleObj = new TupleObj(new CandyObject[]{
currentEntry.key, currentEntry.value
});
moveToNext();
return tupleObj;
}
}
}
|
UECIT/ecds-schema
|
src/main/java/uk/nhs/nhsia/datastandards/ecds/OtherLabourDeliveryStructure.java
|
/*
* XML Type: OtherLabourDelivery_Structure
* Namespace: http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns
* Java type: uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure
*
* Automatically generated - do not modify.
*/
package uk.nhs.nhsia.datastandards.ecds;
/**
* An XML OtherLabourDelivery_Structure(@http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns).
*
* This is a complex type.
*/
public interface OtherLabourDeliveryStructure extends org.apache.xmlbeans.XmlObject
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(OtherLabourDeliveryStructure.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s30C1180FF47174E0C8A992A2D657328B").resolveHandle("otherlabourdeliverystructure2f4ctype");
/**
* Gets the "ActivityCharacteristics" element
*/
uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure.ActivityCharacteristics getActivityCharacteristics();
/**
* Sets the "ActivityCharacteristics" element
*/
void setActivityCharacteristics(uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure.ActivityCharacteristics activityCharacteristics);
/**
* Appends and returns a new empty "ActivityCharacteristics" element
*/
uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure.ActivityCharacteristics addNewActivityCharacteristics();
/**
* Gets the "ServiceAgreementDetails" element
*/
uk.nhs.nhsia.datastandards.ecds.ServiceAgreementDetailsStructure getServiceAgreementDetails();
/**
* Sets the "ServiceAgreementDetails" element
*/
void setServiceAgreementDetails(uk.nhs.nhsia.datastandards.ecds.ServiceAgreementDetailsStructure serviceAgreementDetails);
/**
* Appends and returns a new empty "ServiceAgreementDetails" element
*/
uk.nhs.nhsia.datastandards.ecds.ServiceAgreementDetailsStructure addNewServiceAgreementDetails();
/**
* An XML ActivityCharacteristics(@http://www.nhsia.nhs.uk/DataStandards/XMLschema/CDS/ns).
*
* This is a complex type.
*/
public interface ActivityCharacteristics extends org.apache.xmlbeans.XmlObject
{
public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)
org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ActivityCharacteristics.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s30C1180FF47174E0C8A992A2D657328B").resolveHandle("activitycharacteristics8837elemtype");
/**
* Gets the "AnaestheticGivenDuringLabourOrDeliveryCode" element
*/
uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenDuringLabourOrDeliveryCodeType.Enum getAnaestheticGivenDuringLabourOrDeliveryCode();
/**
* Gets (as xml) the "AnaestheticGivenDuringLabourOrDeliveryCode" element
*/
uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenDuringLabourOrDeliveryCodeType xgetAnaestheticGivenDuringLabourOrDeliveryCode();
/**
* True if has "AnaestheticGivenDuringLabourOrDeliveryCode" element
*/
boolean isSetAnaestheticGivenDuringLabourOrDeliveryCode();
/**
* Sets the "AnaestheticGivenDuringLabourOrDeliveryCode" element
*/
void setAnaestheticGivenDuringLabourOrDeliveryCode(uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenDuringLabourOrDeliveryCodeType.Enum anaestheticGivenDuringLabourOrDeliveryCode);
/**
* Sets (as xml) the "AnaestheticGivenDuringLabourOrDeliveryCode" element
*/
void xsetAnaestheticGivenDuringLabourOrDeliveryCode(uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenDuringLabourOrDeliveryCodeType anaestheticGivenDuringLabourOrDeliveryCode);
/**
* Unsets the "AnaestheticGivenDuringLabourOrDeliveryCode" element
*/
void unsetAnaestheticGivenDuringLabourOrDeliveryCode();
/**
* Gets the "AnaestheticGivenPostLabourOrDeliveryCode" element
*/
uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenPostLabourOrDeliveryCodeType.Enum getAnaestheticGivenPostLabourOrDeliveryCode();
/**
* Gets (as xml) the "AnaestheticGivenPostLabourOrDeliveryCode" element
*/
uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenPostLabourOrDeliveryCodeType xgetAnaestheticGivenPostLabourOrDeliveryCode();
/**
* True if has "AnaestheticGivenPostLabourOrDeliveryCode" element
*/
boolean isSetAnaestheticGivenPostLabourOrDeliveryCode();
/**
* Sets the "AnaestheticGivenPostLabourOrDeliveryCode" element
*/
void setAnaestheticGivenPostLabourOrDeliveryCode(uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenPostLabourOrDeliveryCodeType.Enum anaestheticGivenPostLabourOrDeliveryCode);
/**
* Sets (as xml) the "AnaestheticGivenPostLabourOrDeliveryCode" element
*/
void xsetAnaestheticGivenPostLabourOrDeliveryCode(uk.nhs.nhsia.datastandards.ecds.AnaestheticGivenPostLabourOrDeliveryCodeType anaestheticGivenPostLabourOrDeliveryCode);
/**
* Unsets the "AnaestheticGivenPostLabourOrDeliveryCode" element
*/
void unsetAnaestheticGivenPostLabourOrDeliveryCode();
/**
* Gets the "GestationLength_LabourOnset" element
*/
int getGestationLengthLabourOnset();
/**
* Gets (as xml) the "GestationLength_LabourOnset" element
*/
uk.nhs.nhsia.datastandards.ecds.GestationLengthType xgetGestationLengthLabourOnset();
/**
* True if has "GestationLength_LabourOnset" element
*/
boolean isSetGestationLengthLabourOnset();
/**
* Sets the "GestationLength_LabourOnset" element
*/
void setGestationLengthLabourOnset(int gestationLengthLabourOnset);
/**
* Sets (as xml) the "GestationLength_LabourOnset" element
*/
void xsetGestationLengthLabourOnset(uk.nhs.nhsia.datastandards.ecds.GestationLengthType gestationLengthLabourOnset);
/**
* Unsets the "GestationLength_LabourOnset" element
*/
void unsetGestationLengthLabourOnset();
/**
* Gets the "LabourOrDeliveryOnsetMethodCode" element
*/
uk.nhs.nhsia.datastandards.ecds.LabourOrDeliveryOnsetMethodCodeType.Enum getLabourOrDeliveryOnsetMethodCode();
/**
* Gets (as xml) the "LabourOrDeliveryOnsetMethodCode" element
*/
uk.nhs.nhsia.datastandards.ecds.LabourOrDeliveryOnsetMethodCodeType xgetLabourOrDeliveryOnsetMethodCode();
/**
* True if has "LabourOrDeliveryOnsetMethodCode" element
*/
boolean isSetLabourOrDeliveryOnsetMethodCode();
/**
* Sets the "LabourOrDeliveryOnsetMethodCode" element
*/
void setLabourOrDeliveryOnsetMethodCode(uk.nhs.nhsia.datastandards.ecds.LabourOrDeliveryOnsetMethodCodeType.Enum labourOrDeliveryOnsetMethodCode);
/**
* Sets (as xml) the "LabourOrDeliveryOnsetMethodCode" element
*/
void xsetLabourOrDeliveryOnsetMethodCode(uk.nhs.nhsia.datastandards.ecds.LabourOrDeliveryOnsetMethodCodeType labourOrDeliveryOnsetMethodCode);
/**
* Unsets the "LabourOrDeliveryOnsetMethodCode" element
*/
void unsetLabourOrDeliveryOnsetMethodCode();
/**
* Gets the "DeliveryDate" element
*/
java.util.Calendar getDeliveryDate();
/**
* Gets (as xml) the "DeliveryDate" element
*/
uk.nhs.nhsia.datastandards.ecds.DeliveryDateType xgetDeliveryDate();
/**
* Sets the "DeliveryDate" element
*/
void setDeliveryDate(java.util.Calendar deliveryDate);
/**
* Sets (as xml) the "DeliveryDate" element
*/
void xsetDeliveryDate(uk.nhs.nhsia.datastandards.ecds.DeliveryDateType deliveryDate);
/**
* Gets the "AgeAtCDSActivityDate" element
*/
int getAgeAtCDSActivityDate();
/**
* Gets (as xml) the "AgeAtCDSActivityDate" element
*/
uk.nhs.nhsia.datastandards.ecds.AgeAtCDSActivityDateType xgetAgeAtCDSActivityDate();
/**
* Sets the "AgeAtCDSActivityDate" element
*/
void setAgeAtCDSActivityDate(int ageAtCDSActivityDate);
/**
* Sets (as xml) the "AgeAtCDSActivityDate" element
*/
void xsetAgeAtCDSActivityDate(uk.nhs.nhsia.datastandards.ecds.AgeAtCDSActivityDateType ageAtCDSActivityDate);
/**
* Gets the "OverseasVisitorStatusClassificationAtCDSActivityDate" element
*/
uk.nhs.nhsia.datastandards.ecds.OverseasVisitorClassificationType.Enum getOverseasVisitorStatusClassificationAtCDSActivityDate();
/**
* Gets (as xml) the "OverseasVisitorStatusClassificationAtCDSActivityDate" element
*/
uk.nhs.nhsia.datastandards.ecds.OverseasVisitorStatusClassificationAtCDSActivityDateType xgetOverseasVisitorStatusClassificationAtCDSActivityDate();
/**
* True if has "OverseasVisitorStatusClassificationAtCDSActivityDate" element
*/
boolean isSetOverseasVisitorStatusClassificationAtCDSActivityDate();
/**
* Sets the "OverseasVisitorStatusClassificationAtCDSActivityDate" element
*/
void setOverseasVisitorStatusClassificationAtCDSActivityDate(uk.nhs.nhsia.datastandards.ecds.OverseasVisitorClassificationType.Enum overseasVisitorStatusClassificationAtCDSActivityDate);
/**
* Sets (as xml) the "OverseasVisitorStatusClassificationAtCDSActivityDate" element
*/
void xsetOverseasVisitorStatusClassificationAtCDSActivityDate(uk.nhs.nhsia.datastandards.ecds.OverseasVisitorStatusClassificationAtCDSActivityDateType overseasVisitorStatusClassificationAtCDSActivityDate);
/**
* Unsets the "OverseasVisitorStatusClassificationAtCDSActivityDate" element
*/
void unsetOverseasVisitorStatusClassificationAtCDSActivityDate();
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure.ActivityCharacteristics newInstance() {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure.ActivityCharacteristics) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure.ActivityCharacteristics newInstance(org.apache.xmlbeans.XmlOptions options) {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure.ActivityCharacteristics) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
private Factory() { } // No instance of this class allowed
}
}
/**
* A factory class with static methods for creating instances
* of this type.
*/
public static final class Factory
{
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure newInstance() {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure newInstance(org.apache.xmlbeans.XmlOptions options) {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); }
/** @param xmlAsString the string value to parse */
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); }
/** @param file the file from which to load an xml document */
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); }
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return (uk.nhs.nhsia.datastandards.ecds.OtherLabourDeliveryStructure) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); }
/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */
public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {
return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); }
private Factory() { } // No instance of this class allowed
}
}
|
att-innovate/firework
|
a10-soc-devkit-ghrd/software/uboot_bsp/uboot-socfpga/arch/arm/include/asm/arch-rmobile/gpio.h
|
#ifndef __ASM_ARCH_GPIO_H
#define __ASM_ARCH_GPIO_H
#if defined(CONFIG_SH73A0)
#include "sh73a0-gpio.h"
void sh73a0_pinmux_init(void);
#elif defined(CONFIG_R8A7740)
#include "r8a7740-gpio.h"
void r8a7740_pinmux_init(void);
#elif defined(CONFIG_R8A7790)
#include "r8a7790-gpio.h"
void r8a7790_pinmux_init(void);
#elif defined(CONFIG_R8A7791)
#include "r8a7791-gpio.h"
void r8a7791_pinmux_init(void);
#elif defined(CONFIG_R8A7794)
#include "r8a7794-gpio.h"
void r8a7794_pinmux_init(void);
#endif
#endif /* __ASM_ARCH_GPIO_H */
|
navikt/spsak
|
vtp-mock/dokumentgenerator/src/main/java/no/nav/foreldrepenger/fpmock2/dokumentgenerator/foreldrepengesoknad/erketyper/SoekersRelasjonErketyper.java
|
package no.nav.foreldrepenger.fpmock2.dokumentgenerator.foreldrepengesoknad.erketyper;
import java.time.LocalDate;
import javax.xml.datatype.DatatypeConfigurationException;
import no.nav.foreldrepenger.fpmock2.dokumentgenerator.foreldrepengesoknad.util.DateUtil;
import no.nav.vedtak.felles.xml.soeknad.felles.v1.Adopsjon;
import no.nav.vedtak.felles.xml.soeknad.felles.v1.Foedsel;
import no.nav.vedtak.felles.xml.soeknad.felles.v1.Omsorgsovertakelse;
import no.nav.vedtak.felles.xml.soeknad.felles.v1.Termin;
import no.nav.vedtak.felles.xml.soeknad.kodeverk.v1.Omsorgsovertakelseaarsaker;
public class SoekersRelasjonErketyper {
public static Foedsel søkerFødselFørFødsel(){
return fødsel(1, LocalDate.now().plusDays(14));
}
public static Foedsel søkerFødselEtterFødsel(){
return fødsel(1, LocalDate.now().minusMonths(1));
}
public static Foedsel søkerFødselEtterFødselFlereBarn() {
return fødsel(2, LocalDate.now().minusMonths(1));
}
public static Foedsel søkerFødselEtterSøknadsfrist() {
return fødsel(1, LocalDate.now().minusMonths(7));
}
private static Foedsel fødsel(int antall, LocalDate foedselsDato){
Foedsel soekersRelasjonTilBarnet = new Foedsel();
soekersRelasjonTilBarnet.setAntallBarn(antall);
try {
soekersRelasjonTilBarnet.setFoedselsdato(DateUtil.convertToXMLGregorianCalendar(foedselsDato));
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return soekersRelasjonTilBarnet;
}
public static Termin søkerTerminFørTermin() {
return termin(1,true);
}
public static Termin søkerTerminEtterTermin() {
return termin(1, false);
}
private static Termin termin(int antall, boolean førTermin){
Termin termin = new Termin();
termin.setAntallBarn(antall);
try {
if (førTermin) {
termin.setTermindato(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().plusMonths(1)));
termin.setUtstedtdato(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().minusMonths(1)));
} else {
termin.setTermindato(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().minusMonths(1)));
termin.setUtstedtdato(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().minusMonths(2)));
}
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return termin;
}
public static Adopsjon søkerAdopsjon(){
return adopsjon(false);
}
public static Adopsjon søkerAdopsjonAvEktefellesBarn(){
return adopsjon(true);
}
private static Adopsjon adopsjon(boolean ektefellesBarn){
Adopsjon adopsjon = new Adopsjon();
adopsjon.setAntallBarn(1);
adopsjon.setAdopsjonAvEktefellesBarn(ektefellesBarn);
try {
adopsjon.getFoedselsdato().add(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().minusYears(10)));
adopsjon.setAnkomstdato(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().plusMonths(1)));
adopsjon.setOmsorgsovertakelsesdato(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().plusMonths(1)));
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return adopsjon;
}
public static Omsorgsovertakelse søkerOmsorgsovertakelseGrunnetDød(){
return omsorgsovertakelse("ANDRE_FORELDER_DØD");
//todo implementer OVERTATT_OMSORG, OVERTATT_OMSORG_F, ADOPTERER ALENE, men avklar først hva de betyr funksjonelt
}
private static Omsorgsovertakelse omsorgsovertakelse(String aarsak){
Omsorgsovertakelse omsorgsovertakelse = new Omsorgsovertakelse();
omsorgsovertakelse.setAntallBarn(1);
Omsorgsovertakelseaarsaker omsorgsovertakelseaarsaker = new Omsorgsovertakelseaarsaker();
omsorgsovertakelseaarsaker.setKode(aarsak);
omsorgsovertakelseaarsaker.setKodeverk("FAR_SOEKER_TYPE");
omsorgsovertakelse.setOmsorgsovertakelseaarsak(omsorgsovertakelseaarsaker);
try {
omsorgsovertakelse.setOmsorgsovertakelsesdato(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().plusMonths(1)));
omsorgsovertakelse.getFoedselsdato().add(DateUtil.convertToXMLGregorianCalendar(LocalDate.now().minusMonths(6)));
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
return omsorgsovertakelse;
}
}
|
ktSevindik/anima
|
anima/ui/scripts/avid.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2020, <NAME>
#
# This module is part of anima and is released under the MIT
# License: http://www.opensource.org/licenses/MIT
def edl_importer():
"""Helper script for AVID edl importer
"""
from anima.ui import SET_PYSIDE
SET_PYSIDE()
from anima.ui import edl_importer
reload(edl_importer)
edl_importer.UI()
|
DorinR/Politisense
|
src/controllers/BudgetController.js
|
const Firestore = require('@firestore').Firestore
const ExpenditureComputeAction = require('@action').ExpenditureComputeAction
const Utils = require('./util/ActivityVotingUtils')
function fetchAverageExpenditures (parliament = 43, year = 2019) {
return new Firestore()
.forParliament(parliament)
.atYear(year)
.AverageExpenditure()
.select()
.then(snapshot => {
const docs = []
snapshot.forEach(doc => {
docs.push(doc.data())
})
return docs
.filter(doc => {
return doc.parent === ''
})
.sort((a, b) => {
if (a.category < b.category) return -1
if (a.category > b.category) return 1
return 0
})
.map(doc => {
return { amount: Math.round(doc.amount), category: (doc.category).substr(2) }
})
})
.catch(console.error)
}
function fetchMemberExpenditures (member, parliament = 43, year = 2019) {
return new ExpenditureComputeAction({
parliament: parliament,
year: year,
member: member
})
.perform()
.then(results => {
return results
.filter(result => {
return result.parent === ''
})
.map(doc => {
return Math.round(doc.amount)
})
})
.catch(console.error)
}
exports.pastMemberExpenditures = async (req, res) => {
const ParliamentToYears = {
40: [2012],
41: [2013, 2014],
42: [2015, 2016, 2017, 2018],
43: [2019]
}
const parliament = req.body.parliament
const years = ParliamentToYears[`${parliament}`]
Promise.all(
years.map(year => {
return fetchMemberExpenditures(req.params.member, parliament, year)
})
)
.then(expenditures => {
return expenditures.map(expenditure => {
return expenditure.reduce((a, b) => { return a + b })
})
})
.then(data => {
Utils.success(res, 'expenditures retreived', data)
})
.catch(e => {
console.log(e)
Utils.error(res, 500, 'unspecified server error')
})
}
exports.budgetData = async (req, res) => {
const representativeId = req.params.id
if (!representativeId) {
res.status(404).json({
success: false,
data: {
mp: [],
avg: [],
labels: []
}
})
return
}
const [average, member] = await Promise.all([
fetchAverageExpenditures(),
fetchMemberExpenditures(representativeId)
])
if (member && average) {
const labels = average.map(item => {
if (item.category.includes('Employees')) {
return item.category.substr(0, 9)
}
return item.category
})
const avgCategoriesValues = average.map(item => item.amount)
res.status(200).json({
success: true,
data: {
mp: member,
avg: avgCategoriesValues,
labels: labels
}
})
} else {
res.status(400).json({
success: false,
data: {
mp: [],
avg: [],
labels: []
}
})
}
}
|
sriniwas-acharya/crv-temp
|
crigtt-web/src/main/java/gov/hhs/onc/crigtt/web/validate/ValidatorWebService.java
|
<reponame>sriniwas-acharya/crv-temp
package gov.hhs.onc.crigtt.web.validate;
import gov.hhs.onc.crigtt.validate.ValidatorReport;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.springframework.http.MediaType;
@Path("/validator")
public interface ValidatorWebService {
@Consumes({ MediaType.MULTIPART_FORM_DATA_VALUE })
@Path("/validate")
@POST
@Produces({ MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_HTML_VALUE, MediaType.TEXT_XML_VALUE })
public ValidatorReport validate(@Multipart(ValidatorParameters.FILE_NAME) Attachment docAttachment,
@Multipart(ValidatorParameters.TESTCASE_NAME) String testcaseId) throws Exception;
}
|
wanghaEMQ/kuma
|
src/jni/kmapi-jni.h
|
<gh_stars>100-1000
#include <stdio.h>
#include <jni.h>
#include "kmapi.h"
using namespace kuma;
#include <android/log.h>
#define KUMA_TAG "kuma-jni"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, KUMA_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, KUMA_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, KUMA_TAG, __VA_ARGS__)
extern JavaVM* java_vm;
EventLoop* get_main_loop();
JNIEnv* get_jni_env();
JNIEnv* get_current_jni_env();
void set_handle(JNIEnv *env, jobject obj, void *t);
jbyteArray as_byte_array(JNIEnv* env, uint8_t* buf, int len);
uint8_t* as_uint8_array(JNIEnv* env, jbyteArray array);
void ws_fini();
|
sheeper/jakarta-cactus
|
framework/framework-12-13-14/src/main/java/org/apache/cactus/internal/ServiceEnumeration.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 org.apache.cactus.internal;
/**
* List of valid services that the test redirectors can perform.
*
* @version $Id: ServiceEnumeration.java 238991 2004-05-22 11:34:50Z vmassol $
*/
public final class ServiceEnumeration
{
/**
* Call test method Service.
*/
public static final ServiceEnumeration CALL_TEST_SERVICE =
new ServiceEnumeration("CALL_TEST");
/**
* Get the previous test results Service.
*/
public static final ServiceEnumeration GET_RESULTS_SERVICE =
new ServiceEnumeration("GET_RESULTS");
/**
* Noop service for testing.
*/
public static final ServiceEnumeration RUN_TEST_SERVICE =
new ServiceEnumeration("RUN_TEST");
/**
* Service used to create an HTTP session so that it is returned
* in a cookie.
* @since 1.5
*/
public static final ServiceEnumeration CREATE_SESSION_SERVICE =
new ServiceEnumeration("CREATE_SESSION");
/**
* Service that returns a cactus version identifier. This is used
* to verify that the server side and client side versions of
* Cactus are the same.
* @since 1.5
*/
public static final ServiceEnumeration GET_VERSION_SERVICE =
new ServiceEnumeration("GET_VERSION");
/**
* The service's name.
*/
private String name;
/**
* Private constructor to only allow the predefined instances of the
* enumeration.
*
* @param theServiceName the name of the service
*/
private ServiceEnumeration(String theServiceName)
{
this.name = theServiceName;
}
/**
* Compares a string representing the name of the service with the service
* enumerated type.
*
* @param theString the string to compare with this Service name
* @return true if the string corresponds to the current Service
* @deprecated Use {@link ServiceEnumeration#valueOf} and identity
* comparison instead of this method
*/
public boolean equals(String theString)
{
return theString.equals(this.name);
}
/**
* Always compares object identity.
*
* {@inheritDoc}
* @see java.lang.Object#equals(Object)
* @since 1.5
*/
public boolean equals(Object theObject)
{
return super.equals(theObject);
}
/**
* Delegates to the <code>java.lang.Object</code> implementation.
*
* {@inheritDoc}
* @see java.lang.Object#equals(Object)
* @since 1.5
*/
public int hashCode()
{
return super.hashCode();
}
/**
* Returns the string representation of the service.
*
* @return the service's name
* @see java.lang.Object#toString
*/
public String toString()
{
return this.name;
}
/**
* Returns the enumeration instance corresponding to the provided service
* name.
*
* @param theName The name of the service
* @return The corresponding service instance
* @since 1.5
*/
public static ServiceEnumeration valueOf(String theName)
{
if (CALL_TEST_SERVICE.name.equals(theName))
{
return CALL_TEST_SERVICE;
}
else if (GET_RESULTS_SERVICE.name.equals(theName))
{
return GET_RESULTS_SERVICE;
}
else if (RUN_TEST_SERVICE.name.equals(theName))
{
return RUN_TEST_SERVICE;
}
else if (CREATE_SESSION_SERVICE.name.equals(theName))
{
return CREATE_SESSION_SERVICE;
}
else if (GET_VERSION_SERVICE.name.equals(theName))
{
return GET_VERSION_SERVICE;
}
return null;
}
}
|
alexamy/electric-circuit-testing-platform
|
spec/features/question/show_spec.rb
|
<reponame>alexamy/electric-circuit-testing-platform
# frozen_string_literal: true
require 'rails_helper'
feature 'User can view question', "
In order to explore questions
As an authenticated teacher
I'd like to be able to view questions
" do
given(:teacher) { create(:teacher) }
given!(:questions) { create_list(:question, 3, comment: 'question comment') }
given(:question) { questions.first }
given(:question_without_scheme) { create(:question, scheme: nil) }
given(:question_multiline) { create(:question, text: "Line 1\nLine 2") }
background { sign_in(teacher) }
describe 'Teacher' do
scenario 'views question list' do
visit teacher_questions_path
questions.each do |question|
expect(page).to have_content question.id
expect(page).to have_link question.text, href: teacher_question_path(question)
end
end
scenario 'views question' do
visit teacher_question_path(question)
expect(page).to have_content(question.text)
expect(page).to have_content(question.comment)
expect(page).to have_content(question.formula_text)
end
scenario 'views example of question' do
visit teacher_question_path(question)
expect(page).to have_selector '.question-example', text: 'Пример задания'
end
scenario 'views question without scheme' do
visit teacher_question_path(question_without_scheme)
expect(page).not_to have_selector '.question-scheme'
end
scenario 'views question with multiline text' do
visit teacher_question_path(question_multiline)
within '.question-text' do
expect(page).to have_selector 'br'
end
end
end
end
|
fake-name/ReadableWebProxy
|
WebMirror/management/rss_parser_funcs/feed_parse_extractGilaTranslation.py
|
def extractGilaTranslation(item):
"""
# Gila Translation Monster
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
ltags = [tmp.lower() for tmp in item['tags']]
if 'dawn traveler' in ltags and 'translation' in ltags:
return buildReleaseMessageWithType(item, 'Dawn Traveler', vol, chp, frag=frag, postfix=postfix)
if 'different world business symbol' in ltags and 'translation' in ltags:
return buildReleaseMessageWithType(item, 'Different World Business Symbol', vol, chp, frag=frag, postfix=postfix)
if 'star sea lord' in ltags and 'translation' in ltags:
return buildReleaseMessageWithType(item, 'Star Sea Lord', vol, chp, frag=frag, postfix=postfix)
if 'tensei shitara slime datta ken' in ltags and 'translation' in ltags:
if not 'chapter' in item['title'].lower() and chp:
frag = None
return buildReleaseMessageWithType(item, 'Tensei Shitara Slime Datta Ken', vol, chp, frag=frag, postfix=postfix)
return False
|
201244010/store
|
src/pages/DeviceManagement/Network/NetworkConfig/index.js
|
<reponame>201244010/store
import React from 'react';
import { Card, Tabs, Icon } from 'antd';
import { connect } from 'dva';
import { formatMessage } from 'umi/locale';
import { STATUS } from '@/constants/index';
import { IconBandwidth } from '@/components/IconSvg';
import QosConfig from './QosConfig';
import QosCreate from './QosConfig/QosCreate';
const { TabPane } = Tabs;
@connect(
state => ({
network: state.network,
}),
dispatch => ({
changeTabType: ({ type, value }) =>
dispatch({ type: 'network/changeTabType', payload: { type, value } }),
updateQos: payload => dispatch({ type: 'network/updateQos', payload }),
createQos: payload => dispatch({ type: 'network/createQos', payload }),
deleteQos: payload => dispatch({ type: 'network/deleteQos', payload }),
getQosInfo: payload => dispatch({ type: 'network/getQosInfo', payload }),
getQosList: payload => dispatch({ type: 'network/getQosList', payload }),
getListWithStatus: () => dispatch({ type: 'network/getListWithStatus' }),
unsubscribeTopic: () => dispatch({ type: 'network/unsubscribeTopic' }),
checkClientExist: () => dispatch({ type: 'mqttStore/checkClientExist' }),
generateTopic: payload => dispatch({ type: 'mqttStore/generateTopic', payload }),
subscribe: payload => dispatch({ type: 'mqttStore/subscribe', payload }),
clearMsg: payload => dispatch({ type: 'mqttStore/clearMsg', payload }),
setAPHandler: payload => dispatch({ type: 'network/setAPHandler', payload }),
getAPMessage: payload => dispatch({ type: 'network/getAPMessage', payload }),
})
)
class NetworkConfig extends React.PureComponent {
render() {
const {
network: {
tabType: { qos },
},
} = this.props;
return (
<Card bordered={false}>
<Tabs defaultActiveKey="1">
<TabPane
tab={
<span>
<Icon component={() => <IconBandwidth />} />
{formatMessage({ id: 'network.qos.QoS' })}
</span>
}
key="1"
>
{qos === STATUS.INIT && <QosConfig {...this.props} />}
{(qos === STATUS.UPDATE || qos === STATUS.CREATE) && (
<QosCreate {...this.props} />
)}
</TabPane>
</Tabs>
</Card>
);
}
}
export default NetworkConfig;
|
wkeese/deliteful
|
BoilerplateTextbox.js
|
/** @module delite/BoilerplateTextbox */
define([
"dcl/dcl",
"delite/register",
"delite/uacss",
"delite/Container",
"delite/FormValueWidget",
"delite/Widget",
"delite/handlebars!./BoilerplateTextbox/BoilerplateTextbox.html",
"delite/handlebars!./BoilerplateTextbox/Field.html",
"delite/activationTracker",
"requirejs-dplugins/css!./BoilerplateTextbox/BoilerplateTextbox.css"
], function (
dcl,
register,
has,
Container,
FormValueWidget,
Widget,
template,
fieldTemplate
) {
"use strict";
/**
* Non-editable section, boilerplate text.
*
* Creator should set:
*
* - textContent
*/
var Boilerplate = register("d-btb-boilerplate", [HTMLElement, Widget], {
baseClass: "d-btb-boilerplate"
});
/**
* Base class for editable fields in a BoilerplateTextbox.
*
* Creator should set the following properties:
*
* - value
* - placeholder
* - label
*
* Emits "completed" event if caret should automatically move to next element.
*/
var Field = register("d-btb-field", [HTMLElement, Widget], {
baseClass: "d-btb-field",
/**
* The `<input>` element's value.
* @member {string}
*/
value: "",
/**
* The `tabindex` of the `<input>`.
* @member {number}
* @default 0
*/
tabIndex: 0,
/**
* Whether or not the user can focus and enter data into the `<input>`.
* @member {boolean}
* @default false
*/
disabled: false,
/**
* Whether or not the user can enter data into the `<input>`.
* @member {boolean}
* @default false
*/
readOnly: false,
/**
* Placeholder text.
* @member {string}
* @default ""
*/
placeholder: "",
/**
* The `<input>`'s `type` property.
* @member {string}
* @default "text"
*/
type: "text",
/**
* The `<input>`'s `pattern` property.
* @member {string}
* @default ".*"
*/
pattern: ".*",
/**
* The `<input>`'s `autocomplete` property.
* @member {string}
* @default "off"
*/
autocomplete: "off",
label: "",
template: fieldTemplate,
refreshRendering: function (oldVals) {
if ("placeholder" in oldVals) {
var computedWidth = this.computeWidth();
if (computedWidth) {
this.style.width = computedWidth;
}
}
},
/**
* Figure out the width of this field based on the placeholder.
* If width is specified in CSS then override this method to return null.
*/
computeWidth: function () {
return this.placeholder.length + "em";
},
focus: function () {
this.focusNode.focus();
},
/**
* Called on each keystroke. Subclasses can override this method.
*/
keydownHandler: function () {
},
/**
* Called when `<input>` gets focused. Subclasses can override this method.
*/
focusHandler: function () {
}
});
/**
* Generic number field. Set placeholder, min, and max properties.
*/
var NumberField = register("d-btb-number-field", [Field], {
/**
* Number of characters user has typed into this field since it was focused.
*/
charactersTyped: 0,
// Set <input> properties so that:
// 1. When editing field, numeric virtual keyboard appears on mobile devices.
// 2. Up/down spinner *doesn't* appear on Webkit and Firefox desktop (there's no room for it).
// It appears with type=number although it can be hidden with CSS.
// 3. Firefox allows display of leading zeros. (It's not allowed for type=number, see
// http://stackoverflow.com/questions/8437529/html5-input-type-number-removes-leading-zero.)
// 4. Chrome allows us to move the caret to the end of the text. (It's not allowed for type=number,
// see https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange.)
// 5. Avoid Android behavior where evt.key = 229 instead of the actual digit typed, see
// http://stackoverflow.com/questions/30743490/
// capture-keys-typed-on-android-virtual-keyboard-using-javascript.
//
// I know setting type="tel" is weird. It might only be needed for older browsers,
// otherwise setting pattern should be sufficient.
type: "tel",
pattern: "[0-9]*",
focusHandler: function () {
this.charactersTyped = 0;
this.focusNode.selectionStart = this.focusNode.value.length; // put caret at end
},
/**
* Returns true if the input is complete and BoilerplateTextbox should
* automatically advance to next field. Input is considered complete if:
*
* 1. User has typed the maximum number of digits.
* 2. Typing another digit (any digit) would make the value exceed this.max.
*/
inputComplete: function () {
return this.charactersTyped >= this.placeholder.length || parseInt(this.value + "0", 10) > this.max;
},
keydownHandler: function (evt) {
var char = evt.key;
// Let the browser handle tab and shift-tab.
if (char === "Tab") {
return;
}
// Handle all other keys programatically, don't let the browser insert the character directly.
evt.preventDefault();
if (char === "Delete" || char === "Backspace") {
this.value = "";
this.charactersTyped = 0;
this.emit("input");
} else if (this.charactersTyped >= this.placeholder.length) {
return;
} else if (/[0-9]/.test(char)) {
var newValue;
if (this.charactersTyped === 0) {
// For the first character the user types, replace the boilerplate text (ex: "yyyy")
// with zeros followed by the character the user typed.
newValue = (new Array(this.placeholder.length)).join("0") + char;
} else {
// Otherwise, slide the other characters over and insert new character at right,
// for example if the user types "3" then "0002" is changed to "0023".
newValue = this.value.substr(1) + char;
}
// If the new value exceeds the maximum value, then ignore the keystroke.
if (this.max && parseInt(newValue, 10) > parseInt(this.max, 10)) {
return;
}
// If the new digit makes it impossible to meet the minimum value, ignore the
// keystroke. For example, if the field is two characters with a min of
// 50 and the first character the user types is 4.
var maxPossibleFutureVal = newValue +
(new Array(this.placeholder.length - this.charactersTyped)).join("9");
if (this.min && parseInt(maxPossibleFutureVal, 10) < parseInt(this.min, 10)) {
return;
}
this.value = newValue;
this.charactersTyped++;
this.emit("input");
// Send "completed" event if focus should automatically move to next field.
if (this.inputComplete()) {
this.emit("completed");
}
}
}
});
/**
* A replacement for an `<input>` that enforces a certain pattern by having editable areas separated
* by boilerplate text.
*
* The editable areas and boilerplate text are children of this widget and must exist by the time
* `initializeRendering()` completes.
*/
var BoilerplateTextbox = register("d-boilerplate-textbox", [HTMLElement, Container, FormValueWidget], {
baseClass: "d-boilerplate-textbox",
template: template,
constructor: function () {
this.on("delite-activated", this.activatedHandler.bind(this));
this.on("delite-deactivated", this.deactivatedHandler.bind(this));
},
afterInitializeRendering: function () {
this.on("input", this.nestedInputHandler.bind(this), this.containerNode);
this.on("change", this.nestedChangeHandler.bind(this), this.containerNode);
this.on("completed", this.completedHandler.bind(this), this.containerNode);
// Change tabStops to point to all the fields so that FormWidget#refreshRendering()
// sets tabIndex, disabled, and readonly properties on those fields. (But don't
// set tabindex on the boilerplate nodes)
var fields = [].slice.call(this.containerNode.querySelectorAll(".d-btb-field"));
var tabStops = [];
fields.forEach(function (input) {
this["field" + tabStops.length] = input;
tabStops.push("field" + tabStops.length);
}, this);
this.tabStops = tabStops;
},
/**
* Set values of `<input>` nodes according to specified value.
* String must exactly match formatting of `<input>` placeholder text
* combined with boilerplate text.
* @param value
*/
setInputValues: function (value) {
var start = 0;
Array.prototype.forEach.call(this.containerNode.children, function (section) {
var length = (section.placeholder || section.textContent).length;
if ("value" in section) {
section.value = value ? value.substr(start, length) : "";
}
start += length;
});
},
refreshRendering: function (oldVals) {
if ("value" in oldVals && !this.processingUserInput) {
this.setInputValues(this.value);
}
},
activatedHandler: function () {
// When the BoilerplateTextbox gets focus, focus the first <input>.
this.defer(function () {
this.containerNode.querySelector("input").focus();
});
this.classList.add("d-focused");
},
deactivatedHandler: function () {
// When the BoilerplateTextbox loses focus, fire the "change" event.
this.handleOnChange(this.value);
this.classList.remove("d-focused");
},
/**
* Get value of widget according to values of nested `<input>` nodes.
* @returns {*}
*/
getValue: function () {
// Return concatenated values of fields.
// If any of the fields are unset then return "".
var sections = [].slice.call(this.containerNode.children);
if (sections.every(function (section) { return section.value || section.textContent; })) {
return sections.map(function (section) {
return section.value || section.textContent;
}).join("");
} else {
return "";
}
},
/**
* Handler for when user types into one of the nested `<input>`'s.
* @param evt
*/
nestedInputHandler: function (evt) {
evt.stopPropagation();
this.processingUserInput = true;
this.defer(function () {
this.processingUserInput = false;
}, 1);
this.handleOnInput(this.getValue());
},
/**
* Handler for when nested `<input>` emits a "change" event.
* @param evt
*/
nestedChangeHandler: function (evt) {
evt.stopPropagation();
},
/**
* Handler for when a nested `<input>` declares that user has finished setting the value.
* Advances to the next `<input>` if there is one.
*/
completedHandler: function (evt) {
var fields = [].slice.call(this.containerNode.querySelectorAll(".d-btb-field"));
var nextIdx = fields.indexOf(evt.target) + 1;
if (nextIdx < fields.length) {
fields[nextIdx].focus();
}
},
setAttribute: dcl.superCall(function (sup) {
return function (name, value) {
sup.apply(this, arguments);
// Workaround iOS limitation where VoiceOver doesn't announce label of container.
if (has("ios")) {
var label;
if (name === "aria-label") {
label = value;
} else if (name === "aria-labelledby") {
var labelNode = this.ownerDocument.getElementById(value);
label = labelNode && labelNode.textContent;
}
if (label) {
var fields = [].slice.call(this.containerNode.querySelectorAll(".d-btb-field"));
fields.forEach(function (field) {
if (!field.origLabel) {
field.origLabel = field.label;
}
field.setAttribute("aria-label", field.origLabel + " " + label);
});
}
}
};
})
});
BoilerplateTextbox.Boilerplate = Boilerplate;
BoilerplateTextbox.Field = Field;
BoilerplateTextbox.NumberField = NumberField;
return BoilerplateTextbox;
});
|
samuelteixeiras/openwhisk
|
tests/src/whisk/common/ConfigTests.scala
|
<reponame>samuelteixeiras/openwhisk
/*
* Copyright 2015-2016 IBM Corporation
*
* 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 whisk.common
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class ConfigTests extends FlatSpec with Matchers {
"Config" should "gets default value" in {
val config = new Config(Map("a" -> "A"))
assert(config.isValid && config("a") == "A")
}
it should "not be valid when environment and prop file is not provided" in {
val config = new Config(Map("a" -> null))
assert(!config.isValid && config("a") == null)
}
it should "be valid when a prop file is provided defining required props" in {
val file = File.createTempFile("cxt", ".txt")
file.deleteOnExit()
val bw = new BufferedWriter(new FileWriter(file))
bw.write("a=A")
bw.close()
val config = new Config(Map("a" -> null), file)
assert(config.isValid && config("a") == "A")
}
it should "not be valid when a prop file is provided but does not define required props" in {
val file = File.createTempFile("cxt", ".txt")
file.deleteOnExit()
val bw = new BufferedWriter(new FileWriter(file))
bw.write("a=A")
bw.close()
val config = new Config(Map("a" -> null, "b" -> null), file)
assert(!config.isValid && config("b") == null)
}
}
|
chalk/ux
|
devwidgets/userpermissions/javascript/userpermissions.js
|
/*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.
*/
// load the master sakai object to access all Sakai OAE API methods
require(["jquery", "sakai/sakai.api.core"], function($, sakai){
/**
* @name sakai.userpermissions
*
* @class userpermissions
*
* @version 0.0.1
* @param {String} tuid Unique id of the widget
* @param {Boolean} showSettings Show the settings of the widget or not
*/
sakai_global.userpermissions = function(tuid, showSettings){
var contextData = false;
///////////////////////////////////////
// Retrieving the current permission //
///////////////////////////////////////
var getCurrentPermission = function(){
var currentPath = contextData.path;
var page = false;
if (currentPath.indexOf("/") !== -1) {
var split = currentPath.split("/");
page = sakai_global.user.pubdata.structure0[split[0]][split[1]];
} else {
page = sakai_global.user.pubdata.structure0[currentPath];
}
var permission = page._view;
$("#userpermissions_area_title").text(sakai.api.i18n.General.process(page._title, sakai.api.User.data.me));
$("#userpermissions_content_container").html(sakai.api.Util.TemplateRenderer("userpermissions_content_template", {
"permission": permission
}));
};
/////////////////////////////
// Storing new permissions //
/////////////////////////////
/**
* Notify the user that the permissions have been changed or an error has occurred
* @param {Boolean} success Indicates the success or failure of setting the permissions
*/
var permissionsSet = function(success, data){
if (success) {
// Hide the dialog
$("#userpermissions_container").jqmHide();
// Show gritter notification
sakai.api.Util.notification.show($("#userpermissions_notification_title").text(), $("#userpermissions_notification_body").text());
}else{
// Show an error notification
sakai.api.Util.notification.show($("#userpermissions_notification_title").text(), $("#userpermissions_notification_error_body").text(), sakai.api.Util.notification.type.ERROR);
}
};
/**
* Apply the selected permissions to the page
*/
var applyPermissions = function(){
var currentPath = contextData.path;
var page = false;
var split = "";
if (currentPath.indexOf("/") !== -1) {
split = currentPath.split("/");
page = sakai_global.user.pubdata.structure0[split[0]][split[1]];
} else {
page = sakai_global.user.pubdata.structure0[currentPath];
}
// Collect selected permission
var permission = $("#userpermissions_area_general_visibility").val();
page._view = permission;
sakai.api.Server.saveJSON("/~" + sakai.data.me.user.userid + "/public/pubspace", {
"structure0": $.toJSON(sakai_global.user.pubdata.structure0)
});
if (_.indexOf(["library", "memberships", "contacts"], currentPath) === -1) {
sakai.api.Content.setACLsOnPath("/~" + sakai.data.me.user.userid + "/public/authprofile/" + split[1], permission.toString(), sakai.data.me.user.userid, permissionsSet);
} else {
permissionsSet(true);
}
};
/////////////////////////////////
// Modal dialog initialization //
/////////////////////////////////
var initializeOverlay = function(){
$("#userpermissions_container").jqmShow();
};
$("#userpermissions_container").jqm({
modal: true,
overlay: 20,
toTop: true,
zIndex: 3000
});
/////////////////////
// Internal events //
/////////////////////
$("#userpermissions_apply_permissions").live("click", function(){
applyPermissions();
});
/////////////////////
// External events //
/////////////////////
$(window).bind("permissions.area.trigger", function(ev, _contextData){
contextData = _contextData
getCurrentPermission();
initializeOverlay();
});
};
// inform Sakai OAE that this widget has loaded and is ready to run
sakai.api.Widgets.widgetLoader.informOnLoad("userpermissions");
});
|
marmolak/gray386linux
|
src/linux-3.7.10/drivers/scsi/qla2xxx/qla_inline.h
|
<reponame>marmolak/gray386linux
/*
* QLogic Fibre Channel HBA Driver
* Copyright (c) 2003-2012 QLogic Corporation
*
* See LICENSE.qla2xxx for copyright and licensing details.
*/
/*
* qla2x00_debounce_register
* Debounce register.
*
* Input:
* port = register address.
*
* Returns:
* register value.
*/
static __inline__ uint16_t
qla2x00_debounce_register(volatile uint16_t __iomem *addr)
{
volatile uint16_t first;
volatile uint16_t second;
do {
first = RD_REG_WORD(addr);
barrier();
cpu_relax();
second = RD_REG_WORD(addr);
} while (first != second);
return (first);
}
static inline void
qla2x00_poll(struct rsp_que *rsp)
{
unsigned long flags;
struct qla_hw_data *ha = rsp->hw;
local_irq_save(flags);
if (IS_QLA82XX(ha))
qla82xx_poll(0, rsp);
else
ha->isp_ops->intr_handler(0, rsp);
local_irq_restore(flags);
}
static inline uint8_t *
host_to_fcp_swap(uint8_t *fcp, uint32_t bsize)
{
uint32_t *ifcp = (uint32_t *) fcp;
uint32_t *ofcp = (uint32_t *) fcp;
uint32_t iter = bsize >> 2;
for (; iter ; iter--)
*ofcp++ = swab32(*ifcp++);
return fcp;
}
static inline void
qla2x00_set_reserved_loop_ids(struct qla_hw_data *ha)
{
int i;
if (IS_FWI2_CAPABLE(ha))
return;
for (i = 0; i < SNS_FIRST_LOOP_ID; i++)
set_bit(i, ha->loop_id_map);
set_bit(MANAGEMENT_SERVER, ha->loop_id_map);
set_bit(BROADCAST, ha->loop_id_map);
}
static inline int
qla2x00_is_reserved_id(scsi_qla_host_t *vha, uint16_t loop_id)
{
struct qla_hw_data *ha = vha->hw;
if (IS_FWI2_CAPABLE(ha))
return (loop_id > NPH_LAST_HANDLE);
return ((loop_id > ha->max_loop_id && loop_id < SNS_FIRST_LOOP_ID) ||
loop_id == MANAGEMENT_SERVER || loop_id == BROADCAST);
}
static inline void
qla2x00_clear_loop_id(fc_port_t *fcport) {
struct qla_hw_data *ha = fcport->vha->hw;
if (fcport->loop_id == FC_NO_LOOP_ID ||
qla2x00_is_reserved_id(fcport->vha, fcport->loop_id))
return;
clear_bit(fcport->loop_id, ha->loop_id_map);
fcport->loop_id = FC_NO_LOOP_ID;
}
static inline void
qla2x00_clean_dsd_pool(struct qla_hw_data *ha, srb_t *sp)
{
struct dsd_dma *dsd_ptr, *tdsd_ptr;
struct crc_context *ctx;
ctx = (struct crc_context *)GET_CMD_CTX_SP(sp);
/* clean up allocated prev pool */
list_for_each_entry_safe(dsd_ptr, tdsd_ptr,
&ctx->dsd_list, list) {
dma_pool_free(ha->dl_dma_pool, dsd_ptr->dsd_addr,
dsd_ptr->dsd_list_dma);
list_del(&dsd_ptr->list);
kfree(dsd_ptr);
}
INIT_LIST_HEAD(&ctx->dsd_list);
}
static inline void
qla2x00_set_fcport_state(fc_port_t *fcport, int state)
{
int old_state;
old_state = atomic_read(&fcport->state);
atomic_set(&fcport->state, state);
/* Don't print state transitions during initial allocation of fcport */
if (old_state && old_state != state) {
ql_dbg(ql_dbg_disc, fcport->vha, 0x207d,
"FCPort state transitioned from %s to %s - "
"portid=%02x%02x%02x.\n",
port_state_str[old_state], port_state_str[state],
fcport->d_id.b.domain, fcport->d_id.b.area,
fcport->d_id.b.al_pa);
}
}
static inline int
qla2x00_hba_err_chk_enabled(srb_t *sp)
{
/*
* Uncomment when corresponding SCSI changes are done.
*
if (!sp->cmd->prot_chk)
return 0;
*
*/
switch (scsi_get_prot_op(GET_CMD_SP(sp))) {
case SCSI_PROT_READ_STRIP:
case SCSI_PROT_WRITE_INSERT:
if (ql2xenablehba_err_chk >= 1)
return 1;
break;
case SCSI_PROT_READ_PASS:
case SCSI_PROT_WRITE_PASS:
if (ql2xenablehba_err_chk >= 2)
return 1;
break;
case SCSI_PROT_READ_INSERT:
case SCSI_PROT_WRITE_STRIP:
return 1;
}
return 0;
}
static inline int
qla2x00_reset_active(scsi_qla_host_t *vha)
{
scsi_qla_host_t *base_vha = pci_get_drvdata(vha->hw->pdev);
/* Test appropriate base-vha and vha flags. */
return test_bit(ISP_ABORT_NEEDED, &base_vha->dpc_flags) ||
test_bit(ABORT_ISP_ACTIVE, &base_vha->dpc_flags) ||
test_bit(ISP_ABORT_RETRY, &base_vha->dpc_flags) ||
test_bit(ISP_ABORT_NEEDED, &vha->dpc_flags) ||
test_bit(ABORT_ISP_ACTIVE, &vha->dpc_flags);
}
static inline srb_t *
qla2x00_get_sp(scsi_qla_host_t *vha, fc_port_t *fcport, gfp_t flag)
{
srb_t *sp = NULL;
struct qla_hw_data *ha = vha->hw;
uint8_t bail;
QLA_VHA_MARK_BUSY(vha, bail);
if (unlikely(bail))
return NULL;
sp = mempool_alloc(ha->srb_mempool, flag);
if (!sp)
goto done;
memset(sp, 0, sizeof(*sp));
sp->fcport = fcport;
sp->iocbs = 1;
done:
if (!sp)
QLA_VHA_MARK_NOT_BUSY(vha);
return sp;
}
static inline void
qla2x00_init_timer(srb_t *sp, unsigned long tmo)
{
init_timer(&sp->u.iocb_cmd.timer);
sp->u.iocb_cmd.timer.expires = jiffies + tmo * HZ;
sp->u.iocb_cmd.timer.data = (unsigned long)sp;
sp->u.iocb_cmd.timer.function = qla2x00_sp_timeout;
add_timer(&sp->u.iocb_cmd.timer);
sp->free = qla2x00_sp_free;
}
static inline int
qla2x00_gid_list_size(struct qla_hw_data *ha)
{
return sizeof(struct gid_list_info) * ha->max_fibre_devices;
}
|
BeanGreen247/surf
|
glib-2.64.0/gio/tests/test-pipe-unix.h
|
/* Unix pipe-to-self. This is a utility module for tests, not a test.
*
* Copyright © 2008-2010 Red Hat, Inc.
* Copyright © 2011 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
*
* Author: <NAME> <<EMAIL>>
*/
#ifndef TEST_PIPE_UNIX_H
#define TEST_PIPE_UNIX_H
#include <gio/gio.h>
gboolean test_pipe (GInputStream **is,
GOutputStream **os,
GError **error);
gboolean test_bidi_pipe (GIOStream **left,
GIOStream **right,
GError **error);
#endif /* guard */
|
learningandgrowing/Data-structures-problems
|
mergesortedarays.py
|
def mergesortedarrays(arr1,arr2):
i = 0
j = 0
len1 = len(arr1)
len2 = len(arr2)
arr = []
while (i<len1) and (j < len2):
if arr1[i]<arr2[j]:
arr.append(arr1[i])
i = i + 1
else:
arr.append(arr2[j])
j += 1
while i < len1:
arr.append(arr1[i])
i += 1
while j < len2:
arr.append(arr2[j])
j += 1
return arr
m = int(input())
arr1 = list(int(x) for x in input().strip().split())
n = int(input())
arr2 = list(int(y) for y in input().strip().split())
arr = mergesortedarrays(arr1,arr2)
print(arr)
|
lordmarkm/pyxis
|
pyxis-security/src/main/java/com/pyxis/security/service/UserAccountServiceCustomImpl.java
|
<reponame>lordmarkm/pyxis<gh_stars>0
package com.pyxis.security.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.pyxis.commons.model.security.UserAccount;
import com.pyxis.commons.service.PyxisJpaServiceCustomImpl;
import com.pyxis.security.dto.UserAccountInfo;
public class UserAccountServiceCustomImpl
extends PyxisJpaServiceCustomImpl<UserAccount, UserAccountInfo, UserAccountService>
implements UserAccountServiceCustom {
@Autowired
private UserAccountService userAccountService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<UserAccount> user = userAccountService.findByUsername(username);
if (!user.isPresent()) {
throw new UsernameNotFoundException("Could not find user with name '" + username + "'");
}
return user.get();
}
@Override
public Optional<UserAccountInfo> findByUsernameInfo(String username) {
return userAccountService.findByUsername(username)
.map(userAccount -> mapper.map(userAccount, UserAccountInfo.class));
}
}
|
mindv0rtex/DearPyGui
|
DearPyGui/src/core/AppItems/basic/mvText.h
|
#pragma once
#include "mvTypeBases.h"
//-----------------------------------------------------------------------------
// Widget Index
//
// * mvText
// * mvLabelText
//
//-----------------------------------------------------------------------------
namespace Marvel {
//-----------------------------------------------------------------------------
// mvText
//-----------------------------------------------------------------------------
MV_REGISTER_WIDGET(mvText, MV_ITEM_DESC_DEFAULT, StorageValueTypes::String, 1);
class mvText : public mvStringPtrBase
{
public:
static void InsertParser(std::map<std::string, mvPythonParser>* parsers);
MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvText, add_text)
MV_CREATE_CONSTANT(mvThemeCol_Text_Text, ImGuiCol_Text, 0L);
MV_START_EXTRA_COMMANDS
MV_END_EXTRA_COMMANDS
MV_START_GENERAL_CONSTANTS
MV_END_GENERAL_CONSTANTS
MV_START_COLOR_CONSTANTS
MV_CREATE_CONSTANT_PAIR(mvThemeCol_Text_Text, mvColor(255, 255, 255, 255))
MV_END_COLOR_CONSTANTS
MV_START_STYLE_CONSTANTS
MV_END_STYLE_CONSTANTS
public:
mvText(const std::string& name);
void draw(ImDrawList* drawlist, float x, float y) override;
void setExtraConfigDict(PyObject* dict) override;
void getExtraConfigDict(PyObject* dict) override;
private:
mvColor m_color = {-1.0f, 0.0f, 0.0f, 1.0f};
int m_wrap = -1;
bool m_bullet = false;
};
//-----------------------------------------------------------------------------
// mvLabelText
//-----------------------------------------------------------------------------
MV_REGISTER_WIDGET(mvLabelText, MV_ITEM_DESC_DEFAULT, StorageValueTypes::String, 1);
class mvLabelText : public mvStringPtrBase
{
public:
static void InsertParser(std::map<std::string, mvPythonParser>* parsers);
MV_APPLY_WIDGET_REGISTRATION(mvAppItemType::mvLabelText, add_label_text)
MV_CREATE_CONSTANT(mvThemeCol_LabelText_Text , ImGuiCol_Text, 0L);
MV_CREATE_CONSTANT(mvThemeStyle_LabelText_PaddingX , ImGuiCol_TitleBg, 0L);
MV_CREATE_CONSTANT(mvThemeStyle_LabelText_PaddingY , ImGuiCol_TitleBg, 1L);
MV_CREATE_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingX , 14L, 0L);
MV_CREATE_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingY , 14L, 1L);
MV_START_EXTRA_COMMANDS
MV_END_EXTRA_COMMANDS
MV_START_GENERAL_CONSTANTS
MV_END_GENERAL_CONSTANTS
MV_START_COLOR_CONSTANTS
MV_CREATE_CONSTANT_PAIR(mvThemeCol_LabelText_Text, mvColor(255, 255, 255, 255))
MV_END_COLOR_CONSTANTS
MV_START_STYLE_CONSTANTS
MV_ADD_CONSTANT(mvThemeStyle_LabelText_PaddingX , 4, 20),
MV_ADD_CONSTANT(mvThemeStyle_LabelText_PaddingY , 3, 20),
MV_ADD_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingX , 4, 20),
MV_ADD_CONSTANT(mvThemeStyle_LabelText_ItemInnerSpacingY , 4, 20),
MV_END_STYLE_CONSTANTS
public:
mvLabelText(const std::string& name);
void draw(ImDrawList* drawlist, float x, float y) override;
void setExtraConfigDict(PyObject* dict) override;
void getExtraConfigDict(PyObject* dict) override;
private:
mvColor m_color = { -1.0f, 0.0f, 0.0f, 1.0f};
};
}
|
kirchnerlab/MSTK
|
tests/fe/QuickCharge-test.cpp
|
<filename>tests/fe/QuickCharge-test.cpp<gh_stars>1-10
/*
* QuickCharge-test.cpp
*
* Copyright (C) 2012 <NAME>
*
* This file is part of the Mass Spectrometry Toolkit (MSTK).
*
* 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.
*/
#include "unittest.hxx"
#include "utilities.hpp"
#include <MSTK/fe/QuickCharge.hpp>
#include <MSTK/fe/types/Xic.hpp>
#include <MSTK/fe/XicTraits.hpp>
#include <MSTK/common/Types.hpp>
#include <iostream>
#include <set>
using namespace mstk::fe;
using namespace mstk;
struct QuickChargeTestSuite : vigra::test_suite {
QuickChargeTestSuite() : vigra::test_suite("QuickCharge") {
add(testCase(&QuickChargeTestSuite::test));
}
void test() {
double mzs[] =
{ 100.001, 100.2502, 100.33, 100.501, 101.001 };
int expectedCharges[] = { 4, 3, 2, 13, 6 };
std::vector<double> masses(&mzs[0], &mzs[4]);
IsotopePattern ip = makeIsotopePattern(masses, 3324.0, 1);
QuickCharge qc;
std::vector<int> charges;
qc(ip.begin(), ip.end(), std::back_inserter(charges));
shouldEqual(charges.size(), static_cast<Size>(5));
for (Size k = 0; k < charges.size(); ++k) {
shouldEqual(charges[k], expectedCharges[k]);
}
}
};
int main()
{
QuickChargeTestSuite test;
int success = test.run();
std::cout << test.report() << std::endl;
return success;
}
|
VirtualLG/vimrc
|
my_plugins/youcompleteme/third_party/ycmd/ycmd/tests/javascript/get_completions_test.py
|
# Copyright (C) 2021 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd 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 ycmd. If not, see <http://www.gnu.org/licenses/>.
from hamcrest import ( assert_that,
contains_exactly,
contains_inanyorder,
equal_to,
has_entries,
has_item,
matches_regexp )
from unittest import TestCase
import json
import requests
from ycmd.tests.javascript import setUpModule, tearDownModule # noqa
from ycmd.tests.javascript import IsolatedYcmd, PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest,
ChunkMatcher,
CompletionEntryMatcher,
LocationMatcher )
from ycmd.utils import ReadFile
def RunTest( app, test ):
contents = ReadFile( test[ 'request' ][ 'filepath' ] )
def CombineRequest( request, data ):
kw = request
request.update( data )
return BuildRequest( **kw )
app.post_json(
'/event_notification',
CombineRequest( test[ 'request' ], {
'contents': contents,
'filetype': 'javascript',
'event_name': 'BufferVisit'
} )
)
response = app.post_json(
'/completions',
CombineRequest( test[ 'request' ], {
'contents': contents,
'filetype': 'javascript',
'force_semantic': True
} )
)
print( 'completer response: ', json.dumps( response.json, indent = 2 ) )
assert_that( response.status_code,
equal_to( test[ 'expect' ][ 'response' ] ) )
assert_that( response.json, test[ 'expect' ][ 'data' ] )
class GetCompletionsTest( TestCase ):
@SharedYcmd
def test_GetCompletions_Basic( self, app ):
RunTest( app, {
'description': 'Extra and detailed info when completions are methods',
'request': {
'line_num': 14,
'column_num': 6,
'filepath': PathToTestFile( 'test.js' )
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains_inanyorder(
CompletionEntryMatcher(
'methodA',
'(method) Foo.methodA(): void',
extra_params = {
'kind': 'method',
'detailed_info': '(method) Foo.methodA(): void\n\n'
'Unicode string: 说话'
}
),
CompletionEntryMatcher(
'methodB',
'(method) Foo.methodB(): void',
extra_params = {
'kind': 'method',
'detailed_info': '(method) Foo.methodB(): void'
}
),
CompletionEntryMatcher(
'methodC',
'(method) Foo.methodC(foo: any, bar: any): void',
extra_params = {
'kind': 'method',
'detailed_info': '(method) Foo.methodC(foo: any, '
'bar: any): void'
}
)
)
} )
}
} )
@SharedYcmd
def test_GetCompletions_Keyword( self, app ):
RunTest( app, {
'description': 'No extra and detailed info when completion is a keyword',
'request': {
'line_num': 1,
'column_num': 5,
'filepath': PathToTestFile( 'test.js' ),
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': has_item( {
'insertion_text': 'class',
'kind': 'keyword',
'extra_data': {}
} )
} )
}
} )
@SharedYcmd
def test_GetCompletions_AutoImport( self, app ):
filepath = PathToTestFile( 'test.js' )
RunTest( app, {
'description': 'Symbol from external module can be completed and its '
'completion contains fixits to automatically import it',
'request': {
'line_num': 36,
'column_num': 5,
'filepath': filepath,
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': has_item( has_entries( {
'insertion_text': 'Bår',
'extra_menu_info': 'class Bår',
'detailed_info': 'class Bår',
'kind': 'class',
'extra_data': has_entries( {
'fixits': contains_inanyorder(
has_entries( {
'text': 'Import \'Bår\' from module "./unicode"',
'chunks': contains_exactly(
ChunkMatcher(
matches_regexp( '^import { Bår } from "./unicode";\r?\n'
'\r?\n' ),
LocationMatcher( filepath, 1, 1 ),
LocationMatcher( filepath, 1, 1 )
)
),
'location': LocationMatcher( filepath, 36, 5 )
} )
)
} )
} ) )
} )
}
} )
@IsolatedYcmd()
def test_GetCompletions_IgnoreIdentifiers( self, app ):
RunTest( app, {
'description': 'Identifier "test" is not returned as a suggestion',
'request': {
'line_num': 5,
'column_num': 6,
'filepath': PathToTestFile( 'identifier', 'test.js' ),
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains_exactly(
CompletionEntryMatcher(
'foo',
'(property) foo: string',
extra_params = {
'kind': 'property',
'detailed_info': '(property) foo: string'
}
)
)
} )
}
} )
|
reels-research/iOS-Private-Frameworks
|
NeutrinoCore.framework/NUJSTime.h
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/NeutrinoCore.framework/NeutrinoCore
*/
@interface NUJSTime : NUJSRational
@property (readonly) struct { long long x1; int x2; unsigned int x3; long long x4; } time;
@property (readonly) NSValue *value;
- (id)initWithTime:(struct { long long x1; int x2; unsigned int x3; long long x4; })arg1;
- (id)nu_unwrapJSValue;
- (struct { long long x1; int x2; unsigned int x3; long long x4; })time;
- (id)value;
@end
|
oguzcanphilips/embeddedinfralib
|
hal/interfaces/test/TestFlash.cpp
|
#include "gtest/gtest.h"
#include "hal/interfaces/Flash.hpp"
#include "hal/interfaces/test_doubles/FlashStub.hpp"
class FlashAddressTest
: public testing::Test
{
public:
FlashAddressTest()
: flash(3, 7)
{}
hal::FlashStub flash;
};
TEST_F(FlashAddressTest, StartAddress)
{
EXPECT_EQ(0, flash.SectorOfAddress(0));
EXPECT_EQ(0, flash.AddressOffsetInSector(0));
EXPECT_TRUE(flash.AtStartOfSector(0));
}
TEST_F(FlashAddressTest, AddressOfSector)
{
EXPECT_EQ(7, flash.AddressOfSector(1));
}
TEST_F(FlashAddressTest, StartOfSector)
{
EXPECT_EQ(0, flash.StartOfSector(1));
}
TEST_F(FlashAddressTest, StartOfNextSector)
{
EXPECT_EQ(7, flash.StartOfNextSector(0));
EXPECT_TRUE(flash.AtStartOfSector(7));
}
TEST_F(FlashAddressTest, StartOfNextSectorMidwayInASector)
{
EXPECT_EQ(7, flash.StartOfNextSector(1));
EXPECT_TRUE(flash.AtStartOfSector(7));
}
TEST_F(FlashAddressTest, StartOfPreviousSector)
{
EXPECT_EQ(0, flash.StartOfPreviousSector(7));
EXPECT_TRUE(flash.AtStartOfSector(flash.StartOfPreviousSector(7)));
}
TEST_F(FlashAddressTest, StartOfPreviousSectorMidwayInASector)
{
EXPECT_EQ(0, flash.StartOfPreviousSector(8));
EXPECT_TRUE(flash.AtStartOfSector(flash.StartOfPreviousSector(8)));
}
|
XiaoSenLuo/c-cpp-math-library
|
itpp4.3.1-library/static-lib/include/itpp/stat/misc_stat.h
|
/*!
* \file
* \brief Miscellaneous statistics functions and classes - header file
* \author <NAME>, <NAME> and <NAME>
*
* -------------------------------------------------------------------------
*
* Copyright (C) 1995-2010 (see AUTHORS file for a list of contributors)
*
* This file is part of IT++ - a C++ library of mathematical, signal
* processing, speech processing, and communications classes and functions.
*
* IT++ is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* IT++ 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 IT++. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
#ifndef MISC_STAT_H
#define MISC_STAT_H
#include <itpp/base/math/min_max.h>
#include <itpp/base/mat.h>
#include <itpp/base/math/elem_math.h>
#include <itpp/base/matfunc.h>
#include <itpp/itexports.h>
namespace itpp
{
//! \addtogroup statistics
//!@{
/*!
\brief A class for sampling a signal and calculating statistics
*/
class ITPP_EXPORT Stat
{
public:
//! Default constructor
Stat() {clear();}
//! Destructor
virtual ~Stat() {}
//! Clear statistics
virtual void clear() {
_n_overflows = 0;
_n_samples = 0;
_n_zeros = 0;
_max = 0.0;
_min = 0.0;
_sqr_sum = 0.0;
_sum = 0.0;
}
//! Register a sample and flag for overflow
virtual void sample(const double s, const bool overflow = false) {
_n_samples++;
_sum += s;
_sqr_sum += s * s;
if (s < _min) _min = s;
if (s > _max) _max = s;
if (overflow) _n_overflows++;
if (s == 0.0) _n_zeros++;
}
//! Number of reported overflows
int n_overflows() const {return _n_overflows;}
//! Number of samples
int n_samples() const {return _n_samples;}
//! Number of zero samples
int n_zeros() const {return _n_zeros;}
//! Average over all samples
double avg() const {return _sum / _n_samples;}
//! Maximum sample
double max() const {return _max;}
//! Minimum sample
double min() const {return _min;}
//! Standard deviation of all samples
double sigma() const {
double sigma2 = _sqr_sum / _n_samples - avg() * avg();
return std::sqrt(sigma2 < 0 ? 0 : sigma2);
}
//! Squared sum of all samples
double sqr_sum() const {return _sqr_sum;}
//! Sum of all samples
double sum() const {return _sum;}
//! Histogram over all samples (not implemented yet)
vec histogram() const {return vec(0);}
protected:
//! Number of reported overflows
int _n_overflows;
//! Number of samples
int _n_samples;
//! Number of zero samples
int _n_zeros;
//! Maximum sample
double _max;
//! Minimum sample
double _min;
//! Squared sum of all samples
double _sqr_sum;
//! Sum of all samples
double _sum;
};
//! The mean value
ITPP_EXPORT double mean(const vec &v);
//! The mean value
ITPP_EXPORT std::complex<double> mean(const cvec &v);
//! The mean value
ITPP_EXPORT double mean(const svec &v);
//! The mean value
ITPP_EXPORT double mean(const ivec &v);
//! The mean value
ITPP_EXPORT double mean(const mat &m);
//! The mean value
ITPP_EXPORT std::complex<double> mean(const cmat &m);
//! The mean value
ITPP_EXPORT double mean(const smat &m);
//! The mean value
ITPP_EXPORT double mean(const imat &m);
//! The geometric mean of a vector
template<class T>
double geometric_mean(const Vec<T> &v)
{
return std::exp(std::log(static_cast<double>(prod(v))) / v.length());
}
//! The geometric mean of a matrix
template<class T>
double geometric_mean(const Mat<T> &m)
{
return std::exp(std::log(static_cast<double>(prod(prod(m))))
/ (m.rows() * m.cols()));
}
//! The median
template<class T>
double median(const Vec<T> &v)
{
Vec<T> invect(v);
sort(invect);
return (double)(invect[(invect.length()-1)/2] + invect[invect.length()/2]) / 2.0;
}
//! Calculate the 2-norm: norm(v)=sqrt(sum(abs(v).^2))
ITPP_EXPORT double norm(const cvec &v);
//! Calculate the 2-norm: norm(v)=sqrt(sum(abs(v).^2))
template<class T>
double norm(const Vec<T> &v)
{
double E = 0.0;
for (int i = 0; i < v.size(); i++)
E += sqr(static_cast<double>(v[i]));
return std::sqrt(E);
}
//! Calculate the p-norm: norm(v,p)=sum(abs(v).^2)^(1/p)
ITPP_EXPORT double norm(const cvec &v, int p);
//! Calculate the p-norm: norm(v,p)=sum(abs(v).^2)^(1/p)
template<class T>
double norm(const Vec<T> &v, int p)
{
double E = 0.0;
for (int i = 0; i < v.size(); i++)
E += std::pow(fabs(static_cast<double>(v[i])), static_cast<double>(p));
return std::pow(E, 1.0 / p);
}
//! Calculate the Frobenius norm for s = "fro" (equal to 2-norm)
ITPP_EXPORT double norm(const cvec &v, const std::string &s);
//! Calculate the Frobenius norm for s = "fro" (equal to 2-norm)
template<class T>
double norm(const Vec<T> &v, const std::string &s)
{
it_assert(s == "fro", "norm(): Unrecognised norm");
double E = 0.0;
for (int i = 0; i < v.size(); i++)
E += sqr(static_cast<double>(v[i]));
return std::sqrt(E);
}
/*!
* Calculate the p-norm of a real matrix
*
* p = 1: max(svd(m))
* p = 2: max(sum(abs(X)))
*
* Default if no p is given is the 2-norm
*/
ITPP_EXPORT double norm(const mat &m, int p = 2);
/*!
* Calculate the p-norm of a complex matrix
*
* p = 1: max(svd(m))
* p = 2: max(sum(abs(X)))
*
* Default if no p is given is the 2-norm
*/
ITPP_EXPORT double norm(const cmat &m, int p = 2);
//! Calculate the Frobenius norm of a matrix for s = "fro"
ITPP_EXPORT double norm(const mat &m, const std::string &s);
//! Calculate the Frobenius norm of a matrix for s = "fro"
ITPP_EXPORT double norm(const cmat &m, const std::string &s);
//! The variance of the elements in the vector. Normalized with N-1 to be unbiased.
ITPP_EXPORT double variance(const cvec &v);
//! The variance of the elements in the vector. Normalized with N-1 to be unbiased.
template<class T>
double variance(const Vec<T> &v)
{
int len = v.size();
const T *p = v._data();
double sum = 0.0, sq_sum = 0.0;
for (int i = 0; i < len; i++, p++) {
sum += *p;
sq_sum += *p * *p;
}
return (double)(sq_sum - sum*sum / len) / (len - 1);
}
//! Calculate the energy: squared 2-norm. energy(v)=sum(abs(v).^2)
template<class T>
double energy(const Vec<T> &v)
{
return sqr(norm(v));
}
//! Return true if the input value \c x is within the tolerance \c tol of the reference value \c xref
inline bool within_tolerance(double x, double xref, double tol = 1e-14)
{
return (fabs(x -xref) <= tol) ? true : false;
}
//! Return true if the input value \c x is within the tolerance \c tol of the reference value \c xref
inline bool within_tolerance(std::complex<double> x, std::complex<double> xref, double tol = 1e-14)
{
return (abs(x -xref) <= tol) ? true : false;
}
//! Return true if the input vector \c x is elementwise within the tolerance \c tol of the reference vector \c xref
inline bool within_tolerance(const vec &x, const vec &xref, double tol = 1e-14)
{
return (max(abs(x -xref)) <= tol) ? true : false;
}
//! Return true if the input vector \c x is elementwise within the tolerance \c tol of the reference vector \c xref
inline bool within_tolerance(const cvec &x, const cvec &xref, double tol = 1e-14)
{
return (max(abs(x -xref)) <= tol) ? true : false;
}
//! Return true if the input matrix \c X is elementwise within the tolerance \c tol of the reference matrix \c Xref
inline bool within_tolerance(const mat &X, const mat &Xref, double tol = 1e-14)
{
return (max(max(abs(X -Xref))) <= tol) ? true : false;
}
//! Return true if the input matrix \c X is elementwise within the tolerance \c tol of the reference matrix \c Xref
inline bool within_tolerance(const cmat &X, const cmat &Xref, double tol = 1e-14)
{
return (max(max(abs(X -Xref))) <= tol) ? true : false;
}
/*!
\brief Calculate the central moment of vector x
The \f$r\f$th sample central moment of the samples in the vector
\f$ \mathbf{x} \f$ is defined as
\f[
m_r = \mathrm{E}[x-\mu]^r = \frac{1}{n} \sum_{i=0}^{n-1} (x_i - \mu)^r
\f]
where \f$\mu\f$ is the sample mean.
*/
ITPP_EXPORT double moment(const vec &x, const int r);
/*!
\brief Calculate the skewness excess of the input vector x
The skewness is a measure of the degree of asymmetry of distribution. Negative
skewness means that the distribution is spread more to the left of the mean than to
the right, and vice versa if the skewness is positive.
The skewness of the samples in the vector \f$ \mathbf{x} \f$ is
\f[
\gamma_1 = \frac{\mathrm{E}[x-\mu]^3}{\sigma^3}
\f]
where \f$\mu\f$ is the mean and \f$\sigma\f$ the standard deviation.
The skewness is estimated as
\f[
\gamma_1 = \frac{k_3}{{k_2}^{3/2}}
\f]
where
\f[
k_2 = \frac{n}{n-1} m_2
\f]
and
\f[
k_3 = \frac{n^2}{(n-1)(n-2)} m_3
\f]
Here \f$m_2\f$ is the sample variance and \f$m_3\f$ is the 3rd sample
central moment.
*/
ITPP_EXPORT double skewness(const vec &x);
/*!
\brief Calculate the kurtosis excess of the input vector x
The kurtosis excess is a measure of peakedness of a distribution.
The kurtosis excess is defined as
\f[
\gamma_2 = \frac{\mathrm{E}[x-\mu]^4}{\sigma^4} - 3
\f]
where \f$\mu\f$ is the mean and \f$\sigma\f$ the standard deviation.
The kurtosis excess is estimated as
\f[
\gamma_2 = \frac{k_4}{{k_2}^2}
\f]
where
\f[
k_2 = \frac{n}{n-1} m_2
\f]
and
\f[
k_4 = \frac{n^2 [(n+1)m_4 - 3(n-1){m_2}^2]}{(n-1)(n-2)(n-3)}
\f]
Here \f$m_2\f$ is the sample variance and \f$m_4\f$ is the 4th sample
central moment.
*/
ITPP_EXPORT double kurtosisexcess(const vec &x);
/*!
\brief Calculate the kurtosis of the input vector x
The kurtosis is a measure of peakedness of a distribution. The kurtosis
is defined as
\f[
\gamma_2 = \frac{\mathrm{E}[x-\mu]^4}{\sigma^4}
\f]
where \f$\mu\f$ is the mean and \f$\sigma\f$ the standard deviation.
For a Gaussian variable, the kurtusis is 3.
See also the definition of kurtosisexcess.
*/
inline double kurtosis(const vec &x) {return kurtosisexcess(x) + 3;}
//!@}
} // namespace itpp
#endif // #ifndef MISC_STAT_H
|
zhangchangchun3009/java-web-spring4-cxf-mybatis
|
scm.common/src/main/java/pers/zcc/scm/common/excel/vo/ExcelImportVO.java
|
<reponame>zhangchangchun3009/java-web-spring4-cxf-mybatis
package pers.zcc.scm.common.excel.vo;
import java.util.ArrayList;
import java.util.List;
import pers.zcc.scm.common.user.vo.UserVO;
/**
* The Class ExcelImportVO.
*
* @author zhangchangchun
* @since 2022年1月4日
*/
public class ExcelImportVO {
/**
* 文件名
*/
private String fileName;
/**
* 用户信息
*/
private UserVO user;
/**
* 表单配置
*/
private ArrayList<ExcelSheetMapVO<?>> importSheetMapList;
/**
* 传递自定义上下文,可用在数据消费类获取
*/
private List<Object> definedContext;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public UserVO getUser() {
return user;
}
public void setUser(UserVO user) {
this.user = user;
}
public ArrayList<ExcelSheetMapVO<?>> getImportSheetMapList() {
return importSheetMapList;
}
public void setImportSheetMapList(ArrayList<ExcelSheetMapVO<?>> importSheetMapList) {
this.importSheetMapList = importSheetMapList;
}
public List<Object> getDefinedContext() {
return definedContext;
}
public void setDefinedContext(List<Object> definedContext) {
this.definedContext = definedContext;
}
}
|
000ssg/xLib
|
xLibWAMP/src/main/java/ssg/lib/wamp/WAMPFeature.java
|
<gh_stars>0
/*
* The MIT License
*
* Copyright 2020 <NAME>/<EMAIL>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package ssg.lib.wamp;
import ssg.lib.wamp.util.WAMPException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import static ssg.lib.wamp.WAMP.Role.broker;
import static ssg.lib.wamp.WAMP.Role.callee;
import static ssg.lib.wamp.WAMP.Role.caller;
import static ssg.lib.wamp.WAMP.Role.dealer;
import static ssg.lib.wamp.WAMP.Role.publisher;
import static ssg.lib.wamp.WAMP.Role.subscriber;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_call_canceling;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_call_reroute;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_call_timeout;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_call_trustlevels;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_caller_identification;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_event_history;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_pattern_based_registration;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_pattern_based_subscription;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_procedure_reflection;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_progressive_call_results;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_progressive_calls;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_publication_trustlevels;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_publisher_exclusion;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_publisher_identification;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_registration_meta_api;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_registration_revocation;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_sharded_registration;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_sharded_subscription;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_shared_registration;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_subscriber_blackwhite_listing;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_subscription_meta_api;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_topic_reflection;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_batched_ws_transport;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_challenge_response_authentication;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_cookie_authentication;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_longpoll_transport;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_rawsocket_transport;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_session_meta_api;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_testament_meta_api;
import static ssg.lib.wamp.WAMPConstantsAdvanced.FEATURE_x_ticket_authentication;
import ssg.lib.wamp.messages.WAMP_DT;
import ssg.lib.wamp.util.WAMPTools;
/**
*
* @author 000ssg
*/
public class WAMPFeature implements Serializable {
static final Map<String, WAMPFeature> features = WAMPTools.createMap();
// RPC Features
public static final WAMPFeature progressive_call_results = new WAMPFeature(
FEATURE_progressive_call_results,
caller,
dealer,
callee);
public static final WAMPFeature progressive_calls = new WAMPFeature(
FEATURE_progressive_calls,
caller,
dealer,
callee);
public static final WAMPFeature call_timeout = new WAMPFeature(
FEATURE_call_timeout,
caller,
dealer,
callee);
public static final WAMPFeature call_canceling = new WAMPFeature(
FEATURE_call_canceling,
caller,
dealer,
callee);
public static final WAMPFeature caller_identification = new WAMPFeature(
FEATURE_caller_identification,
caller,
dealer,
callee);
public static final WAMPFeature call_trustlevels = new WAMPFeature(
FEATURE_call_trustlevels,
dealer,
callee);
public static final WAMPFeature registration_meta_api = new WAMPFeature(
FEATURE_registration_meta_api,
dealer);
public static final WAMPFeature pattern_based_registration = new WAMPFeature(
FEATURE_pattern_based_registration,
dealer,
callee);
public static final WAMPFeature shared_registration = new WAMPFeature(
FEATURE_shared_registration,
dealer,
callee);
public static final WAMPFeature sharded_registration = new WAMPFeature(
FEATURE_sharded_registration,
dealer,
callee);
public static final WAMPFeature registration_revocation = new WAMPFeature(
FEATURE_registration_revocation,
dealer,
callee);
public static final WAMPFeature procedure_reflection = new WAMPFeature(
FEATURE_procedure_reflection,
dealer);
public static final WAMPFeature call_reroute = new WAMPFeature(
FEATURE_call_reroute,
dealer,
callee);
// PubSub Features
public static final WAMPFeature subscriber_blackwhite_listing = new WAMPFeature(
FEATURE_subscriber_blackwhite_listing,
publisher,
broker);
public static final WAMPFeature publisher_exclusion = new WAMPFeature(
FEATURE_publisher_exclusion,
publisher,
broker);
public static final WAMPFeature publisher_identification = new WAMPFeature(
FEATURE_publisher_identification,
publisher,
broker,
subscriber);
public static final WAMPFeature publication_trustlevels = new WAMPFeature(
FEATURE_publication_trustlevels,
broker,
subscriber);
public static final WAMPFeature subscription_meta_api = new WAMPFeature(
FEATURE_subscription_meta_api,
broker);
public static final WAMPFeature pattern_based_subscription = new WAMPFeature(
FEATURE_pattern_based_subscription,
broker,
subscriber);
public static final WAMPFeature sharded_subscription = new WAMPFeature(
FEATURE_sharded_subscription,
broker,
subscriber);
public static final WAMPFeature event_history = new WAMPFeature(
FEATURE_event_history,
broker,
subscriber);
public static final WAMPFeature topic_reflection = new WAMPFeature(
FEATURE_topic_reflection,
broker);
// Other Advanced Features
public static final WAMPFeature x_challenge_response_authentication = new WAMPFeature(
FEATURE_x_challenge_response_authentication);
public static final WAMPFeature x_cookie_authentication = new WAMPFeature(
FEATURE_x_cookie_authentication);
public static final WAMPFeature x_ticket_authentication = new WAMPFeature(
FEATURE_x_ticket_authentication);
public static final WAMPFeature x_rawsocket_transport = new WAMPFeature(
FEATURE_x_rawsocket_transport);
public static final WAMPFeature x_batched_ws_transport = new WAMPFeature(
FEATURE_x_batched_ws_transport);
public static final WAMPFeature x_longpoll_transport = new WAMPFeature(
FEATURE_x_longpoll_transport);
public static final WAMPFeature x_session_meta_api = new WAMPFeature(
FEATURE_x_session_meta_api,
dealer,
broker,
subscriber,
caller);
public static final WAMPFeature x_testament_meta_api = new WAMPFeature(
FEATURE_x_testament_meta_api,
dealer,
broker,
//publisher,
caller);
public static WAMPFeature find(String name) {
return features.get(name);
}
/**
* Merges src and features sets. If no changes original src is returned.
*
* @param src
* @param features
* @return
*/
public static WAMPFeature[] merge(WAMPFeature[] src, WAMPFeature... features) {
WAMPFeature[] r = src;
if (features != null) {
for (WAMPFeature f : features) {
if (f == null) {
continue;
}
if (r == null) {
r = new WAMPFeature[]{f};
} else {
boolean found = false;
for (WAMPFeature ff : r) {
if (ff == f) {
found = true;
break;
}
}
if (!found) {
r = Arrays.copyOf(r, r.length + 1);
r[r.length - 1] = f;
}
}
}
}
return r;
}
/**
* Returns copy of merged src and features.
*
* @param src
* @param features
* @return
*/
public static WAMPFeature[] mergeCopy(WAMPFeature[] src, WAMPFeature... features) {
return merge(merge(null, src), features);
}
public static WAMPFeature[] remove(WAMPFeature[] src, WAMPFeature... features) {
if (src == null || src.length == 0 || features == null || features.length == 0) {
return src;
}
WAMPFeature[] r = new WAMPFeature[src.length];
int off = 0;
for (int i = 0; i < r.length; i++) {
boolean found = false;
for (WAMPFeature f : features) {
if (f != null && f.equals(src[i])) {
found = true;
break;
}
}
if (!found) {
r[off++] = src[i];
}
}
if (off < r.length) {
r = Arrays.copyOf(r, off);
}
return r;
}
/**
* Ensures only features present both in a and fs are returned.
*
* @param a
* @param fs
* @return
*/
public static WAMPFeature[] intersection(WAMPFeature[] a, Collection<WAMPFeature> fs) {
return intersection(a, (fs != null) ? fs.toArray(new WAMPFeature[fs.size()]) : null);
}
/**
* Ensures only features present both in a and fs are returned.
*
* @param a
* @param fs
* @return
*/
public static WAMPFeature[] intersection(WAMPFeature[] a, WAMPFeature... fs) {
WAMPFeature[] r = new WAMPFeature[(fs != null) ? fs.length : 0];
int off = 0;
if (fs != null && a != null && a.length > 0) {
for (WAMPFeature f : fs) {
if (f == null) {
continue;
}
if (off > 0) {
boolean duplicate = false;
for (int i = 0; i < off; i++) {
if (r[i].equals(f)) {
duplicate = true;
break;
}
}
if (duplicate) {
continue;
}
}
boolean ok = false;
for (WAMPFeature fa : a) {
if (fa == null) {
continue;
}
if (fa.equals(f)) {
ok = true;
break;
}
}
if (ok) {
r[off++] = f;
}
}
}
if (off < r.length) {
r = Arrays.copyOf(r, off);
}
return r;
}
// instance
String uri;
WAMP.Role[] scope;
public WAMPFeature(String name) {
uri = name;
features.put(uri, this);
}
public WAMPFeature(String uri, WAMP.Role... scope) {
try {
this.uri = uri;
if (!WAMP_DT.uri.validate(uri)) {
throw new WAMPException("Invalid feature URI: " + uri);
}
features.put(uri, this);
} catch (WAMPException wex) {
wex.printStackTrace();
}
this.scope = scope;
}
public String uri() {
return uri;
}
public WAMP.Role[] scope() {
return scope;
}
@Override
public String toString() {
return ((getClass().isAnonymousClass()) ? getClass().getName() : getClass().getSimpleName())
+ "{" + "uri=" + uri + ", scope=" + Arrays.asList(scope) + '}';
}
}
|
aroychoudhury/innovista
|
sharing-services/src/main/java/org/verizon/sharingservices/dataobject/ShareResponse.java
|
<reponame>aroychoudhury/innovista<gh_stars>0
package org.verizon.sharingservices.dataobject;
import java.util.List;
import org.verizon.sharingservices.domain.User;
import org.verizon.sharingservices.domain.Workgroup;
/**
* Response Data transfer object
* @author Bhuvitha
*
*/
public class ShareResponse {
private String responseType = "";
private String responseText = "";
public String getResponseType() {
return responseType;
}
public void setResponseType(String responseType) {
this.responseType = responseType;
}
public String getResponseText() {
return responseText;
}
public void setResponseText(String responseText) {
this.responseText = responseText;
}
}
|
gaybro8777/osf.io
|
api/subjects/urls.py
|
<gh_stars>100-1000
from django.conf.urls import url
from api.subjects import views
app_name = 'osf'
urlpatterns = [
url(r'^(?P<subject_id>\w+)/$', views.SubjectDetail.as_view(), name=views.SubjectDetail.view_name),
url(r'^(?P<subject_id>\w+)/children/$', views.SubjectChildrenList.as_view(), name=views.SubjectChildrenList.view_name),
]
|
HuttonICS/diversify-server
|
src/jhi/diversify/server/database/tables/pojos/ViewSpeciesdata.java
|
<filename>src/jhi/diversify/server/database/tables/pojos/ViewSpeciesdata.java<gh_stars>0
/*
* This file is generated by jOOQ.
*/
package jhi.diversify.server.database.tables.pojos;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* VIEW
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.11.9"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ViewSpeciesdata implements Serializable {
private static final long serialVersionUID = -945464937;
private Integer traitid;
private String traitname;
private String traitcode;
private Integer siteid;
private String sitename;
private String partnername;
private Integer rate;
private String cropname;
private Integer varietyid;
private String varietyname;
private String value;
public ViewSpeciesdata() {}
public ViewSpeciesdata(ViewSpeciesdata value) {
this.traitid = value.traitid;
this.traitname = value.traitname;
this.traitcode = value.traitcode;
this.siteid = value.siteid;
this.sitename = value.sitename;
this.partnername = value.partnername;
this.rate = value.rate;
this.cropname = value.cropname;
this.varietyid = value.varietyid;
this.varietyname = value.varietyname;
this.value = value.value;
}
public ViewSpeciesdata(
Integer traitid,
String traitname,
String traitcode,
Integer siteid,
String sitename,
String partnername,
Integer rate,
String cropname,
Integer varietyid,
String varietyname,
String value
) {
this.traitid = traitid;
this.traitname = traitname;
this.traitcode = traitcode;
this.siteid = siteid;
this.sitename = sitename;
this.partnername = partnername;
this.rate = rate;
this.cropname = cropname;
this.varietyid = varietyid;
this.varietyname = varietyname;
this.value = value;
}
public Integer getTraitid() {
return this.traitid;
}
public void setTraitid(Integer traitid) {
this.traitid = traitid;
}
public String getTraitname() {
return this.traitname;
}
public void setTraitname(String traitname) {
this.traitname = traitname;
}
public String getTraitcode() {
return this.traitcode;
}
public void setTraitcode(String traitcode) {
this.traitcode = traitcode;
}
public Integer getSiteid() {
return this.siteid;
}
public void setSiteid(Integer siteid) {
this.siteid = siteid;
}
public String getSitename() {
return this.sitename;
}
public void setSitename(String sitename) {
this.sitename = sitename;
}
public String getPartnername() {
return this.partnername;
}
public void setPartnername(String partnername) {
this.partnername = partnername;
}
public Integer getRate() {
return this.rate;
}
public void setRate(Integer rate) {
this.rate = rate;
}
public String getCropname() {
return this.cropname;
}
public void setCropname(String cropname) {
this.cropname = cropname;
}
public Integer getVarietyid() {
return this.varietyid;
}
public void setVarietyid(Integer varietyid) {
this.varietyid = varietyid;
}
public String getVarietyname() {
return this.varietyname;
}
public void setVarietyname(String varietyname) {
this.varietyname = varietyname;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ViewSpeciesdata (");
sb.append(traitid);
sb.append(", ").append(traitname);
sb.append(", ").append(traitcode);
sb.append(", ").append(siteid);
sb.append(", ").append(sitename);
sb.append(", ").append(partnername);
sb.append(", ").append(rate);
sb.append(", ").append(cropname);
sb.append(", ").append(varietyid);
sb.append(", ").append(varietyname);
sb.append(", ").append(value);
sb.append(")");
return sb.toString();
}
}
|
automatictester/useful-stuff
|
java/design-patterns/src/test/java/uk/co/automatictester/creational/factorymethod/test/CloudClientFactoryTest.java
|
package uk.co.automatictester.creational.factorymethod.test;
import org.testng.annotations.Test;
import uk.co.automatictester.creational.factorymethod.CloudClient;
import uk.co.automatictester.creational.factorymethod.CloudClientFactory;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static uk.co.automatictester.creational.factorymethod.ClientType.MOCKED;
import static uk.co.automatictester.creational.factorymethod.ClientType.REAL;
public class CloudClientFactoryTest {
@Test
public void testFactoryMethod() {
CloudClient mockedClient = CloudClientFactory.getInstance(MOCKED);
CloudClient anotherMockedClient = CloudClientFactory.getInstance(MOCKED);
CloudClient realClient = CloudClientFactory.getInstance(REAL);
assertEquals(mockedClient, anotherMockedClient);
assertNotEquals(mockedClient, realClient);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.