repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
ltcmelo/psychec | C/symbols/TypeSymbol_Array.cpp | 1497 | // Copyright (c) 2021 Leandro T. C. Melo <ltcmelo@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "TypeSymbol_Array.h"
using namespace psy;
using namespace C;
ArrayTypeSymbol::ArrayTypeSymbol(const SyntaxTree* tree,
const Scope* scope,
const Symbol* containingSym)
: TypeSymbol(tree,
scope,
containingSym,
TypeKind::Array)
{}
| bsd-3-clause |
LukasBanana/ForkENGINE | sources/Engine/Component/Property/FloatProperty.cpp | 864 | /*
* Floating-point property file
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "Engine/Component/Component.h"
#include "IO/FileSystem/File.h"
namespace Fork
{
namespace Engine
{
Component::Property::Types Component::FloatProperty::Type() const
{
return Types::Float;
}
void Component::FloatProperty::WriteToFile(IO::File& file) const
{
file.Write<float>(value);
}
void Component::FloatProperty::ReadFromFile(IO::File& file)
{
value = file.Read<float>();
}
void Component::FloatProperty::WriteToVariant(IO::Variant& variant) const
{
variant = value;
}
void Component::FloatProperty::ReadFromVariant(const IO::Variant& variant)
{
value = variant.GetFloat();
}
} // /namespace Engine
} // /namespace Fork
// ======================== | bsd-3-clause |
wayfinder/Wayfinder-Server | Server/Shared/Items/src/StreetSegmentItem.cpp | 4502 | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd 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 THE COPYRIGHT HOLDER 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.
*/
#include "config.h"
#include "Node.h"
#include "StreetSegmentItem.h"
#include "MC2String.h"
#include "DataBuffer.h"
const byte StreetSegmentItem::WIDTH_MASK = 0x0f;
const byte StreetSegmentItem::ROUNDABOUTISH_MASK = 0x10;
const byte StreetSegmentItem::STREETNUMBERTYPE_MASK = 0x07;
const byte StreetSegmentItem::ROUNDABOUT_MASK = 0x08;
const byte StreetSegmentItem::RAMP_MASK = 0x10;
const byte StreetSegmentItem::DIVIDED_MASK = 0x20;
const byte StreetSegmentItem::MULTI_DIGITISED_MASK = 0x40;
const byte StreetSegmentItem::CONTROLLED_ACCESS_MASK = 0x80;
uint32
StreetSegmentItem::getMemoryUsage() const
{
uint32 totalSize = RouteableItem::getMemoryUsage()
- sizeof(RouteableItem) + sizeof(StreetSegmentItem);
return totalSize;
}
void
StreetSegmentItem::save( DataBuffer& dataBuffer, const GenericMap& map ) const
{
DEBUG_DB(mc2dbg << " StreetSegmentItem::save()" << endl;)
RouteableItem::save( dataBuffer, map );
DEBUG_DB(mc2dbg << " Saving attributes for this item" << endl;)
dataBuffer.writeNextByte( m_condition );
dataBuffer.writeNextByte( m_roadClass );
byte tmpData = m_width & WIDTH_MASK;
if (m_roundaboutish)
tmpData |= ROUNDABOUTISH_MASK;
dataBuffer.writeNextByte( tmpData );
// Store the three flaggs in the streetNumberType-byte on disc
tmpData = byte(m_streetNumberType) & STREETNUMBERTYPE_MASK;
if (m_roundabout)
tmpData |= ROUNDABOUT_MASK;
if (m_ramp)
tmpData |= RAMP_MASK;
if (m_divided)
tmpData |= DIVIDED_MASK;
if (m_multiDigitised)
tmpData |= MULTI_DIGITISED_MASK;
if (m_controlledAccess)
tmpData |= CONTROLLED_ACCESS_MASK;
dataBuffer.writeNextByte(tmpData);
}
void
StreetSegmentItem::load( DataBuffer& dataBuffer, GenericMap& theMap )
{
m_type = ItemTypes::streetSegmentItem;
RouteableItem::load( dataBuffer, theMap );
m_condition = dataBuffer.readNextByte();
m_roadClass = dataBuffer.readNextByte();
byte tmpData = dataBuffer.readNextByte();
m_width = tmpData & WIDTH_MASK;
m_roundaboutish = ( (tmpData & ROUNDABOUTISH_MASK) != 0);
tmpData = dataBuffer.readNextByte();
m_streetNumberType =
ItemTypes::streetNumberType(tmpData & STREETNUMBERTYPE_MASK);
m_roundabout = ( (tmpData & ROUNDABOUT_MASK) != 0);
m_ramp = ( (tmpData & RAMP_MASK) != 0);
m_divided = ( (tmpData & DIVIDED_MASK) != 0);
m_multiDigitised = ( (tmpData & MULTI_DIGITISED_MASK) != 0);
m_controlledAccess = ( (tmpData & CONTROLLED_ACCESS_MASK) != 0);
// The display class is not saved together with the item in the
// current m3-format, instead it is stored in a separate table.
m_displayClass = ItemTypes::nbrRoadDisplayClasses;
}
void
StreetSegmentItem::setStreetNumberType(ItemTypes::streetNumberType x)
{
m_streetNumberType = x;
}
void
StreetSegmentItem::setDisplayClass(
ItemTypes::roadDisplayClass_t displayClass ) {
m_displayClass = displayClass;
}
| bsd-3-clause |
shehzan10/arrayfire | src/backend/opencl/kernel/diagonal.hpp | 4348 | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <kernel_headers/diag_create.hpp>
#include <kernel_headers/diag_extract.hpp>
#include <program.hpp>
#include "../traits.hpp"
#include <dispatch.hpp>
#include <Param.hpp>
#include <debug_opencl.hpp>
#include <map>
#include <mutex>
#include <math.hpp>
#include "config.hpp"
using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::KernelFunctor;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;
using af::scalar_to_option;
namespace opencl
{
namespace kernel
{
template<typename T>
static void diagCreate(Param out, Param in, int num)
{
static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
static std::map<int, Program*> diagCreateProgs;
static std::map<int, Kernel*> diagCreateKernels;
int device = getActiveDeviceId();
std::call_once( compileFlags[device], [device] () {
std::ostringstream options;
options << " -D T=" << dtype_traits<T>::getName()
<< " -D ZERO=(T)(" << scalar_to_option(scalar<T>(0)) << ")";
if (std::is_same<T, double>::value ||
std::is_same<T, cdouble>::value) {
options << " -D USE_DOUBLE";
}
Program prog;
buildProgram(prog, diag_create_cl, diag_create_cl_len, options.str());
diagCreateProgs[device] = new Program(prog);
diagCreateKernels[device] = new Kernel(*diagCreateProgs[device],
"diagCreateKernel");
});
NDRange local(32, 8);
int groups_x = divup(out.info.dims[0], local[0]);
int groups_y = divup(out.info.dims[1], local[1]);
NDRange global(groups_x * local[0] * out.info.dims[2],
groups_y * local[1]);
auto diagCreateOp = KernelFunctor<Buffer, const KParam,
Buffer, const KParam,
int, int> (*diagCreateKernels[device]);
diagCreateOp(EnqueueArgs(getQueue(), global, local),
*(out.data), out.info, *(in.data), in.info, num, groups_x);
CL_DEBUG_FINISH(getQueue());
}
template<typename T>
static void diagExtract(Param out, Param in, int num)
{
static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
static std::map<int, Program*> diagExtractProgs;
static std::map<int, Kernel*> diagExtractKernels;
int device = getActiveDeviceId();
std::call_once( compileFlags[device], [device] () {
std::ostringstream options;
options << " -D T=" << dtype_traits<T>::getName()
<< " -D ZERO=(T)(" << scalar_to_option(scalar<T>(0)) << ")";
if (std::is_same<T, double>::value ||
std::is_same<T, cdouble>::value) {
options << " -D USE_DOUBLE";
}
Program prog;
buildProgram(prog, diag_extract_cl, diag_extract_cl_len, options.str());
diagExtractProgs[device] = new Program(prog);
diagExtractKernels[device] = new Kernel(*diagExtractProgs[device],
"diagExtractKernel");
});
NDRange local(256, 1);
int groups_x = divup(out.info.dims[0], local[0]);
int groups_z = out.info.dims[2];
NDRange global(groups_x * local[0],
groups_z * local[1] * out.info.dims[3]);
auto diagExtractOp = KernelFunctor<Buffer, const KParam,
Buffer, const KParam,
int, int> (*diagExtractKernels[device]);
diagExtractOp(EnqueueArgs(getQueue(), global, local),
*(out.data), out.info, *(in.data), in.info, num, groups_z);
CL_DEBUG_FINISH(getQueue());
}
}
}
| bsd-3-clause |
tartley/flyinghigh-opengl-from-python | flyinghigh/component/wobblyorbit.py | 1716 | from __future__ import division
from math import cos, sin, pi
from random import uniform
from ..geometry.vec3 import Vec3
class Orbit(object):
def __init__(self, distance, speed, phase=None):
self.distance = distance
self.speed = speed
if phase is None:
phase = uniform(0, 2 * pi)
self.phase = phase
def __call__(self, time, dt):
time = time.current
bearing = time * self.speed + self.phase
x = self.distance * sin(bearing)
z = self.distance * cos(bearing)
return Vec3(x, 0, z)
class WobblyOrbit(object):
def __init__(self, mean, variance=0.0, speed=1.0):
self.mean = mean
self.variance = variance
self.speed = speed
self.phase = uniform(0, 2 * pi)
self.desired_mean = mean
self.desired_variance = variance
def __call__(self, time, dt):
time = time.current
# move smoothly between transitions
self.mean += (self.desired_mean - self.mean) * dt * 10
self.variance = min (
self.mean - 2,
self.variance + (self.desired_variance - self.variance) * dt * 10
)
# camera position at distance, bearing
distance = self.mean + sin(time * self.speed) * self.variance
bearing = sin(time * self.speed / 4 + self.phase + 3 * pi / 4) * 10
x1 = distance * sin(bearing)
z1 = distance * cos(bearing)
# then elevate above/below the y=0 plane
elevation = sin(time * self.speed + self.phase) * cos(time / 3) * pi / 2
x2 = x1 * cos(elevation)
z2 = z1 * cos(elevation)
y2 = distance * sin(elevation)
return Vec3(x2, y2, z2)
| bsd-3-clause |
dfabregat/Cl1ck | SRC/Operation.py | 42963 | import sys
import os
import copy
import itertools
from core.expression import Symbol, Matrix, Vector, Scalar, NumericConstant, \
Equal, Plus, Minus, Times, Transpose, \
BlockedExpression, NList, Predicate, \
PatternDot, PatternStar, sZERO
from core.builtin_operands import Zero
from core.properties import *
from core.InferenceOfProperties import *
from core.prop_to_queryfunc import symbol_props_to_constraints, prop_to_func, symbol_props_to_constraints_no_io
from core.functional import replace, replace_all, RewriteRule, Replacement, Constraint, \
map_thread, contains, match, matchq
from core.rules_collection import simplify_rules, canonicalIO_rules
from core.rules_collection_base import canonical_rules
from core.algebraic_manipulation import to_canonical, to_canonicalIO, simplify
import core.TOS as TOS
# DEBUGGING
from core.TOS import _TOS
from CoreExtension import WrapOutBef, WrapOutAft, isOperand, infer_properties
import PredicateMetadata as pm
import Config
from PME import PME
from LoopInvariant import LoopInvariant, initial_rewrite, final_rewrite
from Algorithm import Algorithm
from BindDimensions import bindDimensions
from graph import build_dep_graph, subgraphs, zero_out_lower
from Partitioning import partition_shape, repartition, repartition_shape, repart_group
from Tiling import tile_expr
from utils import sort
from RewritingExtension import *
from BackEnd.MatlabCode import generate_matlab_code, click2matlab
#from BackEnd.LatexCode import generate_latex_code
#from BackEnd.LGenCode import generate_lgen_files
#from BackEnd.CCode import generate_c_code
known_ops = [
# Straight assignment
RewriteRule(
(
NList([ Equal([ PatternDot("LHS"), PatternDot("RHS") ]) ]),
Constraint( "isinstance(LHS, Symbol) and isOutput(LHS) and isInput(RHS)" )
),
Replacement( "Equal([ NList([LHS]), RHS ])" )
)
]
known_ops_single = []
known_pmes = []
op_to_implicit = []
# Add a verbose option
# For now it would help to illustrate the process
class Operation( object ):
def __init__( self, name, operands, equation, overwrite ):
self.name = name
self.operands = operands
self.equation = equation # list because it may be a coupled equation
self.overwrite = overwrite
def run( self ):
print("**********************************")
print("* Generating code for %s " % self.name)
for eq in self.equation:
print("* - %s " % str(eq))
print("**********************************")
self.initial_setup()
self.generate_PMEs()
self.generate_loop_invariants()
self.generate_loop_based_algorithms()
self.generate_code()
print("**********************************")
#
# Initialization step:
#
def initial_setup( self ):
self.to_canonical_IO()
self.learn_pattern()
def to_canonical_IO( self ):
self.equation = [
replace_all( eq, canonical_rules + canonicalIO_rules + simplify_rules ) \
for eq in self.equation
]
# Minimize number of nodes among:
# 1) as is,
# 2) applying minus to both sides, and
# 3) applying transpose to both sides
minimal = []
for eq in self.equation:
alternative_forms= [ eq,
simplify( to_canonical( Equal([ Minus([ eq.lhs() ]), Minus([ eq.rhs()]) ]) ) ),
simplify( to_canonical( Equal([ Transpose([ eq.lhs() ]), Transpose([ eq.rhs()]) ]) ) )
]
_, new = min( [ (alt.num_nodes(), alt) for alt in alternative_forms ] )
minimal.append(new)
# Set minimal forms
self.equation = NList( minimal )
#
nodes = list( itertools.chain( *[[ node for node in eq.iterate_preorder() ] for eq in self.equation ] ) )
self.operands = [ op for op in self.operands if op in nodes ]
def learn_pattern( self ):
inops = [ op for op in self.operands if op.isInput() ]
outops = [ op for op in self.operands if op.isOutput() ]
#
single_assignment = len( self.equation.children ) == 1 and \
isinstance(self.equation.children[0].children[0], Symbol) # eq.lhs.single_entry_in_NL
#
op_to_pattern = [ RewriteRule( op, Replacement("PatternDot(%s.name)" % op.name) ) for op in self.operands ]
pattern = NList([ replace_all( copy.deepcopy(eq), op_to_pattern ) for eq in self.equation ])
if single_assignment:
props_str = [symbol_props_to_constraints_no_io(op) for op in self.operands]
constraint = Constraint(" and ".join( [prop for prop in props_str if prop] ))
else:
constraint = Constraint(" and ".join( [symbol_props_to_constraints(op) for op in self.operands] ))
# [TODO] Tuple for get_size
replacement = Replacement("Equal([ NList([%s]), Predicate( \"%s\", [%s], [%s] ) ])" % (
", ".join( [op.name for op in outops] ),
self.name,
", ".join( [op.name for op in inops] ),
", ".join( ["%s.get_size()" % op.get_name() for op in outops]))
)
# [TODO] This should be part of the verbose option
if Config.options.verbose:
print( "* Learnt pattern" )
print( "* ", pattern, end="" )
if constraint.to_eval:
print( " with ", constraint.to_eval )
print(" --> ")
print( "* ", replacement.to_eval )
print("**********************************")
# [TODO] Maybe sort known ops by specificity (a la mathematica)
#known_ops.insert( 0, RewriteRule( (pattern, constraint), replacement ) )
if single_assignment:
expr = pattern.children[0]
expr.children[0] = NList([ expr.children[0] ])
known_ops_single.insert( 0, RewriteRule( (expr, constraint), replacement ) )
# With minus
replacement = Replacement("Equal([ NList([%s]), Minus([ Predicate( \"%s\", [%s], [%s] ) ]) ])" % (
", ".join( [op.name for op in outops] ),
self.name,
", ".join( [op.name for op in inops] ),
", ".join( ["%s.get_size()" % op.get_name() for op in outops]))
)
expr = copy.deepcopy( expr )
expr.children[1] = Minus([ expr.children[1] ])
expr.children[1] = normalize_minus( copy.deepcopy(expr.children[1]) )
known_ops_single.insert( 0, RewriteRule( (expr, constraint), replacement ) )
else:
known_ops.insert( 0, RewriteRule( (pattern, constraint), replacement ) )
pattern = Equal([ NList([ PatternDot(op.get_name()) for op in outops ]),
Predicate( self.name, [PatternDot(op.get_name()) for op in inops], [op.get_size() for op in outops] ) ])
replacement = Replacement( equation2replacement( self.equation ) )
op_to_implicit.append( RewriteRule( pattern, replacement ) )
def generate_PMEs( self ):
print("* Generating PMEs...")
self.bind_dimensions()
self.predicate_metadata()
#
self.pmes = []
for part_tuple in itertools.product([1,2], repeat=len(self.bound_dimensions)-1):
if Config.options.verbose:
print("* ")
# If multidimensional partitioning and --lgen: skip
#multidim_part = len( [ psize for psize in part_tuple if psize != 1 ] ) > 1
#if multidim_part and Config.options.lgen:
#continue
# Build dict such as part_shape[op.get_name()] = (1,2), ...
part_tuple = [1] + list(part_tuple)
dims_to_part_shape = dict()
for dims, shape in zip( self.bound_dimensions, part_tuple ):
for dim in dims:
dims_to_part_shape[dim] = shape
part_shape = dict()
for operand in self.operands:
op_name = operand.get_name()
part_shape[ op_name ] = \
(
dims_to_part_shape[op_name + "_r"],
dims_to_part_shape[op_name + "_c"]
)
# Initialize PME and generate
pme = PME( self.name, self.operands, self.equation, known_ops, known_pmes, part_tuple, part_shape )
# [TODO] UGLY AS HELL!!!
pme.operation = self
#
pme.partition()
pme.distribute_partitioned_postcondition()
pme.solve_equations()
pme.learn_pattern()
pme.solve_base_case()
self.pmes.append( pme )
#
for pme in self.pmes:
pme.sort()
if Config.options.verbose:
print("**********************************")
def bind_dimensions( self ):
self.bound_dimensions = bindDimensions( self.equation, self.operands )
def predicate_metadata( self ):
inops = [ op for op in self.operands if op.isInput() ]
outops = [ op for op in self.operands if op.isOutput() ]
output_size = []
for op in outops:
row_str = op.get_name() + "_r"
row_set = [ s for s in self.bound_dimensions if row_str in s ][0]
col_str = op.get_name() + "_c"
col_set = [ s for s in self.bound_dimensions if col_str in s ][0]
for dim in row_set:
op_name, dim_label = dim.split("_")
try:
idx = [ op.get_name() for op in inops ].index( op_name )
except ValueError:
continue
row_size = (idx, inops[idx], dim_label)
for dim in col_set:
op_name, dim_label = dim.split("_")
try:
idx = [ op.get_name() for op in inops ].index( op_name )
except ValueError:
continue
col_size = (idx, inops[idx], dim_label)
output_size.append( (row_size, col_size) )
pm.DB[self.name] = pm.PredicateMetadata( self.name, output_size )
pm.DB[self.name].overwrite = [ (inops.index(inp), outops.index(out)) for inp, out in self.overwrite ]
def generate_loop_invariants( self ):
print("* Generating Loop invariants...")
self.linvs = []
self.travs = [] # traversal of the operands
for pme in self.pmes:
if Config.options.verbose:
print("* ")
loop_invariants = [] # This PME's loop invariants
travs = [] # Traversals for this PME's loop invariants
for tiling in self.tile_pme( pme ):
tiling = self.pme_tiling_eliminate_temporaries( tiling )
linear_tiling = list(itertools.chain( *tiling ))
##
if Config.options.verbose:
print( "* Tiling PME" )
for t in linear_tiling:
print("* ", t)
print("* ")
##
dep_graph = build_dep_graph( linear_tiling )
#for g in dep_graph:
#print(g)
zero_out_lower( dep_graph ) # since ops are sorted, there are no deps backwards
# occurs, e.g., in sylvester L,U 2x2 at the BR
# with 3 statements writing to BR
# Check feasibility of the subgraph
for subgraph in subgraphs( dep_graph ):
linv_candidate = LoopInvariant( self, op_to_implicit, known_pmes, pme, tiling, dep_graph, subgraph )
linv_candidate.build()
if linv_candidate.is_feasible() and \
not any( [linv_candidate.same_up_to_temporaries( linv ) \
for linv in loop_invariants] ):
loop_invariants.append( linv_candidate )
if Config.options.verbose:
print( "* Loop invariant %d" % len( loop_invariants ) )
for expr in itertools.chain( *linv_candidate.expressions ):
print("* ", expr )
print("* ")
#else:
#print(" Unfeasiable linv ")
#print( linv_candidate.expressions )
self.linvs.append( loop_invariants )
if Config.options.verbose:
print("**********************************")
def tile_pme( self, pme ):
#TOS.reset_temp() # Start again from T1
#
# Per equation, list of possible tilings,
# which will then be "cross-producted"
pme.tilings = []
tiles_per_eq = []
for _eq in pme.sorted:
tiles_per_eq.append( tile_expr( _eq ) )
for cross in itertools.product( *tiles_per_eq ):
pme.tilings.append( list(cross) )
return pme.tilings
def pme_tiling_eliminate_temporaries( self, tiling ):
# Tiling is a list of tilings, one per quadrant
# The traversal of the quadrants is based on data dependencies already :)
from Passes import dfg
from Passes import alg_passes
#
new_pme_tiling = []
for quad_tiling in tiling:
opt_quad_tiling = []
for st in quad_tiling:
opt_quad_tiling.extend( alg_passes._checkPredicateOverwrite( copy.deepcopy(st) ) )
pme_dfg = dfg.dfg_node( opt_quad_tiling, 0 )
#
prev_tiling = [copy.deepcopy(t) for t in opt_quad_tiling]
done = False
while not done:
old_sts = pme_dfg.statements
pme_dfg.statements = []
for st in old_sts:
pme_dfg.statements.extend( alg_passes._checkPredicateOverwrite(st) )
pme_dfg.opt_backward_copy_propagation()
pme_dfg.opt_copy_propagation()
pme_dfg.opt_remove_self_assignments()
pme_dfg.analysis_next_use()
pme_dfg.opt_dead_code_elimination()
cur_tiling = [copy.deepcopy(t) for t in pme_dfg.statements]
done = len( prev_tiling ) == len( cur_tiling ) and \
all([ t1 == t2 for t1, t2 in zip( prev_tiling, cur_tiling ) ])
if not done:
prev_tiling = []
for t in cur_tiling:
#prev_tiling.extend( pass_check_ow._checkPredicateOverwrite( t ) )
prev_tiling.extend( [t] )
#
new_pme_tiling.append( pme_dfg.statements )
return new_pme_tiling
def generate_loop_based_algorithms( self ):
print( "* Generating Loop-based algorithms..." )
self.algs = []
variant = 1
for pme, linvs in zip( self.pmes, self.linvs ):
algs = []
for linv in linvs:
if Config.options.verbose:
print("* ")
print( "* Loop invariant", variant )
for expr in linv.expressions:
print("* ", expr )
print("* ")
trav, init_state, _ = linv.traversals[0] # this would be another for loop
init = self.algorithm_initialization( init_state )
if Config.options.verbose:
print( "* Init" )
#print( init_state )
print( "* ", init )
s = PatternDot("s")
init = [ replace_all( i, [RewriteRule( WrapOutBef(s), Replacement(lambda d: d["s"]) )] ) for i in init ]
if Config.options.verbose:
print( "* Before" )
repart, before = self.generate_predicate_before( pme, trav, linv.expressions, linv )
if Config.options.verbose:
print( "* After" )
reversed_trav = dict( [(k, (r*-1, c*-1)) for k, (r,c) in trav.items() ] )
cont_with, after = self.generate_predicate_before( pme, reversed_trav, linv.expressions, linv )
# find updates
if Config.options.verbose:
print( "* Updates" )
updates = self.find_updates( before, after )
if updates is None:
#variant += 1
continue
# Tile updates
for u in updates:
infer_properties( u )
final_updates = []
# [DIEGO] Fixing some output pieces being labeled as input
outputs = []
for u in updates:
lhs, rhs = u.children
for l in lhs:
if not l.isTemporary():
outputs.append( l )
l.set_property( OUTPUT )
#
for u in updates:
#[DIEGO] u.children[0].children[0].set_property( OUTPUT )
for node in u.children[1].iterate_preorder():
#if isinstance(node, Symbol):
if isinstance(node, Symbol) and node not in outputs:
node.set_property( INPUT )
#
#copy_u = replace( copy.deepcopy(u), known_ops_single )
copy_u = copy.deepcopy(u)
copy_u = tile_expr(copy.deepcopy(copy_u))[0] # One tiling
final_updates.extend( copy_u )
if len(updates) == 0:
print("No updates!! Should only happen in copy")
continue
algs.append( Algorithm( linv, variant, init, repart, cont_with, before, after, final_updates) )
algs[-1].prepare_for_code_generation()
variant += 1
self.algs.append( algs )
def express_in_terms_of_input( self, assignments ):
expand_rules = list(itertools.chain(*self.expr_to_rule_lhs_rhs( assignments )))
new_ass = []
for expr in assignments:
new = copy.deepcopy(expr)
new.children[1] = simplify(to_canonical(replace_all(new.children[1], expand_rules)))
new_ass.append(new)
return new_ass
def find_updates( self, before, after ):
# If a part is (partially) computed in the before and
# does not appear in the after or
# going from before to after requires undoing some computation
# it is potentially unstable, and more expensive: ignore
before_finputs = self.express_in_terms_of_input( before )
after_finputs = self.express_in_terms_of_input( after )
dict_bef = dict([ (str(u.get_children()[0]), u) for u in before_finputs ])
dict_aft = dict([ (str(u.get_children()[0]), u) for u in after_finputs ])
same = []
ignore = False
for k,v in dict_bef.items():
if k in dict_aft and matchq(v, dict_aft[k]):
same.extend(v.children[0].children)
if k not in dict_aft:
ignore = True
reason = "%s not in %s" % (k, dict_aft.keys())
break
else:
rules = self.expr_to_rule_rhs_lhs( [v] )
rules = list(itertools.chain(*rules))
expr_copy = copy.deepcopy( dict_aft[k] )
t = replace( expr_copy, rules )
#if v == replace( expr_copy, rules ):
if dict_aft[k] == t:
ignore = True
reason = "%s would require undoing job" % k
break
if ignore:
if Config.options.verbose:
print( "[INFO] Skipping invariant: %s" % reason )
return None
#
# Wrap outputs for before and after
WrapBefOut = WrapOutBef
lhss = []
for u in before:
lhss.extend( u.children[0] )
u.children[0] = NList([WrapBefOut(l) for l in u.children[0]])
for u in before:
u.children[1] = replace( u.children[1], [RewriteRule(l, Replacement(WrapBefOut(l))) for l in lhss] )
#
lhss = []
for u in after:
lhss.extend( u.children[0] )
u.children[0] = NList([WrapOutAft(l) for l in u.children[0]])
wrap_rules_after = \
[
RewriteRule(l, Replacement(WrapBefOut(l))) if l in same else
RewriteRule(l, Replacement(WrapOutAft(l))) for l in lhss
]
for u in after:
u.children[1] = replace( u.children[1], wrap_rules_after )
# replace before in before
wrap_rules_before = []
for u in before:
lhs, rhs = u.get_children()
if len(lhs.children) > 1:
wrap_rules_before.append([])
continue
rules = self.expr_to_rule_rhs_lhs( [u] )
wrap_rules_before.append(list(itertools.chain(*rules)))
#
new_rules = []
for i,rules in enumerate(wrap_rules_before):
new_rules.append([])
for rule in rules:
new_r = copy.deepcopy(rule)
new_r.pattern = replace_all(new_r.pattern, list(itertools.chain.from_iterable(wrap_rules_before[:i] + wrap_rules_before[i+1:])))
if new_r.pattern != rule.pattern:
new_rules[-1].append(new_r)
for r1, r2 in zip(new_rules, wrap_rules_before):
r2.extend(r1)
#
wrap_rules_before = list(itertools.chain(*wrap_rules_before))
done = False
while not done:
after_top = [copy.deepcopy(u) for u in after]
for i,u in enumerate(after):
_, rhs = u.get_children()
u.children[1] = simplify(to_canonical(replace_all(copy.deepcopy(rhs), wrap_rules_before)))
done = True
for top, bot in zip(after_top, after):
if top != bot:
done = False
break
# replace after in after
done = False
while not done:
# replace after in after
wrap_rules_after = []
for u in after:
lhs, rhs = u.get_children()
if len(lhs.children) > 1:
wrap_rules_after.append([])
continue
rules = self.expr_to_rule_rhs_lhs( [u] )
wrap_rules_after.append(list(itertools.chain(*rules)))
#
after_top = [copy.deepcopy(u) for u in after]
for i,u in enumerate(after):
_, rhs = u.get_children()
rules = list(itertools.chain.from_iterable(wrap_rules_after[:i] + wrap_rules_after[i+1:]))
u.children[1] = simplify(to_canonical(replace_all(copy.deepcopy(rhs), rules)))
done = True
for top, bot in zip(after_top, after):
if top != bot:
done = False
break
# [TODO] Multiple lhss, won't work
updates = []
for u in after:
lhs, rhs = u.get_children()
lhs = lhs.children[0] # NList[op] -> op
if isinstance(rhs, WrapBefOut) and isinstance(lhs, WrapOutAft) and \
matchq(lhs.children[0], rhs.children[0]):
continue
updates.append(u)
#
tiled_updates = []
for u in updates:
if Config.options.verbose:
print( "* ", u )
tilings = list( tile_expr(u) )
if len(tilings) > 1 and Config.options.verbose:
print( "[WARNING] Multiple (%d) tilings for expression %s" % (len(tilings), u) )
print( " Discarding all but one" )
tiled_updates.extend( tilings[0] )
tiled_updates = sort( tiled_updates )
if Config.options.verbose:
print( "* Tiled update" )
for t in tiled_updates:
print("* ", t)
# Drop WrapOutBef's
# Drop WrapOutAft's
s = PatternDot("s")
updates = []
for u in tiled_updates:
u = replace_all( u, [RewriteRule( WrapOutAft(s), Replacement(lambda d: d["s"]) )] )
u = replace_all( u, [RewriteRule( WrapOutBef(s), Replacement(lambda d: d["s"]) )] )
updates.append( u )
return updates
def find_updates_v2( self, before, after ):
# If a part is (partially) computed in the before and
# does not appear in the after or
# going from before to after requires undoing some computation
# it is potentially unstable, and more expensive: ignore
dict_bef = dict([ (str(u.get_children()[0]), u) for u in before ])
dict_aft = dict([ (str(u.get_children()[0]), u) for u in after ])
ignore = False
quadrant = None
for k,v in dict_bef.items():
if k not in dict_aft:
ignore = True
break
else:
rules = self.expr_to_rule_rhs_lhs( [v] )
rules = list(itertools.chain(*rules))
expr_copy = copy.deepcopy( dict_aft[k] )
t = replace( expr_copy, rules )
#if v == replace( expr_copy, rules ):
if dict_aft[k] == t:
ignore = True
break
if ignore:
print( "[INFO] Skipping invariant: %s" % reason )
return None
#
# Wrap outputs for before and after
WrapBefOut = WrapOutBef
for u in before:
u.children[0] = NList([WrapBefOut(l) for l in u.children[0]])
#
wrap_rules_after = []
for u in after:
u.children[0] = NList([WrapOutAft(l) for l in u.children[0]])
# replace before in after
wrap_rules_before = []
for u in before:
print( u )
lhs, rhs = u.get_children()
if len(lhs.children) > 1:
continue
rules = self.expr_to_rule_rhs_lhs( [u] )
wrap_rules_before.append(list(itertools.chain(*rules)))
#
for i,rule in enumerate(reversed(wrap_rules_before)):
idx = len(wrap_rules_before) - i - 1
for j in range(idx-1,-1,-1):
for _rule in rule:
_rule.pattern = replace_all(_rule.pattern, wrap_rules_before[j])
wrap_rules_before = list(itertools.chain(*wrap_rules_before))
#
for u in after:
_, rhs = u.get_children()
u.children[1] = simplify(to_canonical(replace_all(copy.deepcopy(rhs), wrap_rules_before)))
# replace after in after
done = False
while not done:
# replace after in after
wrap_rules_after = []
for u in after:
lhs, rhs = u.get_children()
if len(lhs.children) > 1:
wrap_rules_after.append([])
continue
rules = self.expr_to_rule_rhs_lhs( [u] )
wrap_rules_after.append(list(itertools.chain(*rules)))
#
after_top = [copy.deepcopy(u) for u in after]
for i,u in enumerate(after):
_, rhs = u.get_children()
rules = list(itertools.chain.from_iterable(wrap_rules_after[:i] + wrap_rules_after[i+1:]))
u.children[1] = simplify(to_canonical(replace_all(copy.deepcopy(rhs), rules)))
done = True
for top, bot in zip(after_top, after):
if top != bot:
done = False
break
# [TODO] Multiple lhss, won't work
updates = []
for u in after:
lhs, rhs = u.get_children()
lhs = lhs.children[0] # NList[op] -> op
if isinstance(rhs, WrapBefOut) and isinstance(lhs, WrapOutAft) and \
matchq(lhs.children[0], rhs.children[0]):
continue
updates.append(u)
#
tiled_updates = []
for u in updates:
if Config.options.verbose:
print( "* ", u )
tilings = list( tile_expr(u) )
if len(tilings) > 1 and Config.options.verbose:
print( "[WARNING] Multiple (%d) tilings for expression %s" % (len(tilings), u) )
print( " Discarding all but one" )
tiled_updates.extend( tilings[0] )
tiled_updates = sort( tiled_updates )
if Config.options.verbose:
print( "* Tiled update" )
for t in tiled_updates:
print("* ", t)
# Drop WrapOutBef's
# Drop WrapOutAft's
s = PatternDot("s")
updates = []
for u in tiled_updates:
u = replace_all( u, [RewriteRule( WrapOutAft(s), Replacement(lambda d: d["s"]) )] )
u = replace_all( u, [RewriteRule( WrapOutBef(s), Replacement(lambda d: d["s"]) )] )
updates.append( u )
return updates
def expr_to_rule_lhs_rhs( self, predicates ):
rules = []
for p in predicates:
lhs, rhs = p.children
if len(lhs.children) == 1:
rules.append( [RewriteRule( lhs.children[0], Replacement(rhs) )] )
return rules
# [TODO] This is quite messy. Needs a serious cleanup
def expr_to_rule_rhs_lhs( self, predicates ):
rules = []
t = PatternStar("t")
l = PatternStar("l")
ld = PatternDot("ld")
r = PatternStar("r")
for p in predicates:
pr = []
lhs, rhs = p.children
if len(lhs.children) == 1:
#lhs_sym = WrapOutBef( lhs.children[0] )
lhs_sym = lhs.children[0]
if isinstance( rhs, Plus ):
# t___ + rhs -> t + lhs
repl_f = (lambda lhs: lambda d: Plus(d["t"].children + [lhs]))(lhs_sym)
pr.append( RewriteRule( Plus([t] + rhs.children),
Replacement(repl_f) ) )
# t___ + l___ rhs_i r___ + ... -> t + l lhs r
repl_f = (lambda lhs: lambda d: Plus(d["t"].children + [Times(d["l"].children + [lhs] + d["r"].children)]))(lhs_sym)
pr.append( RewriteRule( Plus([t] + [ Times([l] + [ch] + [r]) for ch in rhs.children ]),
Replacement(repl_f) ) )
repl_f = (lambda lhs: lambda d: Plus(d["t"].children + [Times([simplify(to_canonical(Minus([lhs])))] + d["r"].children)]))(lhs_sym)
pr.append( RewriteRule( Plus([t] + [ Times( [simplify(to_canonical(Minus([ch])))] + [r]) for ch in rhs.children ]),
Replacement(repl_f) ) )
# A - B C in L B C R + -L A R (minus pushed all the way to the left, and whole thing negated)
repl_f = (lambda lhs: lambda d: normalize_minus(Plus(d["t"].children + [Times([d["ld"]] + d["l"].children + [Minus([lhs])] + d["r"].children)])))(lhs_sym)
pr.append( RewriteRule( Plus([t] + [ normalize_minus( Times([ld, l, Minus([ch]), r]) ) for ch in rhs.children ]),
Replacement(repl_f) ) )
# A - B C in -L B C R + L A R (minus pushed all the way to the left)
repl_f = (lambda lhs: lambda d: Plus(d["t"].children + [Times([d["ld"]] + d["l"].children + [lhs] + d["r"].children)]))(lhs_sym)
pr.append( RewriteRule( Plus([t] + [ normalize_minus( Times([ld, l, ch, r]) ) for ch in rhs.children ]),
Replacement(repl_f) ) )
#repl_f = (lambda lhs: lambda d: Plus(d["t"].children + [Times([simplify(to_canonical(Minus(lhs.children)))] + d["r"].children)]))(lhs_sym)
#pr.append( RewriteRule( Plus([t] + [
#Times([ Minus([ld]), l, ch, r]) if not isinstance(ch, Minus) \
#else Times([ l, ch.children[0], r]) \
#for ch in rhs.children ]),
#Replacement(repl_f) ) )
repl_f = (lambda lhs: lambda d: Plus(d["t"].children + [Times([simplify(to_canonical(Minus([Transpose([lhs])])))] + d["r"].children)]))(lhs_sym)
pr.append( RewriteRule( Plus([t] + [
Times([ Minus([ld]), l, simplify(to_canonical(Transpose([ch]))), r]) if not isinstance(ch, Minus) \
else Times([ l, simplify(to_canonical(Transpose([ch]))), r]) \
for ch in rhs.children ]),
Replacement(repl_f) ) )
elif isinstance( rhs, Times ):
repl_f = (lambda lhs: lambda d: Times(d["l"].children + [lhs] + d["r"].children))(lhs_sym)
pr.append( RewriteRule( Times([l] + rhs.children + [r] ),
Replacement(repl_f) ) )
repl_f = (lambda lhs: lambda d: Times(d["l"].children + [Transpose([lhs])] + d["r"].children))(lhs_sym)
pr.append( RewriteRule( Times([l, simplify(to_canonical(Transpose([rhs]))), r]),
Replacement(repl_f) ) )
# [TODO] Minus is a b*tch. Should go for -1 and remove the operator internally?
repl_f = (lambda lhs: lambda d: Times([simplify(to_canonical(Minus([Times([lhs])])))] + d["r"].children) )(lhs_sym)
pr.append( RewriteRule( Times([simplify(to_canonical(Minus([Times(rhs.get_children())])))] + [r] ),
Replacement(repl_f) ) )
else:
pr.append( RewriteRule( rhs, Replacement(lhs_sym) ) )
new_rhs = simplify(to_canonical(Transpose([rhs])))
if not isOperand( new_rhs ):
pr.append( RewriteRule( simplify(to_canonical(Transpose([rhs]))), Replacement(Transpose([lhs_sym])) ) )
rules.append(pr)
return rules
def before_to_rule( self, before ):
lhs, rhs = before.get_children()
if isinstance( rhs, Plus ):
rules = [ RewriteRule( Plus( [PatternStar("rest")] + rhs.get_children() ),
Replacement( lambda d: Plus(d["rest"].get_children() + lhs.get_children()) ) ),
#Replacement("Plus(rest+lhs.get_children())") )
RewriteRule( Plus([ Times([PatternStar("l")] + [ch] + [PatternStar("r")]) for ch in rhs.get_children() ]),
Replacement( lambda d: Times(d["l"].get_children() + lhs.get_children() + d["r"].get_children()) ) ),
RewriteRule( to_canonical( Plus([ Times([PatternStar("l")] + [ch] + [PatternStar("r")]) for ch in rhs.get_children() ]) ),
Replacement( lambda d: Times(d["l"].get_children() + lhs.get_children() + d["r"].get_children()) ) ) ]
elif isinstance( rhs, Times ):
rules = [ RewriteRule( Times( [PatternStar("l")] + rhs.get_children() + [PatternStar("r")] ),
Replacement( lambda d: Times(d["l"].get_children() + lhs.get_children() + d["r"].get_children()) ) ),
# [TODO] For chol loop invariants 2 and 3, should fix elsewhere (maybe -1 instead of minus operator)
RewriteRule( Times( [PatternStar("l")] + [to_canonical(Minus([Times(rhs.get_children())]))] + [PatternStar("r")] ),
Replacement( lambda d: Times(d["l"].get_children() + [to_canonical(Minus([Times(lhs.get_children())]))] + d["r"].get_children()) ) ) ]
else: # [FIX] what if multiple outputs?
#rules = [ RewriteRule( rhs, Replacement( lhs ) ) ]
rules = [ RewriteRule( rhs, Replacement( lhs.children[0] ) ) ]
return rules
# [TODO] With coupled sylvester, will have to double check a few things here and above
def algorithm_initialization( self, init_state ):
init = []
for expr in init_state:
lhs, rhs = expr.get_children()
lhs_ch = lhs.get_children()
#init.extend([ Equal([ NList([lch]), rhs ]) for lch in lhs_ch if not isZero(lch) and not isZero(rhs) ])
init.extend([ Equal([ NList([lch]), rhs ]) for lch in lhs_ch if not isZero(lch) ])
return init
def generate_predicate_before( self, pme, trav, linv, linv_obj ): # [TODO] Cleanup, no need for linv AND linv_obj
new = [ copy.deepcopy(expr) for expr in itertools.chain(*linv) ]
# Repartition
reparts = dict()
repart_rules = []
for op in linv_obj.linv_operands:
part = linv_obj.linv_operands_basic_part[op.get_name()]
# [CHECK] _shape or not? Regular one needed for inheritance
repart = repartition( op, part.shape, trav[op.get_name()] )
#
#repart_shape = {(1,1):(1,1), (1,2):(1,3), (2,1):(3,1), (2,2):(3,3)}[part.shape]
#repart = repartition_shape( op, repart_shape )
#repart = repart_group( repart, repart_shape, trav[op.get_name()] )
#
for part_op, repart_op in zip( itertools.chain(*part), itertools.chain(*repart) ):
repart_rules.append( RewriteRule( part_op, Replacement( repart_op ) ) )
reparts[op.get_name()] = repart
# Apply repartitionings
new = [ replace( expr, repart_rules ) for expr in new ]
# Explicit functions to BlockedExpression
# First flatten args, then replace
for expr in new:
lhs, rhs = expr.get_children()
if isinstance( rhs, Predicate ):
for i, arg in enumerate( rhs.get_children() ):
#rhs.set_children( i, flatten_blocked_operation(arg) )
rhs.set_children( i, flatten_blocked_operation_click(arg) )
new = [ replace( expr, known_pmes ) for expr in new ]
# Operators applied to BlockedExpression, into BlockedExpressions
for expr in new:
if isinstance( expr, BlockedExpression ):
continue
_, rhs = expr.get_children()
#print( rhs ) # [TODO] Maybe "Sylv(...)"!!!
#rhs = flatten_blocked_operation( rhs )
rhs = flatten_blocked_operation_click( rhs )
expr.set_children( 1, rhs )
# Flatten left-hand sides of the previous type of expressions
for expr in new:
if isinstance( expr, BlockedExpression ):
continue
lhs, rhs = expr.get_children()
new_lhs = []
for out in lhs:
if isinstance( out, Symbol ): # this is a temporary one
out.size = rhs.get_size()
#part = partition_shape( out, rhs.shape )
part = partition_shape( out, tuple(rhs.shape) )
new_lhs.append( part )
else:
new_lhs.append( out )
lhs = BlockedExpression( map_thread( NList, new_lhs, 2 ), (0,0), rhs.shape )
expr.set_children( 0, lhs )
# Flatten the last type of expressions
final = []
for expr in new:
if isinstance( expr, BlockedExpression ):
final.extend( [ simplify( to_canonical( eq ) ) for eq in itertools.chain( *expr ) ] )
else:
lhs, rhs = expr.get_children()
final.extend( [ simplify( to_canonical( eq ) ) for eq in itertools.chain.from_iterable( map_thread( Equal, [lhs, rhs], 2 ) ) ] )
final = filter_zero_zero( final )
# remove expressions of the type " B_10^T = ..." (e.g., in symv)"
_final = final
final = []
for expr in _final:
lhs, rhs = expr.children
lhs = lhs.children
# [FIXME] == 1 only to make sure it does not affect other cases.
# Just want to let them break and study them in the future
if len( lhs ) == 1 and (not isOperand( lhs[0] ) or lhs[0].isZero()):
continue
final.append( expr )
#
# expand in terms of input parts
#
#expand_rules = list(itertools.chain(*self.expr_to_rule_lhs_rhs( final )))
#for expr in final:
#expr.children[1] = simplify(to_canonical(replace_all(copy.deepcopy(expr.children[1]), expand_rules)))
#
# Print and return
#
if Config.options.verbose:
for expr in final:
print( "* ", expr )
return (reparts, final)
def generate_code( self ):
## [LATEX] Algorithms in pdf
#if Config.options.latex:
#latex_dir = os.path.join(Config.latex_dir, self.name)
#try:
#os.makedirs( latex_dir )
#except OSError as err:
#pass
#generate_latex_code( self, latex_dir )
# [MATLAB] Recursive, loop-based and test driver code
if Config.options.matlab:
matlab_dir = os.path.join(Config.matlab_dir, self.name)
try:
os.makedirs( matlab_dir )
except OSError as err:
pass
generate_matlab_code( self, matlab_dir )
return
## [LGEN] Loop based algorithms/code
#if Config.options.lgen:
#if Config.options.opt:
#lgen_dir = os.path.join(Config.lgen_dir, self.name + "_opt")
#else:
#lgen_dir = os.path.join(Config.lgen_dir, self.name)
#try:
#os.makedirs( lgen_dir )
#except OSError as err:
#pass
#generate_lgen_files( self, lgen_dir )
## [FLAMEC] Loop based algorithms/code
#if Config.options.flamec:
#c_dir = os.path.join(Config.c_dir, self.name)
#try:
#os.makedirs( c_dir )
#except OSError as err:
#pass
#generate_c_code( self, c_dir )
| bsd-3-clause |
f97one/MainCameraJoke | app/src/main/java/net/formula97/android/app_maincamerajoke/NetaMessages.java | 2208 | package net.formula97.android.app_maincamerajoke;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* ネタ表示するデータを格納するエンティティクラス。
* Created by HAJIME on 2014/06/19.
*/
@DatabaseTable(tableName = "NetaMessages")
public class NetaMessages {
/**
* 管理用主キー
*/
@DatabaseField(generatedId = true, unique = true)
private Integer _id;
/**
* ネタ表示のメッセージ本文
*/
@DatabaseField
private String messageBody;
/**
* ユーザにより追加されたか否かを表す。アップグレード管理用。<br />
* trueならユーザー追加、falseならシステム組み込み。
*/
@DatabaseField(defaultValue = "true")
private boolean userDefined;
/**
* コンストラクタ。<br />
* OrmLiteの動作に必要。
*/
public NetaMessages() {
}
/**
* ユーザーによるメッセージ本文とみなすコンストラクタ。
*
* @param messageBody 登録したいメッセージ本文
*/
public NetaMessages(String messageBody) {
setMessageBody(messageBody);
setUserDefined(true);
}
/**
* メッセージ登録者がユーザーか否かを明示したい場合に使用するコンストラクタ。
*
* @param messageBody 登録したいメッセージ本文
* @param userDefined ユーザーによる登録とする場合はtrue、システムによる登録とする場合はfalse
*/
public NetaMessages(String messageBody, boolean userDefined) {
setMessageBody(messageBody);
setUserDefined(userDefined);
}
public Integer get_id() {
return _id;
}
public void set_id(Integer _id) {
this._id = _id;
}
public String getMessageBody() {
return messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public boolean isUserDefined() {
return userDefined;
}
public void setUserDefined(boolean userDefined) {
this.userDefined = userDefined;
}
}
| bsd-3-clause |
paksv/vijava | src/com/vmware/vim25/PhysicalNicIpHint.java | 1991 | /*================================================================================
Copyright (c) 2013 Steve Jin. 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 VMware, Inc. 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 VMWARE, INC. 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.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class PhysicalNicIpHint extends PhysicalNicHint {
public String ipSubnet;
public String getIpSubnet() {
return this.ipSubnet;
}
public void setIpSubnet(String ipSubnet) {
this.ipSubnet=ipSubnet;
}
} | bsd-3-clause |
cingwun/test-yii | views/test/country.php | 695 | <?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
$this->params['breadcrumbs'][] = ['label' => 'Countries', 'url' => ['test/country']];
?>
<h1>Countries</h1>
<div>
<?= Html::a('Create Country', ['test/create'], ['class' => 'btn btn-success']) ?>
</div>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>country</th>
<th>code</th>
<th>population</th>
</tr>
</thead>
<tbody>
<?php foreach ($countries as $idx => $country): ?>
<tr>
<td><?=$idx+1?></td>
<td><?=$country->name?></td>
<td><?=$country->code?></td>
<td><?=$country->population?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= LinkPager::widget(['pagination' => $pagination]) ?>
| bsd-3-clause |
maxhutch/magma | sparse-iter/src/cftjacobi.cpp | 6623 | /*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@author Hartwig Anzt
@generated from sparse-iter/src/zftjacobi.cpp, normal z -> c, Tue Aug 30 09:38:55 2016
*/
#include "magmasparse_internal.h"
#define RTOLERANCE lapackf77_slamch( "E" )
#define ATOLERANCE lapackf77_slamch( "E" )
/**
Purpose
-------
Iterates the solution approximation according to
x^(k+1) = D^(-1) * b - D^(-1) * (L+U) * x^k
x^(k+1) = c - M * x^k.
This routine takes the system matrix A and the RHS b as input.
This is the fault-tolerant version of Jacobi according to ScalLA'15.
Arguments
---------
@param[in]
A magma_c_matrix
input matrix M = D^(-1) * (L+U)
@param[in]
b magma_c_matrix
input RHS b
@param[in,out]
x magma_c_matrix*
iteration vector x
@param[in,out]
solver_par magma_c_solver_par*
solver parameters
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_c
********************************************************************/
extern "C" magma_int_t
magma_cftjacobi(
magma_c_matrix A,
magma_c_matrix b,
magma_c_matrix *x,
magma_c_solver_par *solver_par,
magma_queue_t queue )
{
magma_int_t info = MAGMA_NOTCONVERGED;
// some useful variables
real_Double_t tempo1, tempo2, runtime=0;
float residual;
// local variables
magmaFloatComplex c_zero = MAGMA_C_ZERO;
magma_int_t dofs = A.num_cols;
magma_int_t k = solver_par->verbose;
magma_c_matrix xkm2 = {Magma_CSR};
magma_c_matrix xkm1 = {Magma_CSR};
magma_c_matrix xk = {Magma_CSR};
magma_c_matrix z = {Magma_CSR};
magma_c_matrix c = {Magma_CSR};
magma_int_t *flag_t = NULL;
magma_int_t *flag_fp = NULL;
float delta = 0.9;
solver_par->numiter = 0;
solver_par->spmv_count = 0;
magma_c_matrix r={Magma_CSR}, d={Magma_CSR}, ACSR={Magma_CSR};
CHECK( magma_cmconvert(A, &ACSR, A.storage_type, Magma_CSR, queue ) );
// prepare solver feedback
solver_par->solver = Magma_JACOBI;
solver_par->info = MAGMA_SUCCESS;
// solver setup
CHECK( magma_cvinit( &r, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cresidualvec( ACSR, b, *x, &r, &residual, queue));
solver_par->init_res = residual;
if ( solver_par->verbose > 0 ) {
solver_par->res_vec[0] = (real_Double_t) residual;
}
//nom0 = residual;
// Jacobi setup
CHECK( magma_cjacobisetup_diagscal( ACSR, &d, queue ));
magma_c_solver_par jacobiiter_par;
if ( solver_par->verbose > 0 ) {
jacobiiter_par.maxiter = solver_par->verbose;
}
else {
jacobiiter_par.maxiter = solver_par->maxiter;
}
k = jacobiiter_par.maxiter;
CHECK( magma_cvinit( &xkm2, Magma_DEV, b.num_rows, 1, c_zero, queue ));
CHECK( magma_cvinit( &xkm1, Magma_DEV, b.num_rows, 1, c_zero, queue ));
CHECK( magma_cvinit( &xk, Magma_DEV, b.num_rows, 1, c_zero, queue ));
CHECK( magma_cvinit( &z, Magma_DEV, b.num_rows, 1, c_zero, queue ));
CHECK( magma_cvinit( &c, Magma_DEV, b.num_rows, 1, c_zero, queue ));
CHECK( magma_imalloc( &flag_t, b.num_rows ));
CHECK( magma_imalloc( &flag_fp, b.num_rows ));
if ( solver_par->verbose != 0 ) {
// k iterations for startup
tempo1 = magma_sync_wtime( queue );
CHECK( magma_cjacobispmvupdate(k, ACSR, r, b, d, x, queue ));
tempo2 = magma_sync_wtime( queue );
runtime += tempo2 - tempo1;
solver_par->spmv_count=solver_par->spmv_count+k;
solver_par->numiter=solver_par->numiter+k;
// save in xkm2
magma_ccopyvector( dofs, x->dval, 1, xkm2.dval, 1, queue );
// two times k iterations for computing the contraction constants
tempo1 = magma_sync_wtime( queue );
CHECK( magma_cjacobispmvupdate(k, ACSR, r, b, d, x, queue ));
tempo2 = magma_sync_wtime( queue );
runtime += tempo2 - tempo1;
solver_par->spmv_count=solver_par->spmv_count+k;
solver_par->numiter=solver_par->numiter+k;
// save in xkm1
tempo1 = magma_sync_wtime( queue );
magma_ccopyvector( dofs, x->dval, 1, xkm1.dval, 1, queue );
CHECK( magma_cjacobispmvupdate(k, ACSR, r, b, d, x, queue ));
tempo2 = magma_sync_wtime( queue );
runtime += tempo2 - tempo1;
solver_par->spmv_count=solver_par->spmv_count+k;
solver_par->numiter=solver_par->numiter+k;
// compute contraction constants
magma_ccopyvector( dofs, x->dval, 1, xk.dval, 1, queue );
magma_cftjacobicontractions( xkm2, xkm1, xk, &z, &c, queue );
}
// Jacobi iterator
do {
tempo1 = magma_sync_wtime( queue );
solver_par->numiter = solver_par->numiter+jacobiiter_par.maxiter;
CHECK( magma_cjacobispmvupdate(jacobiiter_par.maxiter, ACSR, r, b, d, x, queue ));
if( solver_par->verbose != 0 ){
magma_cftjacobiupdatecheck( delta, &xk, x, &z, c, flag_t, flag_fp, queue );
}
solver_par->spmv_count=solver_par->spmv_count+k;
tempo2 = magma_sync_wtime( queue );
runtime += tempo2 - tempo1;
if ( solver_par->verbose > 0 ) {
CHECK( magma_cresidualvec( ACSR, b, *x, &r, &residual, queue));
solver_par->res_vec[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) residual;
solver_par->timing[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) runtime;
}
}
while ( solver_par->numiter+1 <= solver_par->maxiter );
solver_par->runtime = (real_Double_t) runtime;
CHECK( magma_cresidualvec( A, b, *x, &r, &residual, queue));
solver_par->final_res = residual;
if ( solver_par->init_res > solver_par->final_res )
info = MAGMA_SUCCESS;
else
info = MAGMA_DIVERGENCE;
cleanup:
magma_cmfree( &r, queue );
magma_cmfree( &d, queue );
magma_cmfree( &ACSR, queue );
magma_cmfree( &xkm2, queue );
magma_cmfree( &xkm1, queue );
magma_cmfree( &xk, queue );
magma_cmfree( &z, queue );
magma_cmfree( &c, queue );
magma_free( flag_t );
magma_free( flag_fp );
solver_par->info = info;
return info;
} /* magma_cftjacobi */
| bsd-3-clause |
alexissmirnov/donomo | donomo_archive/lib/donomo/archive/media/js/tjpzoom/tjpzoom_config_smart.js | 978 | // TJPzoom 3 configuration file * János Pál Tóth
// 2007.04.28
// Docs @ http://valid.tjp.hu/tjpzoom/
// News @ http://tjpzoom.blogspot.com/
// SMART
// a bit of a border (2px)
// and a bit of a drop shadow
// smart cursor following mode
var TJPzoomwidth=160; //zoom window size
var TJPzoomheight=120;
var TJPzoomwindowlock=0; //set to 1 to lock window size
var TJPzoomoffset='smart'; //turning on the wonderful smart mode!
var TJPzoomamount=4;
var TJPzoomamountmax=12;
var TJPzoomamountmin=1;
var TJPborderthick=2; //border thickness, SET 0 to no borders
var TJPbordercolor='#cccccc'; //border color
var TJPshadowthick=8; //shadow image size/2, SET 0 to have no shadows (saves cpu)
var TJPshadow='dropshadow/'; // <>: n, ne, e, se, s, sw, w, nw - TJPshadow+'nw.png'
// TJPzoom 3 configuration file * János Pál Tóth
// Docs @ http://valid.tjp.hu/tjpzoom/
// News @ http://tjpzoom.blogspot.com/
| bsd-3-clause |
socialdevices/manager | core/migrations/0009_auto__chg_field_actiondevice_parameter_position.py | 11138 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'ActionDevice.parameter_position'
db.alter_column('core_actiondevice', 'parameter_position', self.gf('django.db.models.fields.SmallIntegerField')(default=0))
def backwards(self, orm):
# Changing field 'ActionDevice.parameter_position'
db.alter_column('core_actiondevice', 'parameter_position', self.gf('django.db.models.fields.SmallIntegerField')(null=True))
models = {
'core.action': {
'Meta': {'object_name': 'Action'},
'action_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'precondition_expression': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.actiondevice': {
'Meta': {'unique_together': "(('action', 'name'), ('action', 'parameter_position'))", 'object_name': 'ActionDevice'},
'action': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Action']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'interfaces': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Interface']", 'through': "orm['core.ActionDeviceInterface']", 'symmetrical': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'parameter_position': ('django.db.models.fields.SmallIntegerField', [], {}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.actiondeviceinterface': {
'Meta': {'unique_together': "(('action_device', 'interface'),)", 'object_name': 'ActionDeviceInterface'},
'action_device': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.ActionDevice']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'interface': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Interface']"})
},
'core.actionpreconditionmethod': {
'Meta': {'unique_together': "(('action', 'expression_position'),)", 'object_name': 'ActionPreconditionMethod'},
'action': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Action']"}),
'action_device': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.ActionDevice']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'expression_position': ('django.db.models.fields.SmallIntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Method']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.datatype': {
'Meta': {'object_name': 'DataType'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.device': {
'Meta': {'object_name': 'Device'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'interfaces': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Interface']", 'through': "orm['core.DeviceInterface']", 'symmetrical': 'False'}),
'is_reserved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'mac_address': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '17'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.deviceinterface': {
'Meta': {'unique_together': "(('device', 'interface'),)", 'object_name': 'DeviceInterface'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'device': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Device']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'interface': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Interface']"})
},
'core.interface': {
'Meta': {'object_name': 'Interface'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'interface_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.method': {
'Meta': {'unique_together': "(('name', 'interface'),)", 'object_name': 'Method'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'interface': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Interface']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'return_data_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.DataType']", 'null': 'True', 'blank': 'True'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.methodparameter': {
'Meta': {'unique_together': "(('name', 'method'),)", 'object_name': 'MethodParameter'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'data_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.DataType']", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Method']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.schedule': {
'Meta': {'object_name': 'Schedule'},
'actions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['core.Action']", 'through': "orm['core.ScheduleAction']", 'symmetrical': 'False'}),
'configuration_model_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'configuration_model_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'schedule_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'trigger': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Trigger']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'core.scheduleaction': {
'Meta': {'unique_together': "(('schedule', 'action'),)", 'object_name': 'ScheduleAction'},
'action': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Action']"}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'schedule': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Schedule']"}),
'trigger_from_position': ('django.db.models.fields.SmallIntegerField', [], {'null': 'True', 'blank': 'True'})
},
'core.statevalue': {
'Meta': {'unique_together': "(('device', 'method'),)", 'object_name': 'StateValue'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'device': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Device']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Method']"}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'core.trigger': {
'Meta': {'object_name': 'Trigger'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'method': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Method']", 'unique': 'True'}),
'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
}
}
complete_apps = ['core']
| bsd-3-clause |
solanolabs/rply | rply/errors.py | 264 | class ParserGeneratorError(Exception):
pass
class ParsingError(Exception):
def __init__(self, source_pos):
self.source_pos = source_pos
def getsourcepos(self):
return self.source_pos
class ParserGeneratorWarning(Warning):
pass
| bsd-3-clause |
slotix/dataflowkit | fetch/server.go | 2496 | package fetch
import (
"context"
"fmt"
"net/http"
"os"
"sync"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Config provides basic configuration
type Config struct {
Host string
Version string
}
// HTMLServer represents the web service that serves up HTML
type HTMLServer struct {
server *http.Server
wg sync.WaitGroup
}
// Start func launches Parsing service
func Start(cfg Config) *HTMLServer {
// Setup Context
ctx := context.Background()
_, cancel := context.WithCancel(ctx)
defer cancel()
encoderCfg := zapcore.EncoderConfig{
TimeKey: "ts",
MessageKey: "msg",
LevelKey: "level",
NameKey: "fetcher",
EncodeLevel: zapcore.CapitalColorLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder,
EncodeName: zapcore.FullNameEncoder,
}
core := zapcore.NewCore(zapcore.NewConsoleEncoder(encoderCfg), os.Stdout, zapcore.DebugLevel)
logger := zap.New(core)
defer logger.Sync() // flushes buffer, if any
var svc Service
svc = FetchService{}
//svc = RobotsTxtMiddleware()(svc)
//svc = LoggingMiddleware(logger)(svc)
endpoints := endpoints{
fetchEndpoint: makeFetchEndpoint(svc),
}
r := newHttpHandler(ctx, endpoints)
// Create the HTML Server
htmlServer := HTMLServer{
server: &http.Server{
Addr: cfg.Host,
Handler: r,
MaxHeaderBytes: 1 << 20,
},
}
// Add to the WaitGroup for the listener goroutine
htmlServer.wg.Add(1)
go func() {
fmt.Printf("\n%s\nStarting ...%s",
cfg.Version,
htmlServer.server.Addr,
)
htmlServer.server.ListenAndServe()
htmlServer.wg.Done()
}()
return &htmlServer
}
// Stop turns off the HTML Server
func (htmlServer *HTMLServer) Stop() error {
// Create a context to attempt a graceful 5 second shutdown.
const timeout = 5 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
fmt.Printf("\nFetch Server : Service stopping\n")
// Attempt the graceful shutdown by closing the listener
// and completing all inflight requests
if err := htmlServer.server.Shutdown(ctx); err != nil {
// Looks like we timed out on the graceful shutdown. Force close.
if err := htmlServer.server.Close(); err != nil {
fmt.Printf("\nFetch Server : Service stopping : Error=%v\n", err)
return err
}
}
// Wait for the listener to report that it is closed.
htmlServer.wg.Wait()
fmt.Printf("\nFetch Server : Stopped\n")
return nil
}
| bsd-3-clause |
fimex/sistema | frontend/assets/js/script.js | 766 | var app = angular.module("MyFirseModule",[]);
app.controller("FirseController",function ($scope,$http) {
$scope.valor = function () {
if ($scope.numero == '') {
$scope.numero = 0;
};
};
});
function justNumbers(e) {
var keynum = window.event ? window.event.keyCode : e.which;
if ( keynum == 8 ) return true;
return /\d/.test(String.fromCharCode(keynum));
}
function getkey (event,objeto) {
if (event.charCode == 0){
if (event.target == objeto){
return false;
};
};
}
function sumarDias(dias,fecha){
dias = fecha == undefined ? 0 : dias;
fecha = fecha == undefined ? new Date() : new Date(fecha);
var zn = fecha.getTimezoneOffset() * 1000 * 60;
fecha.setTime(fecha.getTime()+parseInt(dias*24*60*60*1000)+zn);
return fecha;
} | bsd-3-clause |
kiichi7/DungeonQuestGDC | Collision/CollisionGeometry.cs | 18633 | // Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\Collision
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:37
#region Using directives
using DungeonQuest.Helpers;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
#endregion
namespace DungeonQuest.Collision
{
/// <summary>
/// Collision mesh
/// </summary>
class CollisionGeometry
{
#region Constants
/// <summary>
/// Default Extension for Collada files exported with 3ds max.
/// </summary>
public const string ColladaDirectory = "Content\\Models",
ColladaExtension = "DAE";
#endregion
#region Variables
/// <summary>
/// Vectors for this mesh, we don't care about anything else!
/// </summary>
private Vector3[] vectors;
/// <summary>
/// Indices for all the triangles. Should be optimized together with
/// the vectors (no duplicates there) for the best performance.
/// This array is just used for loading, for processing the collision
/// we use the collision faces and the collision tree!
/// </summary>
private int[] indices;
/// <summary>
/// Collision mesh faces
/// </summary>
CollisionPolygon[] faces;
/// <summary>
/// Collision tree with meshes faces
/// </summary>
CollisionHelper tree;
#endregion
#region Constructor
/// <summary>
/// Create a collision mesh from a collada file
/// </summary>
/// <param name="setName">Set name</param>
public CollisionGeometry(string setName)
{
// Set name to identify this model and build the filename
string filename = Path.Combine(ColladaDirectory,
StringHelper.ExtractFilename(setName, true) + "." +
ColladaExtension);
// Load file
Stream file = File.OpenRead(filename);
string colladaXml = new StreamReader(file).ReadToEnd();
XmlNode colladaFile = XmlHelper.LoadXmlFromText(colladaXml);
// Load mesh (vectors and indices)
LoadMesh(colladaFile);
// Close file, we are done.
file.Close();
} // CollisionMesh(setName)
#endregion
#region Load collada matrix helper method
/// <summary>
/// Create matrix from collada float value array. The matrices in collada
/// are stored differently from the xna format (row based instead of
/// columns).
/// </summary>
/// <param name="mat">mat</param>
/// <returns>Matrix</returns>
protected Matrix LoadColladaMatrix(float[] mat, int offset)
{
return new Matrix(
mat[offset + 0], mat[offset + 4], mat[offset + 8], mat[offset + 12],
mat[offset + 1], mat[offset + 5], mat[offset + 9], mat[offset + 13],
mat[offset + 2], mat[offset + 6], mat[offset + 10], mat[offset + 14],
mat[offset + 3], mat[offset + 7], mat[offset + 11], mat[offset + 15]);
} // LoadColladaMatrix(mat, offset)
/// <summary>
/// Only scale transformation down to globalScaling, left rest of
/// the matrix intact. This is required for rendering because all the
/// models have their own scaling!
/// </summary>
/// <param name="mat">Matrix</param>
/// <returns>Matrix</returns>
protected Matrix OnlyScaleTransformation(Matrix mat)
{
mat.Translation = mat.Translation * globalScaling;
return mat;
} // OnlyScaleTransformation(mat)
/// <summary>
/// Only scale transformation inverse
/// </summary>
/// <param name="mat">Matrix</param>
/// <returns>Matrix</returns>
protected Matrix OnlyScaleTransformationInverse(Matrix mat)
{
mat.Translation = mat.Translation / globalScaling;
return mat;
} // OnlyScaleTransformationInverse(mat)
#endregion
#region Load mesh
/// <summary>
/// Load mesh, must be called after we got all bones. Will also create
/// the vertex and index buffers and optimize the vertices as much as
/// we can.
/// </summary>
/// <param name="colladaFile">Collada file</param>
private void LoadMesh(XmlNode colladaFile)
{
XmlNode geometrys =
XmlHelper.GetChildNode(colladaFile, "library_geometries");
if (geometrys == null)
throw new InvalidOperationException(
"library_geometries node not found in collision file");
foreach (XmlNode geometry in geometrys)
if (geometry.Name == "geometry")
{
// Load everything from the mesh node
LoadMeshGeometry(colladaFile,
XmlHelper.GetChildNode(colladaFile, "mesh"),
XmlHelper.GetXmlAttribute(geometry, "name"));
// Optimize vertices first and build index buffer from that!
indices = OptimizeVertexBuffer();
// Copy and create everything to CollisionFace
faces = new CollisionPolygon[indices.Length / 3];
for (int i = 0; i < indices.Length / 3; i++)
{
faces[i] = new CollisionPolygon(i * 3, indices, 0, vectors);
} // for (int)
BoxHelper box = new BoxHelper(float.MaxValue, -float.MaxValue);
for (int i = 0; i < vectors.Length; i++)
box.AddPoint(vectors[i]);
uint subdivLevel = 4; // max 8^6 nodes
tree = new CollisionHelper(box, subdivLevel);
for (int i = 0; i < faces.Length; i++)
tree.AddElement(faces[i]);
// Get outa here, we currently only support one single mesh!
return;
} // foreach if (geometry.Name)
} // LoadMesh(colladaFile)
/// <summary>
/// Helpers to remember how we can reuse vertices for OptimizeVertexBuffer.
/// See below for more details.
/// </summary>
int[] reuseVertexPositions;
/// <summary>
/// Reverse reuse vertex positions, this one is even more important because
/// this way we can get a list of used vertices for a shared vertex pos.
/// </summary>
List<int>[] reverseReuseVertexPositions;
/// <summary>
/// Global scaling we get for importing the mesh and all positions.
/// This is important because 3DS max might use different units than we are.
/// </summary>
protected float globalScaling = 1.0f;
/// <summary>
/// Object matrix. Not really needed here.
/// </summary>
Matrix objectMatrix = Matrix.Identity;
/// <summary>
/// Load mesh geometry
/// </summary>
/// <param name="geometry"></param>
private void LoadMeshGeometry(XmlNode colladaFile,
XmlNode meshNode, string meshName)
{
#region Load all source nodes
Dictionary<string, List<float>> sources = new Dictionary<string,
List<float>>();
foreach (XmlNode node in meshNode)
{
if (node.Name != "source")
continue;
XmlNode floatArray = XmlHelper.GetChildNode(node, "float_array");
List<float> floats = new List<float>(
StringHelper.ConvertStringToFloatArray(floatArray.InnerText));
// Fill the array up
int count = Convert.ToInt32(XmlHelper.GetXmlAttribute(floatArray,
"count"), NumberFormatInfo.InvariantInfo);
while (floats.Count < count)
floats.Add(0.0f);
sources.Add(XmlHelper.GetXmlAttribute(node, "id"), floats);
} // foreach (node)
#endregion
#region Vertices
// Also add vertices node, redirected to position node into sources
XmlNode verticesNode = XmlHelper.GetChildNode(meshNode, "vertices");
XmlNode posInput = XmlHelper.GetChildNode(verticesNode, "input");
if (XmlHelper.GetXmlAttribute(posInput, "semantic").ToLower(
CultureInfo.InvariantCulture) != "position")
throw new InvalidOperationException(
"unsupported feature found in collada \"vertices\" node");
string verticesValueName = XmlHelper.GetXmlAttribute(posInput,
"source").Substring(1);
sources.Add(XmlHelper.GetXmlAttribute(verticesNode, "id"),
sources[verticesValueName]);
#endregion
#region Get the global scaling from the exported units to meters!
XmlNode unitNode = XmlHelper.GetChildNode(
XmlHelper.GetChildNode(colladaFile, "asset"), "unit");
globalScaling = Convert.ToSingle(
XmlHelper.GetXmlAttribute(unitNode, "meter"),
NumberFormatInfo.InvariantInfo);
#endregion
#region Get the object matrix (its in the visual_scene node at the end)
XmlNode sceneStuff = XmlHelper.GetChildNode(
XmlHelper.GetChildNode(colladaFile, "library_visual_scenes"),
"visual_scene");
if (sceneStuff == null)
throw new InvalidOperationException(
"library_visual_scenes node not found in collision file");
// Search for the node with the name of this geometry.
foreach (XmlNode node in sceneStuff)
if (node.Name == "node" &&
XmlHelper.GetXmlAttribute(node, "name") == meshName &&
XmlHelper.GetChildNode(node, "matrix") != null)
{
// Get the object matrix
objectMatrix = LoadColladaMatrix(
StringHelper.ConvertStringToFloatArray(
XmlHelper.GetChildNode(node, "matrix").InnerText), 0) *
Matrix.CreateScale(globalScaling);
break;
} // foreach if (node.Name)
#endregion
#region Construct all triangle polygons from the vertex data
// Construct and generate vertices lists. Every 3 vertices will
// span one triangle polygon, but everything is optimized later.
foreach (XmlNode trianglenode in meshNode)
{
if (trianglenode.Name != "triangles")
continue;
// Find data source nodes
XmlNode positionsnode = XmlHelper.GetChildNode(trianglenode,
"semantic", "VERTEX");
// All the rest is ignored
// Get the data of the sources
List<float> positions = sources[XmlHelper.GetXmlAttribute(
positionsnode, "source").Substring(1)];
// Find the Offsets
int positionsoffset = Convert.ToInt32(XmlHelper.GetXmlAttribute(
positionsnode, "offset"), NumberFormatInfo.InvariantInfo);
// Get the indexlist
XmlNode p = XmlHelper.GetChildNode(trianglenode, "p");
int[] pints = StringHelper.ConvertStringToIntArray(p.InnerText);
int trianglecount = Convert.ToInt32(XmlHelper.GetXmlAttribute(
trianglenode, "count"), NumberFormatInfo.InvariantInfo);
// The number of ints that form one vertex:
int vertexcomponentcount = pints.Length / trianglecount / 3;
// Construct data
// Initialize reuseVertexPositions and reverseReuseVertexPositions
// to make it easier to use them below
reuseVertexPositions = new int[trianglecount * 3];
reverseReuseVertexPositions = new List<int>[positions.Count / 3];
for (int i = 0; i < reverseReuseVertexPositions.Length; i++)
reverseReuseVertexPositions[i] = new List<int>();
vectors = new Vector3[trianglecount * 3];
// We have to use int indices here because we often have models
// with more than 64k triangles (even if that gets optimized later).
for (int i = 0; i < trianglecount * 3; i++)
{
// Position
int pos = pints[i * vertexcomponentcount + positionsoffset] * 3;
Vector3 position = new Vector3(
positions[pos], positions[pos + 1], positions[pos + 2]);
// For the cave mesh we are not going to use a world matrix,
// Just scale everything correctly right here!
position *= globalScaling;
// Set the vertex
vectors[i] = position;
// Remember pos for optimizing the vertices later more easily.
reuseVertexPositions[i] = pos / 3;
reverseReuseVertexPositions[pos / 3].Add(i);
} // for (int)
// Only support one mesh for now, get outta here.
return;
} // foreach (trianglenode)
throw new InvalidOperationException(
"No mesh found in this collada file, unable to continue!");
#endregion
} // LoadMeshGeometry(colladaFile, meshNode, meshName)
#endregion
#region Optimize vertex buffer
#region Flip index order
/// <summary>
/// Little helper method to flip indices from 0, 1, 2 to 0, 2, 1.
/// This way we can render with CullClockwiseFace (default for XNA).
/// </summary>
/// <param name="oldIndex"></param>
/// <returns></returns>
private int FlipIndexOrder(int oldIndex)
{
int polygonIndex = oldIndex % 3;
if (polygonIndex == 0)
return oldIndex;
else if (polygonIndex == 1)
return oldIndex + 1;
else //if (polygonIndex == 2)
return oldIndex - 1;
} // FlipIndexOrder(oldIndex)
#endregion
#region OptimizeVertexBuffer
/// <summary>
/// Optimize vertex buffer. Note: The vertices list array will be changed
/// and shorted quite a lot here. We are also going to create the indices
/// for the index buffer here (we don't have them yet, they are just
/// sequential from the loading process above).
///
/// Note: This method is highly optimized for speed, it performs
/// hundred of times faster than OptimizeVertexBufferSlow, see below!
/// </summary>
/// <returns>int array for the optimized indices</returns>
private int[] OptimizeVertexBuffer()
{
List<Vector3> newVertices =
new List<Vector3>();
List<int> newIndices = new List<int>();
// Helper to only search already added newVertices and for checking the
// old position indices by transforming them into newVertices indices.
List<int> newVerticesPositions = new List<int>();
// Go over all vertices (indices are currently 1:1 with the vertices)
for (int num = 0; num < vectors.Length; num++)
{
// Get current vertex
Vector3 currentVertex = vectors[num];
bool reusedExistingVertex = false;
// Find out which position index was used, then we can compare
// all other vertices that share this position. They will not
// all be equal, but some of them can be merged.
int sharedPos = reuseVertexPositions[num];
foreach (int otherVertexIndex in reverseReuseVertexPositions[sharedPos])
{
// Only check the indices that have already been added!
if (otherVertexIndex != num &&
// Make sure we already are that far in our new index list
otherVertexIndex < newIndices.Count &&
// And make sure this index has been added to newVertices yet!
newIndices[otherVertexIndex] < newVertices.Count &&
// Then finally compare vertices (this call is slow, but thanks to
// all the other optimizations we don't have to call it that often)
currentVertex == newVertices[newIndices[otherVertexIndex]])
{
// Reuse the existing vertex, don't add it again, just
// add another index for it!
newIndices.Add(newIndices[otherVertexIndex]);
reusedExistingVertex = true;
break;
} // if (otherVertexIndex)
} // foreach (otherVertexIndex)
if (reusedExistingVertex == false)
{
// Add the currentVertex and set it as the current index
newIndices.Add(newVertices.Count);
newVertices.Add(currentVertex);
} // if (reusedExistingVertex)
} // for (num)
// Finally flip order of all triangles to allow us rendering
// with CullCounterClockwiseFace (default for XNA) because all the data
// is in CullClockwiseFace format right now!
for (int num = 0; num < newIndices.Count / 3; num++)
{
int swap = newIndices[num * 3 + 1];
newIndices[num * 3 + 1] = newIndices[num * 3 + 2];
newIndices[num * 3 + 2] = swap;
} // for (num)
// Reassign the vertices, we might have deleted some duplicates!
vectors = newVertices.ToArray();
// And return index list for the caller
return newIndices.ToArray();
} // OptimizeVertexBuffer()
#endregion
#endregion
#region Collision testing
/// <summary>
/// Point intersect
/// </summary>
/// <param name="ray_start">Ray _start</param>
/// <param name="ray_end">Ray _end</param>
/// <param name="distance">Intersect _distance</param>
/// <param name="collisionPosition">Intersect _position</param>
/// <param name="collisionNormal">Intersect _normal</param>
/// <returns>Bool</returns>
public bool DoesRayIntersect(Vector3 ray_start, Vector3 ray_end,
out float distance, out Vector3 collisionPosition,
out Vector3 collisionNormal)
{
return tree.DoesRayIntersect(
Ray.FromStartAndEnd(ray_start, ray_end), vectors,
out distance, out collisionPosition, out collisionNormal);
} // DoesRayIntersect(ray_start, ray_end, distance)
/// <summary>
/// Box intersect
/// </summary>
/// <param name="box">Box</param>
/// <param name="ray_start">Ray _start</param>
/// <param name="ray_end">Ray _end</param>
/// <param name="distance">Intersect _distance</param>
/// <param name="collisionPosition">Intersect _position</param>
/// <param name="collisionNormal">Intersect _normal</param>
/// <returns>Bool</returns>
public bool DoesBoxIntersect(BoxHelper box, Ray ray, out float distance,
out Vector3 collisionPosition, out Vector3 collisionNormal)
{
return tree.DoesBoxIntersect(box, ray, vectors,
out distance, out collisionPosition, out collisionNormal);
} // DoesBoxIntersect(box, ray_start, ray_end)
/// <summary>
/// Point move
/// </summary>
/// <param name="pointStart">Point _start</param>
/// <param name="pointEnd">Point _end</param>
/// <param name="frictionFactor">Friction _factor</param>
/// <param name="bumpFactor">Bump mapping _factor</param>
/// <param name="recurseLevel">Recurse _level</param>
/// <param name="pointResult">Point _result</param>
/// <param name="velocityResult">Velocity _result</param>
public void PointMove(Vector3 pointStart, Vector3 pointEnd,
float frictionFactor, float bumpFactor, uint recurseLevel,
out Vector3 pointResult, ref Vector3 velocityResult,
out Vector3 polyPoint)
{
tree.PointMove(pointStart, pointEnd, vectors, frictionFactor,
bumpFactor, recurseLevel, out pointResult, ref velocityResult,
out polyPoint);
} // PointMove(pointStart, pointEnd, frictionFactor)
/// <summary>
/// Box move
/// </summary>
/// <param name="box">Box</param>
/// <param name="pointStart">Point _start</param>
/// <param name="pointEnd">Point _end</param>
/// <param name="frictionFactor">Friction _factor</param>
/// <param name="bumpFactor">Bump mapping _factor</param>
/// <param name="recurseLevel">Recurse _level</param>
/// <param name="pointResult">Point _result</param>
/// <param name="velocityResult">Velocity _result</param>
public void BoxMove(BoxHelper box, Vector3 pointStart,
Vector3 pointEnd, float frictionFactor, float bumpFactor,
uint recurseLevel, out Vector3 pointResult, ref Vector3 velocityResult)
{
tree.BoxMove(box, pointStart, pointEnd, vectors, frictionFactor,
bumpFactor, recurseLevel, out pointResult, ref velocityResult);
} // BoxMove(box, pointStart, pointEnd)
/// <summary>
/// Get elements
/// </summary>
/// <param name="b">B</param>
/// <param name="e">E</param>
public void GetElements(BoxHelper b, List<BaseCollisionObject> e)
{
tree.GetElements(b, e);
} // GetElements(b, e)
#endregion
#region Unit Testing
#if DEBUG
//TODO?
#endif
#endregion
} // class CollisionMesh
} // namespace DungeonQuest.Collision
| bsd-3-clause |
tkf/neo | neo/test/io/test_micromedio.py | 509 | # encoding: utf-8
"""
Tests of io.asciisignalio
"""
from __future__ import division
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import MicromedIO
import numpy
from neo.test.io.common_io_test import BaseTestIO
class TestMicromedIO(BaseTestIO, unittest.TestCase, ):
ioclass = MicromedIO
files_to_test = [ 'File_micromed_1.TRC',
]
files_to_download = files_to_test
if __name__ == "__main__":
unittest.main()
| bsd-3-clause |
jphalip/django-treemenus | treemenus/tests/urls.py | 366 | try:
from django.conf.urls import patterns, include
except ImportError: # Django < 1.4
from django.conf.urls.defaults import patterns, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^test_treemenus_admin/', include(admin.site.urls)),
)
handler500 = 'django.views.defaults.server_error' | bsd-3-clause |
wiseman/virtual-radar-server | Test/Test.VirtualRadar.Library/Listener/ListenerTests.cs | 82917 | // Copyright © 2012 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software 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 author nor the names of the program's 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 THE AUTHORS OF THE SOFTWARE 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using InterfaceFactory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Test.Framework;
using VirtualRadar.Interface;
using VirtualRadar.Interface.BaseStation;
using VirtualRadar.Interface.Listener;
using VirtualRadar.Interface.ModeS;
using VirtualRadar.Interface.Adsb;
namespace Test.VirtualRadar.Library.Listener
{
[TestClass]
public class ListenerTests
{
#region Private Enum - TranslatorType
/// <summary>
/// An enumeration of the different translator types involved in each of the ExtractedBytesFormat decoding.
/// </summary>
enum TranslatorType
{
// Port30003 format translators
Port30003,
// ModeS format translators
ModeS,
Adsb,
Raw,
}
#endregion
#region TestContext, Fields, TestInitialise, TestCleanup
public TestContext TestContext { get; set; }
private IClassFactory _OriginalClassFactory;
private IListener _Listener;
private MockListenerProvider _Provider;
private MockMessageBytesExtractor _BytesExtractor;
private Mock<IRuntimeEnvironment> _RuntimeEnvironment;
private Mock<IModeSParity> _ModeSParity;
private EventRecorder<EventArgs<Exception>> _ExceptionCaughtEvent;
private EventRecorder<EventArgs> _ConnectionStateChangedEvent;
private EventRecorder<ModeSMessageEventArgs> _ModeSMessageReceivedEvent;
private EventRecorder<BaseStationMessageEventArgs> _Port30003MessageReceivedEvent;
private EventRecorder<EventArgs> _SourceChangedEvent;
private Mock<IBaseStationMessageTranslator> _Port30003Translator;
private Mock<IModeSTranslator> _ModeSTranslator;
private Mock<IAdsbTranslator> _AdsbTranslator;
private Mock<IRawMessageTranslator> _RawMessageTranslator;
private ModeSMessage _ModeSMessage;
private AdsbMessage _AdsbMessage;
private BaseStationMessage _Port30003Message;
private IStatistics _Statistics;
[TestInitialize]
public void TestInitialise()
{
_Statistics = Factory.Singleton.Resolve<IStatistics>().Singleton;
_Statistics.Initialise();
_Statistics.ResetConnectionStatistics();
_Statistics.ResetMessageCounters();
_OriginalClassFactory = Factory.TakeSnapshot();
_RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();
_RuntimeEnvironment.Setup(r => r.IsTest).Returns(true);
_Port30003Translator = TestUtilities.CreateMockImplementation<IBaseStationMessageTranslator>();
_ModeSTranslator = TestUtilities.CreateMockImplementation<IModeSTranslator>();
_AdsbTranslator = TestUtilities.CreateMockImplementation<IAdsbTranslator>();
_RawMessageTranslator = new Mock<IRawMessageTranslator>(MockBehavior.Default) { DefaultValue = DefaultValue.Mock };
_ModeSParity = TestUtilities.CreateMockImplementation<IModeSParity>();
_ModeSMessage = new ModeSMessage();
_AdsbMessage = new AdsbMessage(_ModeSMessage);
_Port30003Message = new BaseStationMessage();
_Port30003Translator.Setup(r => r.Translate(It.IsAny<string>())).Returns(_Port30003Message);
_AdsbTranslator.Setup(r => r.Translate(It.IsAny<ModeSMessage>())).Returns(_AdsbMessage);
_ModeSTranslator.Setup(r => r.Translate(It.IsAny<byte[]>())).Returns(_ModeSMessage);
_ModeSTranslator.Setup(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>())).Returns(_ModeSMessage);
_RawMessageTranslator.Setup(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>())).Returns(_Port30003Message);
_Listener = Factory.Singleton.Resolve<IListener>();
_Provider = new MockListenerProvider();
_BytesExtractor = new MockMessageBytesExtractor();
_ExceptionCaughtEvent = new EventRecorder<EventArgs<Exception>>();
_ConnectionStateChangedEvent = new EventRecorder<EventArgs>();
_ModeSMessageReceivedEvent = new EventRecorder<ModeSMessageEventArgs>();
_Port30003MessageReceivedEvent = new EventRecorder<BaseStationMessageEventArgs>();
_SourceChangedEvent = new EventRecorder<EventArgs>();
_Listener.ConnectionStateChanged += _ConnectionStateChangedEvent.Handler;
_Listener.ExceptionCaught += _ExceptionCaughtEvent.Handler;
_Listener.ModeSMessageReceived += _ModeSMessageReceivedEvent.Handler;
_Listener.Port30003MessageReceived += _Port30003MessageReceivedEvent.Handler;
_Listener.SourceChanged += _SourceChangedEvent.Handler;
_ExceptionCaughtEvent.EventRaised += DefaultExceptionCaughtHandler;
}
[TestCleanup]
public void TestCleanup()
{
Factory.RestoreSnapshot(_OriginalClassFactory);
_Listener.Dispose();
}
#endregion
#region ChangeSourceAndConnect
private void ChangeSourceAndConnect(bool reconnect = false, Mock<IListenerProvider> provider = null, Mock<IMessageBytesExtractor> bytesExtractor = null, Mock<IRawMessageTranslator> translator = null, bool connectAutoReconnect = false)
{
_Listener.ChangeSource(provider == null ? _Provider.Object : provider.Object,
bytesExtractor == null ? _BytesExtractor.Object : bytesExtractor.Object,
translator == null ? _RawMessageTranslator.Object : translator.Object,
reconnect);
_Listener.Connect(connectAutoReconnect);
}
#endregion
#region DefaultExceptionCaughtHandler
/// <summary>
/// Default handler for exceptions raised on a background thread by the listener.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void DefaultExceptionCaughtHandler(object sender, EventArgs<Exception> args)
{
Assert.Fail("Exception caught and passed to ExceptionCaught: {0}", args.Value.ToString());
}
/// <summary>
/// Removes the default exception caught handler.
/// </summary>
public void RemoveDefaultExceptionCaughtHandler()
{
_ExceptionCaughtEvent.EventRaised -= DefaultExceptionCaughtHandler;
}
#endregion
#region DoForEveryFormatAndTranslator, MakeFormatTranslatorThrowException, MakeMessageReceivedHandlerThrowException
private void DoForEveryFormat(Action<ExtractedBytesFormat, string> action)
{
foreach(ExtractedBytesFormat format in Enum.GetValues(typeof(ExtractedBytesFormat))) {
TestCleanup();
TestInitialise();
action(format, String.Format("Format {0}", format));
}
}
private void DoForEveryFormatAndTranslator(Action<ExtractedBytesFormat, TranslatorType, string> action)
{
foreach(ExtractedBytesFormat format in Enum.GetValues(typeof(ExtractedBytesFormat))) {
TranslatorType[] translators;
switch(format) {
case ExtractedBytesFormat.Port30003: translators = new TranslatorType[] { TranslatorType.Port30003 }; break;
case ExtractedBytesFormat.ModeS: translators = new TranslatorType[] { TranslatorType.ModeS, TranslatorType.Adsb, TranslatorType.Raw }; break;
case ExtractedBytesFormat.None: continue;
default: throw new NotImplementedException();
}
foreach(var translatorType in translators) {
TestCleanup();
TestInitialise();
var failMessage = String.Format("Format {0}, Translator {1}", format, translatorType);
action(format, translatorType, failMessage);
}
}
}
private InvalidOperationException MakeFormatTranslatorThrowException(TranslatorType translatorType)
{
var exception = new InvalidOperationException();
switch(translatorType) {
case TranslatorType.Adsb: _AdsbTranslator.Setup(r => r.Translate(It.IsAny<ModeSMessage>())).Throws(exception); break;
case TranslatorType.ModeS: _ModeSTranslator.Setup(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>())).Throws(exception); break;
case TranslatorType.Port30003: _Port30003Translator.Setup(r => r.Translate(It.IsAny<string>())).Throws(exception); break;
case TranslatorType.Raw: _RawMessageTranslator.Setup(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>())).Throws(exception); break;
default:
throw new NotImplementedException();
}
return exception;
}
private InvalidOperationException MakeMessageReceivedHandlerThrowException(TranslatorType translatorType)
{
var exception = new InvalidOperationException();
switch(translatorType) {
case TranslatorType.Adsb:
case TranslatorType.ModeS: _ModeSMessageReceivedEvent.EventRaised += (s, a) => { throw exception; }; break;
case TranslatorType.Port30003:
case TranslatorType.Raw: _Port30003MessageReceivedEvent.EventRaised += (s, a) => { throw exception; }; break;
default:
throw new NotImplementedException();
}
return exception;
}
#endregion
#region Constructor
[TestMethod]
public void Listener_Constructor_Initialises_To_Known_State_And_Properties_Work()
{
TestUtilities.TestProperty(_Listener, r => r.IgnoreBadMessages, false);
Assert.AreEqual(null, _Listener.BytesExtractor);
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus);
Assert.AreEqual(null, _Listener.Provider);
Assert.AreEqual(null, _Listener.RawMessageTranslator);
Assert.AreEqual(0, _Listener.TotalMessages);
Assert.AreEqual(0, _Listener.TotalBadMessages);
}
#endregion
#region Dispose
[TestMethod]
public void Listener_Dispose_Calls_Provider_Close()
{
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
_Listener.Dispose();
_Provider.Verify(p => p.Close(), Times.Once());
}
[TestMethod]
public void Listener_Dispose_Disposes_Of_RawMessageTranslator()
{
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
_Listener.Dispose();
_RawMessageTranslator.Verify(r => r.Dispose(), Times.Once());
}
#endregion
#region ChangeSource
[TestMethod]
public void Listener_ChangeSource_Can_Change_Properties()
{
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
Assert.AreSame(_Provider.Object, _Listener.Provider);
Assert.AreSame(_Listener.BytesExtractor, _BytesExtractor.Object);
Assert.AreSame(_RawMessageTranslator.Object, _Listener.RawMessageTranslator);
}
[TestMethod]
public void Listener_ChangeSource_Raises_SourceChanged()
{
_SourceChangedEvent.EventRaised += (s, a) => {
Assert.AreSame(_Provider.Object, _Listener.Provider);
Assert.AreSame(_BytesExtractor.Object, _Listener.BytesExtractor);
Assert.AreSame(_RawMessageTranslator.Object, _Listener.RawMessageTranslator);
};
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
Assert.AreEqual(1, _SourceChangedEvent.CallCount);
Assert.AreSame(_Listener, _SourceChangedEvent.Sender);
Assert.AreNotEqual(null, _SourceChangedEvent.Args);
}
[TestMethod]
public void Listener_ChangeSource_Resets_TotalMessages_Counter()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003);
ChangeSourceAndConnect();
_Listener.ChangeSource(new MockListenerProvider().Object, new MockMessageBytesExtractor().Object, new Mock<IRawMessageTranslator>().Object, false);
Assert.AreEqual(0, _Listener.TotalMessages);
}
[TestMethod]
public void Listener_ChangeSource_Resets_TotalBadMessages_Counter()
{
_Listener.IgnoreBadMessages = false;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003);
MakeFormatTranslatorThrowException(TranslatorType.Port30003);
ChangeSourceAndConnect();
_Listener.ChangeSource(new MockListenerProvider().Object, new MockMessageBytesExtractor().Object, new Mock<IRawMessageTranslator>().Object, false);
Assert.AreEqual(0, _Listener.TotalBadMessages);
}
[TestMethod]
public void Listener_ChangeSource_Is_Not_Raised_If_Nothing_Changes()
{
var newProvider = new MockListenerProvider();
var newExtractor = new MockMessageBytesExtractor();
var newRawMessageTranslator = new Mock<IRawMessageTranslator>(MockBehavior.Default) { DefaultValue = DefaultValue.Mock };
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
Assert.AreEqual(1, _SourceChangedEvent.CallCount);
_Listener.ChangeSource(newProvider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
Assert.AreEqual(2, _SourceChangedEvent.CallCount);
_Listener.ChangeSource(newProvider.Object, newExtractor.Object, _RawMessageTranslator.Object, false);
Assert.AreEqual(3, _SourceChangedEvent.CallCount);
_Listener.ChangeSource(newProvider.Object, newExtractor.Object, newRawMessageTranslator.Object, false);
Assert.AreEqual(4, _SourceChangedEvent.CallCount);
_Listener.ChangeSource(newProvider.Object, newExtractor.Object, newRawMessageTranslator.Object, false);
Assert.AreEqual(4, _SourceChangedEvent.CallCount);
}
[TestMethod]
public void Listener_ChangeSource_AutoReconnect_Reconnects_If_Set()
{
var firstProvider = new MockListenerProvider();
var firstExtractor = new MockMessageBytesExtractor();
firstProvider.Setup(p => p.Close()).Callback(() => {
Assert.AreSame(firstProvider.Object, _Listener.Provider);
Assert.AreSame(firstExtractor.Object, _Listener.BytesExtractor);
});
firstProvider.ConfigureForConnect();
_Listener.ChangeSource(firstProvider.Object, firstExtractor.Object, _RawMessageTranslator.Object, false);
_Listener.Connect(false);
_Provider.ConfigureForConnect();
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, true);
firstProvider.Verify(p => p.Close(), Times.Once());
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_ChangeSource_AutoReconnect_Does_Not_Reconnect_If_Clear()
{
var firstProvider = new MockListenerProvider();
var firstExtractor = new MockMessageBytesExtractor();
firstProvider.ConfigureForConnect();
_Listener.ChangeSource(firstProvider.Object, firstExtractor.Object, _RawMessageTranslator.Object, false);
_Listener.Connect(false);
_Provider.ConfigureForConnect();
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
firstProvider.Verify(p => p.Close(), Times.Once());
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Never());
}
[TestMethod]
public void Listener_ChangeSource_Disconnects_Existing_Provider_Even_If_Not_Connected()
{
var firstProvider = new MockListenerProvider();
var firstExtractor = new MockMessageBytesExtractor();
firstProvider.ConfigureForConnect();
_Listener.ChangeSource(firstProvider.Object, firstExtractor.Object, _RawMessageTranslator.Object, false);
_Provider.ConfigureForConnect();
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
firstProvider.Verify(p => p.Close(), Times.Once());
}
[TestMethod]
public void Listener_ChangeSource_With_Reconnec_True_Connects_New_Provider_Even_If_Not_Originally_Connected()
{
var firstProvider = new MockListenerProvider();
var firstExtractor = new MockMessageBytesExtractor();
firstProvider.ConfigureForConnect();
_Listener.ChangeSource(firstProvider.Object, firstExtractor.Object, _RawMessageTranslator.Object, false);
_Provider.ConfigureForConnect();
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, true);
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_ChangeSource_Disposes_Of_Existing_RawMessageTranslator()
{
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
_RawMessageTranslator.Verify(r => r.Dispose(), Times.Never());
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, new Mock<IRawMessageTranslator>().Object, false);
_RawMessageTranslator.Verify(r => r.Dispose(), Times.Once());
}
[TestMethod]
public void Listener_ChangeSource_Does_Not_Dispose_Of_Existing_RawMessageTranslator_If_It_Has_Not_Changed()
{
_Listener.ChangeSource(_Provider.Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
_Listener.ChangeSource(new MockListenerProvider().Object, _BytesExtractor.Object, _RawMessageTranslator.Object, false);
_RawMessageTranslator.Verify(r => r.Dispose(), Times.Never());
}
#endregion
#region Connect - Basics
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void Listener_Connect_Without_AutoReconnect_Throws_If_ChangeSource_Never_Called()
{
_Listener.Connect(false);
}
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void Listener_Connect_With_AutoReconnect_Throws_If_ChangeSource_Never_Called()
{
_Listener.Connect(true);
}
[TestMethod]
public void Listener_Connect_Calls_BeginConnect()
{
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_Connect_Does_Not_Call_BeginConnect_After_Disposed()
{
_Listener.Dispose();
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Never());
}
[TestMethod]
public void Listener_Connect_Does_Not_Pass_A_Null_AsyncCallback_To_Provider()
{
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginConnect(null), Times.Never());
}
[TestMethod]
public void Listener_Connect_Calls_EndConnect_If_BeginConnect_Works()
{
var asyncResult = _Provider.ConfigureForConnect();
ChangeSourceAndConnect();
_Provider.Verify(p => p.EndConnect(asyncResult), Times.Once());
}
[TestMethod]
public void Listener_Connect_Does_Not_Call_EndConnect_If_BeginConnect_Never_Completes()
{
ChangeSourceAndConnect();
_Provider.Verify(p => p.EndConnect(It.IsAny<IAsyncResult>()), Times.Never());
}
[TestMethod]
public void Listener_Connect_Routes_All_Exceptions_From_BeginConnect_Through_ExceptionCaught()
{
// Connect could be called during a reconnect operation from a background thread so it can't let
// exceptions just bubble up.
var exception = new InvalidOperationException();
_Provider.Setup(p => p.BeginConnect(It.IsAny<AsyncCallback>())).Callback(() => { throw exception; });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount);
Assert.AreSame(_Listener, _ExceptionCaughtEvent.Sender);
Assert.AreSame(exception, _ExceptionCaughtEvent.Args.Value);
}
[TestMethod]
public void Listener_Connect_Disconnects_If_BeginConnect_Throws_Exception()
{
_Provider.Setup(p => p.BeginConnect(It.IsAny<AsyncCallback>())).Callback(() => { throw new InvalidOperationException(); });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
_Provider.Verify(p => p.Close(), Times.Once());
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus);
}
[TestMethod]
public void Listener_Connect_Routes_All_Exceptions_From_EndConnect_Through_ExceptionCaught()
{
_Provider.ConfigureForConnect();
var exception = new NotSupportedException();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Callback(() => { throw exception; });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount);
Assert.AreSame(_Listener, _ExceptionCaughtEvent.Sender);
Assert.AreSame(exception, _ExceptionCaughtEvent.Args.Value);
}
[TestMethod]
public void Listener_Connect_Disconnects_After_EndConnect_Picks_Up_General_Exception()
{
_Provider.ConfigureForConnect();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Callback(() => { throw new NotSupportedException(); });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
_Provider.Verify(p => p.Close(), Times.Once());
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus);
}
[TestMethod]
public void Listener_Connect_Ignores_Exceptions_From_EndConnect_About_The_Connection_Being_Disposed()
{
// These are just exception spam, we can safely ignore them
_Provider.ConfigureForConnect();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Callback(() => { throw new ObjectDisposedException("whatever"); });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
Assert.AreEqual(0, _ExceptionCaughtEvent.CallCount);
_Provider.Verify(p => p.Close(), Times.Never());
Assert.AreEqual(ConnectionStatus.Connecting, _Listener.ConnectionStatus);
}
[TestMethod]
public void Listener_Connect_Ignores_Exceptions_From_EndConnect_About_The_Connection_Being_Closed()
{
// These are just exception spam - unfortunately they use a fairly common exception class for these but we still need to ignore them
_Provider.ConfigureForConnect();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Callback(() => { throw new InvalidOperationException(); });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
Assert.AreEqual(0, _ExceptionCaughtEvent.CallCount);
_Provider.Verify(p => p.Close(), Times.Never());
Assert.AreEqual(ConnectionStatus.Connecting, _Listener.ConnectionStatus);
}
[TestMethod]
public void Listener_Connect_Sets_ConnectionStatus_To_Connecting_When_Calling_BeginConnect_With_AutoReconnect_False()
{
_ConnectionStateChangedEvent.EventRaised += (object sender, EventArgs args) => {
Assert.AreEqual(ConnectionStatus.Connecting, _Listener.ConnectionStatus);
};
ChangeSourceAndConnect(false, null, null, null, false);
Assert.AreEqual(1, _ConnectionStateChangedEvent.CallCount);
Assert.AreSame(_Listener, _ConnectionStateChangedEvent.Sender);
}
[TestMethod]
public void Listener_Connect_Sets_ConnectionStatus_To_Reconnecting_When_Calling_BeginConnect_With_AutoReconnect_True()
{
_ConnectionStateChangedEvent.EventRaised += (object sender, EventArgs args) => {
Assert.AreEqual(ConnectionStatus.Reconnecting, _Listener.ConnectionStatus);
};
ChangeSourceAndConnect(false, null, null, null, true);
Assert.AreEqual(1, _ConnectionStateChangedEvent.CallCount);
Assert.AreSame(_Listener, _ConnectionStateChangedEvent.Sender);
}
[TestMethod]
public void Listener_Connect_Sets_ConnectionStatus_To_Connected_When_BeginConnect_Calls_Back()
{
_Provider.ConfigureForConnect();
int connectionChangedCount = 0;
_ConnectionStateChangedEvent.EventRaised += (object sender, EventArgs args) => {
if(++connectionChangedCount == 2) {
Assert.AreEqual(ConnectionStatus.Connected, _Listener.ConnectionStatus);
}
};
ChangeSourceAndConnect();
Assert.AreEqual(2, _ConnectionStateChangedEvent.CallCount);
Assert.AreSame(_Listener, _ConnectionStateChangedEvent.Sender);
}
[TestMethod]
public void Listener_Connect_Sets_ConnectionTime_In_Statistics_When_BeginConnect_Calls_Back()
{
_Provider.ConfigureForConnect();
DateTime now = new DateTime(2012, 11, 10, 9, 8, 7, 6);
_Provider.Setup(r => r.UtcNow).Returns(now);
int connectionChangedCount = 0;
_ConnectionStateChangedEvent.EventRaised += (object sender, EventArgs args) => {
switch(++connectionChangedCount) {
case 1: Assert.IsNull(_Statistics.ConnectionTimeUtc); break;
case 2: Assert.AreEqual(now, _Statistics.ConnectionTimeUtc); break;
}
};
ChangeSourceAndConnect();
Assert.AreEqual(2, _ConnectionStateChangedEvent.CallCount);
Assert.AreSame(_Listener, _ConnectionStateChangedEvent.Sender);
}
[TestMethod]
public void Listener_Connect_Does_Not_Set_Connection_Status_If_EndConnect_Reported_It_Was_For_An_Old_Connection()
{
_Provider.ConfigureForConnect();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Returns(false);
ChangeSourceAndConnect();
Assert.AreEqual(1, _ConnectionStateChangedEvent.CallCount);
Assert.AreEqual(ConnectionStatus.Connecting, _Listener.ConnectionStatus);
}
[TestMethod]
public void Listener_Connect_Sets_ConnectionStatus_To_CannotConnect_If_EndConnect_Throws_SocketException()
{
_Provider.ConfigureForConnect();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Callback(() => { throw new SocketException(); } );
ChangeSourceAndConnect();
Assert.AreEqual(ConnectionStatus.CannotConnect, _Listener.ConnectionStatus);
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_Connect_Begins_Reading_Content_From_Connection_When_BeginConnect_Works()
{
_Provider.ConfigureForConnect();
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginRead(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_Connect_Does_Not_Read_Content_If_EndConnect_Reported_It_Was_For_An_Old_Connection()
{
_Provider.ConfigureForConnect();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Returns(false);
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginRead(It.IsAny<AsyncCallback>()), Times.Never());
}
[TestMethod]
public void Listener_Connect_Does_Not_Read_Content_If_EndConnect_Throws_Exception()
{
_Provider.ConfigureForConnect();
RemoveDefaultExceptionCaughtHandler();
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Callback(() => { throw new NotImplementedException(); });
ChangeSourceAndConnect();
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount);
_Provider.Verify(p => p.BeginRead(It.IsAny<AsyncCallback>()), Times.Never());
}
[TestMethod]
public void Listener_Connect_Catches_Exceptions_In_EndRead_Calls()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("XYZ\n");
RemoveDefaultExceptionCaughtHandler();
var exception = new NotImplementedException();
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw exception; });
ChangeSourceAndConnect();
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount);
Assert.AreSame(_Listener, _ExceptionCaughtEvent.Sender);
Assert.AreSame(exception, _ExceptionCaughtEvent.Args.Value);
}
[TestMethod]
public void Listener_Connect_Disconnects_After_Catching_A_General_Exception_In_EndRead()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("XYZ\n");
RemoveDefaultExceptionCaughtHandler();
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new NotImplementedException(); });
ChangeSourceAndConnect();
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus);
_Provider.Verify(p => p.Close(), Times.Once());
Assert.IsNull(_Statistics.ConnectionTimeUtc);
Assert.AreEqual(0, _Statistics.BytesReceived);
}
[TestMethod]
public void Listener_Connect_Does_Not_Start_New_Read_After_Catching_A_General_Exception_In_EndRead()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("XYZ\n");
RemoveDefaultExceptionCaughtHandler();
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new NotImplementedException(); });
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginRead(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_Connect_Ignores_ObjectDisposed_Exceptions_In_EndRead()
{
// These happen a lot, whenever the connection is disposed of on another thread. We need to ignore them.
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("XYZ\n");
RemoveDefaultExceptionCaughtHandler();
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new ObjectDisposedException("x"); });
ChangeSourceAndConnect();
Assert.AreEqual(0, _ExceptionCaughtEvent.CallCount);
}
[TestMethod]
public void Listener_Connect_Does_Not_Start_New_Read_After_Catching_An_Object_Disposed_Exception_In_EndRead()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("XYZ\n");
RemoveDefaultExceptionCaughtHandler();
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new ObjectDisposedException("x"); });
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginRead(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_Connect_Will_Attempt_A_Reconnect_If_EndRead_Reports_SocketException()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("ABC\nXYZ\n");
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new SocketException(); });
bool seenReconnectingConnectionStateEvent = false;
_ConnectionStateChangedEvent.EventRaised += (object sender, EventArgs args) => {
if(_Listener.ConnectionStatus == ConnectionStatus.Reconnecting) {
seenReconnectingConnectionStateEvent = true;
}
};
ChangeSourceAndConnect();
Assert.IsTrue(seenReconnectingConnectionStateEvent);
Assert.AreEqual(ConnectionStatus.Reconnecting, _Listener.ConnectionStatus);
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Exactly(2));
Assert.IsNull(_Statistics.ConnectionTimeUtc);
Assert.AreEqual(0, _Statistics.BytesReceived);
}
[TestMethod]
public void Listener_Connect_Will_Attempt_A_Reconnect_If_EndRead_Returns_Zero()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("ABC\nXYZ\n");
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Returns(0);
bool seenReconnectingConnectionStateEvent = false;
_ConnectionStateChangedEvent.EventRaised += (object sender, EventArgs args) => {
if(_Listener.ConnectionStatus == ConnectionStatus.Reconnecting) seenReconnectingConnectionStateEvent = true;
};
ChangeSourceAndConnect();
Assert.IsTrue(seenReconnectingConnectionStateEvent);
Assert.AreEqual(ConnectionStatus.Reconnecting, _Listener.ConnectionStatus);
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Exactly(2));
}
[TestMethod]
public void Listener_Connect_Will_Not_Attempt_To_Read_Blocks_From_Dropped_Connection()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("ABC\nXYZ\n");
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new SocketException(); });
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginRead(It.IsAny<AsyncCallback>()), Times.Once());
}
[TestMethod]
public void Listener_Connect_Will_Wait_At_Least_One_Second_Between_Each_Reconnect_Attempt()
{
var beginConnectTimes = new List<DateTime>();
_Provider.ConfigureForConnect(2, () => { beginConnectTimes.Add(DateTime.UtcNow); });
_Provider.ConfigureForReadStream("ABC\nXYZ\n");
int endConnectCallCount = 0;
_Provider.Setup(p => p.EndConnect(It.IsAny<IAsyncResult>())).Returns(true).Callback(() => {
switch(endConnectCallCount++) {
case 0: break; // first connect works, triggers read
case 1: throw new SocketException(); // second connect (1st attempt at reconnect) fails
}
});
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new SocketException(); });
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Exactly(3));
Assert.AreEqual(ConnectionStatus.Reconnecting, _Listener.ConnectionStatus);
var milliseconds = (beginConnectTimes[1] - beginConnectTimes[0]).TotalMilliseconds;
Assert.IsTrue(milliseconds >= 900, milliseconds.ToString());
milliseconds = (beginConnectTimes[2] - beginConnectTimes[1]).TotalMilliseconds;
Assert.IsTrue(milliseconds >= 900, milliseconds.ToString());
}
[TestMethod]
public void Listener_Connect_Will_Abandon_Reconnect_If_User_Manually_Connects_While_Pausing()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("ABC\nXYZ\n");
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new SocketException(); });
_Provider.Setup(p => p.Sleep(It.IsAny<int>())).Callback(() => { _Listener.Connect(false); });
ChangeSourceAndConnect();
_Provider.Verify(p => p.BeginConnect(It.IsAny<AsyncCallback>()), Times.Exactly(2));
Assert.AreEqual(ConnectionStatus.Connecting, _Listener.ConnectionStatus);
}
[TestMethod]
public void Listener_Connect_Will_Pass_Exceptions_From_BeginConnect_During_Reconnect_To_ExceptionCaught()
{
int connectCount = 0;
var exception = new InvalidOperationException();
_Provider.ConfigureForConnect(2, () => { if(++connectCount == 2) throw exception; });
_Provider.ConfigureForReadStream("ABC\nXYZ\n");
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new SocketException(); });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount);
Assert.AreSame(_Listener, _ExceptionCaughtEvent.Sender);
Assert.AreSame(exception, _ExceptionCaughtEvent.Args.Value);
}
[TestMethod]
public void Listener_Connect_Will_Disconnect_If_Reconnect_Throws_A_General_Exception()
{
int connectCount = 0;
_Provider.ConfigureForConnect(2, () => { if(++connectCount == 2) throw new InvalidOperationException(); });
_Provider.ConfigureForReadStream("ABC\nXYZ\n");
_Provider.Setup(p => p.EndRead(It.IsAny<IAsyncResult>())).Callback(() => { throw new SocketException(); });
RemoveDefaultExceptionCaughtHandler();
ChangeSourceAndConnect();
_Provider.Verify(p => p.Close(), Times.Once());
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus);
}
#endregion
#region Connect - General Message Processing
[TestMethod]
public void Listener_Connect_Raises_RawBytesReceived_When_Bytes_Are_Received()
{
var bytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream(bytes, 3);
var eventRecorder = new EventRecorder<EventArgs<byte[]>>();
_Listener.RawBytesReceived += eventRecorder.Handler;
ChangeSourceAndConnect();
Assert.AreEqual(1, eventRecorder.CallCount);
Assert.AreSame(_Listener, eventRecorder.Sender);
Assert.IsTrue(new byte[] { 0x01, 0x02, 0x03}.SequenceEqual(eventRecorder.Args.Value));
}
[TestMethod]
public void Listener_Connect_Updates_Statistics_When_Bytes_Are_Received()
{
var bytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream(new byte[] { 0x01, 0x02 }, int.MinValue, new List<IEnumerable<byte>>() { { new byte[] { 0x03, 0x04, 0x05 } } });
ChangeSourceAndConnect();
Assert.AreEqual(5, _Statistics.BytesReceived);
}
[TestMethod]
public void Listener_Connect_Raises_ModeSBytesReceived_When_BytesExtractor_Extracts_ModeS_Message()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
var extractedBytes = _BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }, 1, 7, false, false);
var eventRecorder = new EventRecorder<EventArgs<ExtractedBytes>>();
_Listener.ModeSBytesReceived += eventRecorder.Handler;
ChangeSourceAndConnect();
Assert.AreEqual(1, eventRecorder.CallCount);
Assert.AreSame(_Listener, eventRecorder.Sender);
Assert.AreEqual(extractedBytes, eventRecorder.Args.Value);
Assert.AreNotSame(extractedBytes, eventRecorder.Args.Value); // must be a clone, not the original - the original can be reused
}
[TestMethod]
public void Listener_Connect_Does_Not_Raise_ModeSBytesReceived_When_BytesExtractor_Extracts_Bad_Checksum_Message()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
var extractedBytes = _BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }, 1, 7, true, false);
var eventRecorder = new EventRecorder<EventArgs<ExtractedBytes>>();
_Listener.ModeSBytesReceived += eventRecorder.Handler;
ChangeSourceAndConnect();
Assert.AreEqual(0, eventRecorder.CallCount);
}
[TestMethod]
public void Listener_Connect_Does_Not_Raise_ModeSBytesReceived_When_BytesExtractor_Extracts_Port30003_Message()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
var extractedBytes = _BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 }, 1, 7, false, false);
var eventRecorder = new EventRecorder<EventArgs<ExtractedBytes>>();
_Listener.ModeSBytesReceived += eventRecorder.Handler;
ChangeSourceAndConnect();
Assert.AreEqual(0, eventRecorder.CallCount);
}
[TestMethod]
public void Listener_Connect_Passes_Bytes_Received_To_Extractor()
{
var bytes = new List<byte>();
for(var i = 0;i < 256;++i) {
bytes.Add((byte)i);
}
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream(bytes);
ChangeSourceAndConnect();
Assert.AreEqual(1, _BytesExtractor.SourceByteArrays.Count);
Assert.IsTrue(bytes.SequenceEqual(_BytesExtractor.SourceByteArrays[0]));
_BytesExtractor.Verify(r => r.ExtractMessageBytes(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once());
}
[TestMethod]
public void Listener_Connect_Passes_Count_Of_Bytes_Read_To_Message_Extractor()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream(new byte[] { 0xf0, 0xe8 }, 1);
ChangeSourceAndConnect();
Assert.AreEqual(1, _BytesExtractor.SourceByteArrays.Count);
Assert.AreEqual(1, _BytesExtractor.SourceByteArrays[0].Length);
Assert.AreEqual(0xf0, _BytesExtractor.SourceByteArrays[0][0]);
}
[TestMethod]
public void Listener_Connect_Passes_Every_Block_Of_Bytes_Read_To_Message_Extractor()
{
var bytes1 = new byte[] { 0x01, 0xf0 };
var bytes2 = new byte[] { 0xef, 0x02 };
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream(bytes1, int.MinValue, new List<IEnumerable<byte>>() { bytes2 });
ChangeSourceAndConnect();
Assert.AreEqual(2, _BytesExtractor.SourceByteArrays.Count);
Assert.IsTrue(bytes1.SequenceEqual(_BytesExtractor.SourceByteArrays[0]));
Assert.IsTrue(bytes2.SequenceEqual(_BytesExtractor.SourceByteArrays[1]));
}
#endregion
#region Connect - Port30003 Message Processing
[TestMethod]
public void Listener_Connect_Passes_Port30003_Messages_To_Port30003_Message_Translator()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "ABC123");
ChangeSourceAndConnect();
_Port30003Translator.Verify(r => r.Translate("ABC123"), Times.Once());
_ModeSTranslator.Verify(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>()), Times.Never());
_AdsbTranslator.Verify(r => r.Translate(It.IsAny<ModeSMessage>()), Times.Never());
_RawMessageTranslator.Verify(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>()), Times.Never());
}
[TestMethod]
public void Listener_Connect_Honours_Offset_And_Length_When_Translating_Extracted_Bytes_To_Port30003_Message_Strings_For_Translation()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "-ABC-", 1, 3, false, false);
ChangeSourceAndConnect();
_Port30003Translator.Verify(r => r.Translate("ABC"), Times.Once());
}
[TestMethod]
public void Listener_Connect_Ignores_Extracted_Parity_On_Port30003_Messages()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "ABC123", false, true);
ChangeSourceAndConnect();
_Port30003Translator.Verify(r => r.Translate("ABC123"), Times.Once());
}
[TestMethod]
public void Listener_Connect_Raises_Port30003MessageReceived_With_Message_From_Translator()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "A");
ChangeSourceAndConnect();
Assert.AreEqual(1, _Port30003MessageReceivedEvent.CallCount);
Assert.AreSame(_Listener, _Port30003MessageReceivedEvent.Sender);
Assert.AreSame(_Port30003Message, _Port30003MessageReceivedEvent.Args.Message);
Assert.AreEqual(0, _ModeSMessageReceivedEvent.CallCount);
}
[TestMethod]
public void Listener_Connect_Does_Not_Raise_Port30003MessageReceived_When_Translator_Returns_Null()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "A");
_Port30003Translator.Setup(r => r.Translate("A")).Returns((BaseStationMessage)null);
ChangeSourceAndConnect();
Assert.AreEqual(0, _Port30003MessageReceivedEvent.CallCount);
Assert.AreEqual(0, _ModeSMessageReceivedEvent.CallCount);
}
[TestMethod]
public void Listener_Connect_Raises_Port30003MessageReceived_For_Every_Extracted_Packet()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "A");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "B");
ChangeSourceAndConnect();
_Port30003Translator.Verify(r => r.Translate("A"), Times.Once());
_Port30003Translator.Verify(r => r.Translate("B"), Times.Once());
Assert.AreEqual(2, _Port30003MessageReceivedEvent.CallCount);
}
[TestMethod]
public void Listener_Connect_Increments_Total_Messages_When_Port30003_Message_Received()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "A");
ChangeSourceAndConnect();
Assert.AreEqual(1, _Listener.TotalMessages);
}
[TestMethod]
public void Listener_Connect_Updates_Statistics_When_Port30003_Message_Received()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "A");
ChangeSourceAndConnect();
Assert.AreEqual(1, _Statistics.BaseStationMessagesReceived);
}
[TestMethod]
public void Listener_Connect_Updates_Statistics_When_Bad_Port30003_Message_Received()
{
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "A");
var exception = MakeFormatTranslatorThrowException(TranslatorType.Port30003);
ChangeSourceAndConnect();
Assert.AreEqual(0, _Statistics.BaseStationMessagesReceived);
Assert.AreEqual(1, _Statistics.BaseStationBadFormatMessagesReceived);
}
[TestMethod]
public void Listener_Connect_Increments_Total_Messages_For_Every_Message_In_A_Received_Packet_Of_Port30003_Messages()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "A");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "B");
ChangeSourceAndConnect();
Assert.AreEqual(2, _Listener.TotalMessages);
}
[TestMethod]
public void Listener_Connect_Does_Not_Increment_TotalMessages_When_Port30003Translator_Returns_Null()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.Port30003, "B");
_Port30003Translator.Setup(r => r.Translate(It.IsAny<string>())).Returns((BaseStationMessage)null);
ChangeSourceAndConnect();
Assert.AreEqual(0, _Listener.TotalMessages);
}
#endregion
#region Connect - ModeS Message Processing
[TestMethod]
public void Listener_Connect_Passes_ModeS_Messages_To_ModeS_Message_Translators()
{
var extractedBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, extractedBytes, 1, 7, false, false);
byte[] bytesPassedToTranslator = null;
int offsetPassedToTranslator = 0;
_ModeSTranslator.Setup(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>()))
.Callback((byte[] bytes, int offset) => {
bytesPassedToTranslator = bytes;
offsetPassedToTranslator = offset;
})
.Returns(_ModeSMessage);
ChangeSourceAndConnect();
_Port30003Translator.Verify(r => r.Translate(It.IsAny<string>()), Times.Never());
_ModeSTranslator.Verify(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>()), Times.Once());
Assert.AreSame(extractedBytes, bytesPassedToTranslator);
Assert.AreEqual(1, offsetPassedToTranslator);
_AdsbTranslator.Verify(r => r.Translate(_ModeSMessage), Times.Once());
_RawMessageTranslator.Verify(r => r.Translate(utcNow, _ModeSMessage, _AdsbMessage), Times.Once());
}
[TestMethod]
public void Listener_Connect_Does_Not_Pass_ModeS_Messages_To_ModeS_Translator_If_Length_Is_Anything_Other_Than_7_Or_14()
{
for(var length = 0;length < 20;++length) {
TestCleanup();
TestInitialise();
var extractedBytes = new byte[length];
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, extractedBytes);
ChangeSourceAndConnect();
string failMessage = String.Format("For length of {0}", length);
if(length != 7 && length != 14) {
_Port30003Translator.Verify(r => r.Translate(It.IsAny<string>()), Times.Never(), failMessage);
_ModeSTranslator.Verify(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>()), Times.Never(), failMessage);
_AdsbTranslator.Verify(r => r.Translate(It.IsAny<ModeSMessage>()), Times.Never(), failMessage);
_RawMessageTranslator.Verify(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>()), Times.Never(), failMessage);
} else {
_Port30003Translator.Verify(r => r.Translate(It.IsAny<string>()), Times.Never(), failMessage);
_ModeSTranslator.Verify(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>()), Times.Once(), failMessage);
_AdsbTranslator.Verify(r => r.Translate(It.IsAny<ModeSMessage>()), Times.Once(), failMessage);
_RawMessageTranslator.Verify(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>()), Times.Once(), failMessage);
}
}
}
[TestMethod]
public void Listener_Connect_Strips_Parity_From_ModeSMessages_When_Indicated()
{
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
var bytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, bytes, 1, 7, false, true);
ChangeSourceAndConnect();
_ModeSParity.Verify(r => r.StripParity(bytes, 1, 7), Times.Once());
}
[TestMethod]
public void Listener_Connect_Does_Not_Strip_Parity_From_ModeSMessages_When_Indicated()
{
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
var bytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, bytes, 1, 7, false, false);
ChangeSourceAndConnect();
_ModeSParity.Verify(r => r.StripParity(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Never());
}
[TestMethod]
public void Listener_Connect_Updates_Statistics_If_ModeS_Message_Has_NonNull_PI()
{
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
var bytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
foreach(var piValue in new int?[] { null, 0, 99 }) {
TestCleanup();
TestInitialise();
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, bytes, 1, 7, false, true);
_ModeSMessage.ParityInterrogatorIdentifier = piValue;
ChangeSourceAndConnect();
long expected = piValue == null ? 0L : 1L;
Assert.AreEqual(expected, _Statistics.ModeSWithPIField);
}
}
[TestMethod]
public void Listener_Connect_Updates_Statistics_If_ModeS_Message_Has_NonZero_PI()
{
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
var bytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
foreach(var piValue in new int?[] { null, 0, 99 }) {
TestCleanup();
TestInitialise();
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, bytes, 1, 7, false, true);
_ModeSMessage.ParityInterrogatorIdentifier = piValue;
ChangeSourceAndConnect();
long expected = piValue == null || piValue == 0 ? 0L : 1L;
Assert.AreEqual(expected, _Statistics.ModeSWithBadParityPIField);
}
}
[TestMethod]
public void Listener_Connect_Updates_Statistics_If_ModeS_Message_Does_Not_Contain_Adsb_Payload()
{
var extractedBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
foreach(var hasAdsbPayload in new bool[] { true, false }) {
TestCleanup();
TestInitialise();
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, extractedBytes, 1, 7, false, false);
if(!hasAdsbPayload) _AdsbTranslator.Setup(r => r.Translate(It.IsAny<ModeSMessage>())).Returns((AdsbMessage)null);
ChangeSourceAndConnect();
Assert.AreEqual(hasAdsbPayload ? 0L : 1L, _Statistics.ModeSNotAdsbCount);
}
}
[TestMethod]
public void Listener_Connect_Raises_ModeSMessageReceived_When_ModeS_Message_Received()
{
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
ChangeSourceAndConnect();
Assert.AreEqual(1, _ModeSMessageReceivedEvent.CallCount);
Assert.AreSame(_Listener, _ModeSMessageReceivedEvent.Sender);
Assert.AreEqual(utcNow, _ModeSMessageReceivedEvent.Args.ReceivedUtc);
Assert.AreSame(_ModeSMessage, _ModeSMessageReceivedEvent.Args.ModeSMessage);
Assert.AreSame(_AdsbMessage, _ModeSMessageReceivedEvent.Args.AdsbMessage);
}
[TestMethod]
public void Listener_Connect_Raises_Port30003MessageReceived_With_Translated_ModeS_Message()
{
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
ChangeSourceAndConnect();
Assert.AreEqual(1, _Port30003MessageReceivedEvent.CallCount);
Assert.AreSame(_Listener, _Port30003MessageReceivedEvent.Sender);
Assert.AreSame(_Port30003Message, _Port30003MessageReceivedEvent.Args.Message);
}
[TestMethod]
public void Listener_Connect_Does_Not_Translate_Null_ModeS_Messages()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
_ModeSTranslator.Setup(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>())).Returns((ModeSMessage)null);
ChangeSourceAndConnect();
_ModeSTranslator.Verify(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>()), Times.Once());
_AdsbTranslator.Verify(r => r.Translate(It.IsAny<ModeSMessage>()), Times.Never());
_RawMessageTranslator.Verify(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>()), Times.Never());
Assert.AreEqual(0, _ModeSMessageReceivedEvent.CallCount);
Assert.AreEqual(0, _Port30003MessageReceivedEvent.CallCount);
}
[TestMethod]
public void Listener_Connect_Will_Translate_Null_Adsb_Messages()
{
var utcNow = new DateTime(2007, 8, 9, 10, 11, 12, 13);
_Provider.Setup(r => r.UtcNow).Returns(utcNow);
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
_AdsbTranslator.Setup(r => r.Translate(It.IsAny<ModeSMessage>())).Returns((AdsbMessage)null);
ChangeSourceAndConnect();
_ModeSTranslator.Verify(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>()), Times.Once());
_AdsbTranslator.Verify(r => r.Translate(It.IsAny<ModeSMessage>()), Times.Once());
_RawMessageTranslator.Verify(r => r.Translate(utcNow, _ModeSMessage, null), Times.Once());
Assert.AreEqual(1, _ModeSMessageReceivedEvent.CallCount);
Assert.AreEqual(utcNow, _ModeSMessageReceivedEvent.Args.ReceivedUtc);
Assert.AreSame(_ModeSMessage, _ModeSMessageReceivedEvent.Args.ModeSMessage);
Assert.IsNull(_ModeSMessageReceivedEvent.Args.AdsbMessage);
Assert.AreEqual(1, _Port30003MessageReceivedEvent.CallCount);
Assert.AreSame(_Listener, _Port30003MessageReceivedEvent.Sender);
Assert.AreSame(_Port30003Message, _Port30003MessageReceivedEvent.Args.Message);
}
[TestMethod]
public void Listener_Connect_Will_Not_Raise_Port30003MessageReceived_When_Raw_Translator_Returns_Null()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
_RawMessageTranslator.Setup(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>())).Returns((BaseStationMessage)null);
ChangeSourceAndConnect();
Assert.AreEqual(0, _Port30003MessageReceivedEvent.CallCount);
}
[TestMethod]
public void Listener_Connect_Increments_Total_Messages_When_ModeS_Message_Received()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
ChangeSourceAndConnect();
Assert.AreEqual(1, _Listener.TotalMessages);
}
[TestMethod]
public void Listener_Connect_Increments_Total_Messages_For_Every_Message_In_A_Received_Packet_Of_ModeS_Messages()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
ChangeSourceAndConnect();
Assert.AreEqual(2, _Listener.TotalMessages);
}
[TestMethod]
public void Listener_Connect_Does_Not_Increment_TotalMessages_When_ModeSTranslator_Returns_Null()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
_ModeSTranslator.Setup(r => r.Translate(It.IsAny<byte[]>(), It.IsAny<int>())).Returns((ModeSMessage)null);
ChangeSourceAndConnect();
Assert.AreEqual(0, _Listener.TotalMessages);
}
[TestMethod]
public void Listener_Connect_Increments_TotalMessages_When_AdsbTranslator_Returns_Null()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
_AdsbTranslator.Setup(r => r.Translate(It.IsAny<ModeSMessage>())).Returns((AdsbMessage)null);
ChangeSourceAndConnect();
Assert.AreEqual(1, _Listener.TotalMessages);
}
[TestMethod]
public void Listener_Connect_Increments_TotalMessages_When_RawTranslator_Returns_Null()
{
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(ExtractedBytesFormat.ModeS, 7);
_RawMessageTranslator.Setup(r => r.Translate(It.IsAny<DateTime>(), It.IsAny<ModeSMessage>(), It.IsAny<AdsbMessage>())).Returns((BaseStationMessage)null);
ChangeSourceAndConnect();
Assert.AreEqual(1, _Listener.TotalMessages);
}
#endregion
#region Connect - Unknown Message Processing
[TestMethod]
public void Listener_Connect_Throws_Exception_When_ExtractedBytes_Are_In_Unknown_Format()
{
DoForEveryFormat((format, failMessage) => {
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(format);
ChangeSourceAndConnect();
switch(format) {
case ExtractedBytesFormat.None:
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount, failMessage);
break;
case ExtractedBytesFormat.Port30003:
case ExtractedBytesFormat.ModeS:
Assert.AreEqual(0, _ExceptionCaughtEvent.CallCount, failMessage);
break;
default:
throw new NotImplementedException();
}
});
}
#endregion
#region Connect - Packet Checksum Handling
[TestMethod]
public void Listener_Connect_Does_Not_Increment_TotalMessages_When_BadChecksum_Packet_Received()
{
DoForEveryFormat((format, failMessage) => {
if(format != ExtractedBytesFormat.None) {
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(format, 7, true, false);
ChangeSourceAndConnect();
Assert.AreEqual(0, _Listener.TotalMessages, failMessage);
}
});
}
[TestMethod]
public void Listener_Connect_Updates_Statistics_When_BadChecksum_Packet_Received()
{
DoForEveryFormat((format, failMessage) => {
if(format != ExtractedBytesFormat.None) {
TestCleanup();
TestInitialise();
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(format, 7, true, false);
ChangeSourceAndConnect();
Assert.AreEqual(1L, _Statistics.FailedChecksumMessages);
}
});
}
[TestMethod]
public void Listener_Connect_Increments_BadMessages_When_BadChecksum_Packet_Received_Irrespective_Of_IgnoreBadMessages_Setting()
{
DoForEveryFormat((format, failMessagePrefix) => {
if(format != ExtractedBytesFormat.None) {
foreach(var ignoreBadMessages in new bool[] { true, false }) {
TestCleanup();
TestInitialise();
var failMessage = String.Format("{0} ignoreBadMessages {1}", failMessagePrefix, ignoreBadMessages);
RemoveDefaultExceptionCaughtHandler();
_Listener.IgnoreBadMessages = ignoreBadMessages;
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(format, 7, true, false);
ChangeSourceAndConnect();
Assert.AreEqual(1, _Listener.TotalBadMessages, failMessage);
}
}
});
}
[TestMethod]
public void Listener_Connect_Does_Not_Throw_Exception_When_BadChecksum_Packet_Received_Irrespective_Of_IgnoreBadMessages_Setting()
{
DoForEveryFormat((format, failMessagePrefix) => {
if(format != ExtractedBytesFormat.None) {
foreach(var ignoreBadMessages in new bool[] { true, false }) {
TestCleanup();
TestInitialise();
var failMessage = String.Format("{0} ignoreBadMessages {1}", failMessagePrefix, ignoreBadMessages);
RemoveDefaultExceptionCaughtHandler();
_Listener.IgnoreBadMessages = ignoreBadMessages;
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("a");
_BytesExtractor.AddExtractedBytes(format, 7, true, false);
ChangeSourceAndConnect();
Assert.AreEqual(0, _ExceptionCaughtEvent.CallCount, failMessage);
Assert.AreEqual(ConnectionStatus.Connected, _Listener.ConnectionStatus);
}
}
});
}
#endregion
#region Connect - Exception Handling
[TestMethod]
public void Listener_Connect_Raises_ExceptionCaught_If_Translator_Throws_Exception_When_IgnoreBadMessages_Is_False()
{
DoForEveryFormatAndTranslator((format, translatorType, failMessage) => {
_Listener.IgnoreBadMessages = false;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(format, 7);
var exception = MakeFormatTranslatorThrowException(translatorType);
ChangeSourceAndConnect();
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount, failMessage);
Assert.AreSame(_Listener, _ExceptionCaughtEvent.Sender, failMessage);
Assert.AreSame(exception, _ExceptionCaughtEvent.Args.Value, failMessage);
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus, failMessage);
});
}
[TestMethod]
public void Listener_Connect_Does_Not_Raise_ExceptionCaught_If_Translator_Throws_Exception_When_IgnoreBadMessages_Is_True()
{
DoForEveryFormatAndTranslator((format, translatorType, failMessage) => {
_Listener.IgnoreBadMessages = true;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(format, 7);
var exception = MakeFormatTranslatorThrowException(translatorType);
ChangeSourceAndConnect();
if(translatorType != TranslatorType.Raw) {
Assert.AreEqual(0, _ExceptionCaughtEvent.CallCount, failMessage);
Assert.AreEqual(ConnectionStatus.Connected, _Listener.ConnectionStatus, failMessage);
} else {
// If the Mode-S and ADS-B messages decoded correctly then any exception in the raw message translator
// is something I always want to know about - there should never be any combination of Mode-S and ADS-B
// message that makes it throw an exception. So in this case I want to still stop the listener and report
// the exception.
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount, failMessage);
Assert.AreSame(_Listener, _ExceptionCaughtEvent.Sender, failMessage);
Assert.AreSame(exception, _ExceptionCaughtEvent.Args.Value, failMessage);
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus, failMessage);
}
});
}
[TestMethod]
public void Listener_Connect_Raises_ExceptionCaught_If_MessageReceived_Event_Handler_Throws_Exception_When_IgnoreBadMessages_Is_True()
{
DoForEveryFormatAndTranslator((format, translatorType, failMessage) => {
_Listener.IgnoreBadMessages = true;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(format, 7);
var exception = MakeMessageReceivedHandlerThrowException(translatorType);
ChangeSourceAndConnect();
Assert.AreEqual(1, _ExceptionCaughtEvent.CallCount, failMessage);
Assert.AreSame(_Listener, _ExceptionCaughtEvent.Sender, failMessage);
Assert.AreSame(exception, _ExceptionCaughtEvent.Args.Value, failMessage);
Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus, failMessage);
});
}
[TestMethod]
public void Listener_Connect_Does_Not_Raise_MessageReceived_If_Translator_Throws_Exception_When_IgnoreBadMessages_Is_True()
{
DoForEveryFormatAndTranslator((format, translatorType, failMessage) => {
_Listener.IgnoreBadMessages = true;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(format, 7);
var exception = MakeFormatTranslatorThrowException(translatorType);
ChangeSourceAndConnect();
Assert.AreEqual(0, _Port30003MessageReceivedEvent.CallCount, failMessage);
Assert.AreEqual(translatorType == TranslatorType.Raw ? 1 : 0, _ModeSMessageReceivedEvent.CallCount, failMessage); // The Mode-S message will have been raised before the raw translator runs
});
}
[TestMethod]
public void Listener_Connect_Does_Not_Increment_TotalMessages_If_Translator_Throws_Exception()
{
DoForEveryFormatAndTranslator((format, translatorType, failMessage) => {
_Listener.IgnoreBadMessages = true;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(format, 7);
var exception = MakeFormatTranslatorThrowException(translatorType);
ChangeSourceAndConnect();
Assert.AreEqual(translatorType == TranslatorType.Raw ? 1 : 0, _Listener.TotalMessages, failMessage); // If the message gets as far as the raw translator then it was actually a good message...
});
}
[TestMethod]
public void Listener_Connect_Increments_TotalBadMessages_If_Translator_Throws_Exception_When_IgnoreBadMessage_Is_True()
{
DoForEveryFormatAndTranslator((format, translatorType, failMessage) => {
_Listener.IgnoreBadMessages = true;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(format, 7);
var exception = MakeFormatTranslatorThrowException(translatorType);
ChangeSourceAndConnect();
Assert.AreEqual(translatorType == TranslatorType.Raw ? 0 : 1, _Listener.TotalBadMessages, failMessage); // Exceptions in the raw translator are not an indication of a bad message, they're an indication of a bug
});
}
[TestMethod]
public void Listener_Connect_Increments_TotalBadMessages_If_Translator_Throws_Exception_When_IgnoreBadMessage_Is_False()
{
DoForEveryFormatAndTranslator((format, translatorType, failMessage) => {
_Listener.IgnoreBadMessages = false;
RemoveDefaultExceptionCaughtHandler();
_Provider.ConfigureForConnect();
_Provider.ConfigureForReadStream("A");
_BytesExtractor.AddExtractedBytes(format, 7);
var exception = MakeFormatTranslatorThrowException(translatorType);
ChangeSourceAndConnect();
Assert.AreEqual(translatorType == TranslatorType.Raw ? 0 : 1, _Listener.TotalBadMessages, failMessage); // Exceptions in the raw translator are not an indication of a bad message, they're an indication of a bug
});
}
#endregion
#region Disconnect
[TestMethod]
public void Listener_Disconnect_Closes_Provider()
{
_Provider.ConfigureForConnect();
ChangeSourceAndConnect();
_Listener.Disconnect();
_Provider.Verify(p => p.Close(), Times.Once());
}
[TestMethod]
public void Listener_Disconnect_Sets_Connection_Status()
{
_Provider.ConfigureForConnect();
int callCount = 0;
_ConnectionStateChangedEvent.EventRaised += (object sender, EventArgs args) => {
if(++callCount == 3) Assert.AreEqual(ConnectionStatus.Disconnected, _Listener.ConnectionStatus);
};
ChangeSourceAndConnect();
_Listener.Disconnect();
Assert.AreEqual(3, _ConnectionStateChangedEvent.CallCount);
}
#endregion
}
}
| bsd-3-clause |
newville/scikit-image | skimage/transform/__init__.py | 1652 | from ._hough_transform import (hough_ellipse, hough_line,
probabilistic_hough_line)
from .hough_transform import hough_circle, hough_line_peaks
from .radon_transform import radon, iradon, iradon_sart, iradon_workspace
from .finite_radon_transform import frt2, ifrt2
from .integral import integral_image, integrate
from ._geometric import (warp, warp_coords, estimate_transform,
matrix_transform,
SimilarityTransform, AffineTransform,
ProjectiveTransform, PolynomialTransform,
PiecewiseAffineTransform)
from ._warps import swirl, resize, rotate, rescale, downscale_local_mean
from .pyramids import (pyramid_reduce, pyramid_expand,
pyramid_gaussian, pyramid_laplacian)
__all__ = ['hough_circle',
'hough_ellipse',
'hough_line',
'probabilistic_hough_line',
'hough_line_peaks',
'radon',
'iradon',
'iradon_sart',
'frt2',
'ifrt2',
'integral_image',
'integrate',
'warp',
'warp_coords',
'estimate_transform',
'matrix_transform',
'SimilarityTransform',
'AffineTransform',
'ProjectiveTransform',
'PolynomialTransform',
'PiecewiseAffineTransform',
'swirl',
'resize',
'rotate',
'rescale',
'downscale_local_mean',
'pyramid_reduce',
'pyramid_expand',
'pyramid_gaussian',
'pyramid_laplacian']
| bsd-3-clause |
dongnan/LinkTool | src/linktool/log/Log.php | 3902 | <?php
/**
* LinkTool - A useful library for PHP
*
* @author Dong Nan <hidongnan@gmail.com>
* @copyright (c) Dong Nan http://idongnan.cn All rights reserved.
* @link https://github.com/dongnan/LinkTool
* @license BSD (http://opensource.org/licenses/BSD-3-Clause)
*/
namespace linktool\log;
/**
* Log
* 日志抽象类
* @author DongNan <dongyh@126.com>
* @date 2015-9-1
*/
abstract class Log {
/**
* 调试日志
*/
const DEBUG = 100;
/**
* 普通日志
*/
const INFO = 200;
/**
* 罕见的事件日志
*/
const NOTICE = 250;
/**
* 非错误的警示信息,例如过期方法的提醒或一些非错误的异常警告日志
*/
const WARNING = 300;
/**
* 错误日志
*/
const ERROR = 400;
/**
* 临界错误日志,系统负载过高或不同寻常的异常日志
*/
const CRITICAL = 500;
/**
* 需要立即处理的错误,例如网站瘫痪,数据库不可用等
*/
const ALERT = 550;
/**
* 突发事件,紧急情况日志
*/
const EMERGENCY = 600;
/**
* Logging levels from syslog protocol defined in RFC 5424
*
* @var array $levels 日志等级
*/
protected static $levels = [
100 => 'DEBUG',
200 => 'INFO',
250 => 'NOTICE',
300 => 'WARNING',
400 => 'ERROR',
500 => 'CRITICAL',
550 => 'ALERT',
600 => 'EMERGENCY',
];
/**
* 添加日志记录
* @access public
* @param int $level 日志等级
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function log($level, $message, $data = []);
/**
* 添加 debug 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function debug($message, $data = []);
/**
* 添加 info 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function info($message, $data = []);
/**
* 添加 notice 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function notice($message, $data = []);
/**
* 添加 warning 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function warning($message, $data = []);
/**
* 添加 error 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function error($message, $data = []);
/**
* 添加 critical 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function critical($message, $data = []);
/**
* 添加 alert 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function alert($message, $data = []);
/**
* 添加 emergency 日志
* @access public
* @param string $message 日志内容
* @param array $data 日志相关数组数据
* @return boolean
*/
abstract public function emergency($message, $data = []);
}
| bsd-3-clause |
charlesportwoodii/yii2-api | tests/unit/forms/ChangeEmailTest.php | 2778 | <?php
namespace tests\unit;
use common\forms\ChangeEmail;
use Faker\Factory;
use Yii;
class ChangeEmailTest extends \tests\codeception\Unit
{
use \Codeception\Specify;
public function testValidate()
{
$this->specify(
'test required fields', function () {
$form = new ChangeEmail;
expect('form does not validate', $form->validate())->false();
expect('form has errors', $form->hasErrors())->true();
expect('form has email error', $form->getErrors())->hasKey('email');
expect('form has password error', $form->getErrors())->hasKey('password');
}, [
'throws' => '\yii\base\Exception'
]
);
$this->specify(
'test a valid user is required', function () {
$faker = Factory::create();
$user = $this->register(true);
$form = new ChangeEmail;
$form->email = $faker->safeEmail;
$form->password = $this->getPassword();
$form->setUser($user);
expect('form validates', $form->validate())->true();
expect('form does not have errors', $form->hasErrors())->false();
}
);
$this->specify(
'tests that the email cannot be the users current email', function () {
$faker = Factory::create();
$user = $this->register(true);
$form = new ChangeEmail;
$form->email = $this->getUser()->email;
$form->password = $this->getPassword();
$form->setUser($user);
expect('form does not validate', $form->validate())->false();
expect('form has errors', $form->hasErrors())->true();
expect('form has email error', $form->getErrors())->hasKey('email');
}
);
}
public function testChange()
{
$this->specify(
'tests a user can actually change their email', function () {
$faker = Factory::create();
$user = $this->register(true);
$form = new ChangeEmail;
$form->email = $faker->safeEmail;
$form->password = $this->getPassword();
$form->setUser($user);
expect('form validates', $form->validate())->true();
expect('form does not have errors', $form->hasErrors())->false();
expect('form changes user object', $form->change())->true();
$this->getUser()->refresh();
expect('user email has been changed', $this->getUser()->email)->equals($form->email);
}
);
}
} | bsd-3-clause |
vIiRuS/Lagerregal | devicetypes/migrations/0001_initial.py | 1951 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devices', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Type',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(unique=True, max_length=200, verbose_name='Name')),
],
options={
'verbose_name': 'Type',
'verbose_name_plural': 'Types',
'permissions': (('read_type', 'Can read Type'),),
},
),
migrations.CreateModel(
name='TypeAttribute',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200)),
('regex', models.CharField(max_length=500, null=True, blank=True)),
('devicetype', models.ForeignKey(to='devicetypes.Type', on_delete=models.CASCADE)),
],
options={
'verbose_name': 'Type-attribute',
'verbose_name_plural': 'Type-attributes',
},
),
migrations.CreateModel(
name='TypeAttributeValue',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('value', models.CharField(max_length=400)),
('device', models.ForeignKey(to='devices.Device', on_delete=models.CASCADE)),
('typeattribute', models.ForeignKey(to='devicetypes.TypeAttribute', on_delete=models.CASCADE)),
],
options={
'verbose_name': 'Type-attribute value',
'verbose_name_plural': 'Type-attribute values',
},
),
]
| bsd-3-clause |
glenc/sp.py | src/sp/utils.py | 3239 | # Set up References
import clr
clr.AddReference("System")
clr.AddReference("Microsoft.SharePoint")
from System import Uri
from Microsoft.SharePoint import *
from Microsoft.SharePoint.Administration import SPWebApplication
# Enumeration
# These are simple enumeration methods for walking over various SharePoint
# objects and collections.
def enum(col, fn):
"""Enumerate a collection and call function fn for each item."""
for x in col:
fn(x)
def enum_sites(webapp, fn):
"""
Enumerate all site collections in the specified web application
and call the specified function with each site collection.
"""
# just in case we were passed a URL, get the web app
webapp = get_webapplication(webapp)
enum(webapp.Sites, fn)
def enum_webs(site, fn):
"""
Enumerate all webs beneath the site or web specified
and call te specified function with each web.
"""
# do different things based on the type of object provided
if type(site) is SPWeb:
enum(site.Webs, fn)
else:
site = get_site(site)
enum(site.RootWeb.Webs, fn)
def enum_all_webs(site, fn):
"""Enumerate all webs in a site collection"""
site = get_site(site)
enum(site.AllWebs, fn)
def enum_lists(web, fn):
"""Enumerate all lists in the web specified"""
web = get_web(web)
enum(web.Lists, fn)
# Get Object Helper Methods
# These methods take in some sort of object identifier (usually a URL)
# and return the appropriate object instance
def get_webapplication(url):
"""Gets a web application by its URL"""
if type(url) is SPWebApplication:
return url
return SPWebApplication.Lookup(Uri(url))
def get_site(url):
"""Gets a site collection by its URL"""
if type(url) is SPSite:
return url
return SPSite(url)
def get_web(url):
"""Gets a web by its URL"""
if type(url) is SPWeb:
return url
if type(url) is SPSite:
return url.RootWeb
site = get_site(url)
relative_url = url.replace(site.Url, "")
return site.OpenWeb(relative_url)
def get_list(web, list_name):
"""Gets a list within a web"""
web = get_web(web)
return first(web.Lists, lambda l: l.Title == list_name)
def try_get_site(url):
"""Tries to get a site collection but returns false if no site was found"""
try:
site = get_site(url)
return True, site
except:
return False, None
def try_get_web(url):
"""Tries to get a web but returns false if no web was found"""
web = get_web(url)
if web.Exists:
return True, web
else:
return False, None
def try_get_list(web, list_name):
"""Tries to get a list but returns false if no list was found"""
l = get_list(web, list_name)
return l != None, l
# Find Object Helper Methods
# These methods are used to find objects in collections
def list_exists(web, list_name):
"""Checks if a list exists"""
web = get_web(web)
match = first(web.Lists, lambda l: l.Title == list_name)
return match != None
# List/Collection helper methods
def collect(collection, fn):
"""Collects items where the function evalueates as true"""
results = []
for item in collection:
if fn(item):
results << item
return results
def first(collection, fn):
"""Finds the first item in the collection where the function evaluates as true"""
for item in collection:
if fn(item):
return item
return None
| bsd-3-clause |
vipaction/blog_yii2 | views/user/login.php | 1519 | <?php
/* @var $this yii\web\View */
/* @var $form, $register yii\bootstrap\ActiveForm */
/* @var $user app\models\User */
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\ActiveForm;
$this->title = 'Авторизация';
$this->params['breadcrumbs'][] = $this->title;
?>
<h1 class="text-center"><?= Html::encode($this->title) ?></h1>
<div class="container row">
<div class="col-lg-4 col-lg-offset-1 col-md-7 panel panel-default">
<div class="panel-heading">
<h4>Вход в аккаунт</h4>
</div>
<div class="panel-body">
<?php $form = ActiveForm::begin([
'id' => 'login_form',
'method' => 'post',
]);
echo $form->field($user, 'login')->textInput(['autofocus' => 'true']);
echo $form->field($user, 'password')->passwordInput();
echo Html::submitButton('Войти', ['class' => 'btn-block btn btn-primary']);
ActiveForm::end();
?>
</div>
</div>
<div class="col-lg-4 col-lg-offset-2 col-md-7 panel panel-default">
<div class="panel-body">
<?php
$register = ActiveForm::begin([
'method' => 'post',
'action' => 'register',
]);
echo Html::submitButton('Регистрация нового пользователя', ['class' => 'btn-block btn btn-primary']);
ActiveForm::end();
?>
</div>
</div>
</div>
| bsd-3-clause |
thkoch2001/libpostgresql-jdbc-java | org/postgresql/test/jdbc2/RefCursorTest.java | 4649 | /*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2011, PostgreSQL Global Development Group
*
*
*-------------------------------------------------------------------------
*/
package org.postgresql.test.jdbc2;
import org.postgresql.test.TestUtil;
import java.sql.*;
import junit.framework.TestCase;
/*
* RefCursor ResultSet tests.
* This test case is basically the same as the ResultSet test case.
*
* @author Nic Ferrier <nferrier@tapsellferrier.co.uk>
*/
public class RefCursorTest extends TestCase
{
private Connection con;
public RefCursorTest(String name)
{
super(name);
}
protected void setUp() throws Exception
{
// this is the same as the ResultSet setup.
con = TestUtil.openDB();
Statement stmt = con.createStatement();
TestUtil.createTable(con, "testrs", "id integer primary key");
stmt.executeUpdate("INSERT INTO testrs VALUES (1)");
stmt.executeUpdate("INSERT INTO testrs VALUES (2)");
stmt.executeUpdate("INSERT INTO testrs VALUES (3)");
stmt.executeUpdate("INSERT INTO testrs VALUES (4)");
stmt.executeUpdate("INSERT INTO testrs VALUES (6)");
stmt.executeUpdate("INSERT INTO testrs VALUES (9)");
// Create the functions.
stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getRefcursor () RETURNS refcursor AS '"
+ "declare v_resset refcursor; begin open v_resset for select id from testrs order by id; "
+ "return v_resset; end;' LANGUAGE 'plpgsql';");
stmt.execute ("CREATE OR REPLACE FUNCTION testspg__getEmptyRefcursor () RETURNS refcursor AS '"
+ "declare v_resset refcursor; begin open v_resset for select id from testrs where id < 1 order by id; "
+ "return v_resset; end;' LANGUAGE 'plpgsql';");
stmt.close();
con.setAutoCommit(false);
}
protected void tearDown() throws Exception
{
con.setAutoCommit(true);
Statement stmt = con.createStatement ();
stmt.execute ("drop FUNCTION testspg__getRefcursor ();");
stmt.execute ("drop FUNCTION testspg__getEmptyRefcursor ();");
TestUtil.dropTable(con, "testrs");
TestUtil.closeDB(con);
}
public void testResult() throws SQLException
{
CallableStatement call = con.prepareCall("{ ? = call testspg__getRefcursor () }");
call.registerOutParameter(1, Types.OTHER);
call.execute();
ResultSet rs = (ResultSet) call.getObject(1);
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 1);
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 2);
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 3);
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 4);
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 6);
assertTrue(rs.next());
assertTrue(rs.getInt(1) == 9);
assertTrue(!rs.next());
call.close();
}
public void testEmptyResult() throws SQLException
{
CallableStatement call = con.prepareCall("{ ? = call testspg__getEmptyRefcursor () }");
call.registerOutParameter(1, Types.OTHER);
call.execute();
ResultSet rs = (ResultSet) call.getObject(1);
assertTrue(!rs.next());
call.close();
}
public void testMetaData() throws SQLException
{
if (!TestUtil.haveMinimumServerVersion(con, "7.4"))
return;
CallableStatement call = con.prepareCall("{ ? = call testspg__getRefcursor () }");
call.registerOutParameter(1, Types.OTHER);
call.execute();
ResultSet rs = (ResultSet) call.getObject(1);
ResultSetMetaData rsmd = rs.getMetaData();
assertNotNull(rsmd);
assertEquals(1, rsmd.getColumnCount());
assertEquals(Types.INTEGER, rsmd.getColumnType(1));
assertEquals("int4", rsmd.getColumnTypeName(1));
rs.close();
call.close();
}
public void testResultType() throws SQLException
{
CallableStatement call = con.prepareCall("{ ? = call testspg__getRefcursor () }", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
call.registerOutParameter(1, Types.OTHER);
call.execute();
ResultSet rs = (ResultSet) call.getObject(1);
assertEquals(rs.getType(), ResultSet.TYPE_SCROLL_INSENSITIVE);
assertEquals(rs.getConcurrency(), ResultSet.CONCUR_READ_ONLY);
assertTrue(rs.last());
assertEquals(6, rs.getRow());
}
}
| bsd-3-clause |
rfloca/MITK | Core/Code/Controllers/mitkCoreActivator.cpp | 6877 | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkRenderingManager.h"
#include "mitkPlanePositionManager.h"
#include <mitkCoreDataNodeReader.h>
#include <mitkStandardFileLocations.h>
#include <mitkShaderRepository.h>
#include <mitkPropertyAliases.h>
#include <mitkPropertyDescriptions.h>
#include <mitkPropertyExtensions.h>
#include <mitkPropertyFilters.h>
#include <mitkIOUtil.h>
#include <usModuleInitialization.h>
#include <usModuleActivator.h>
#include <usModuleContext.h>
#include <usModuleSettings.h>
#include <usModuleEvent.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>
void HandleMicroServicesMessages(us::MsgType type, const char* msg)
{
switch (type)
{
case us::DebugMsg:
MITK_DEBUG << msg;
break;
case us::InfoMsg:
MITK_INFO << msg;
break;
case us::WarningMsg:
MITK_WARN << msg;
break;
case us::ErrorMsg:
MITK_ERROR << msg;
break;
}
}
void AddMitkAutoLoadPaths(const std::string& programPath)
{
us::ModuleSettings::AddAutoLoadPath(programPath);
#ifdef __APPLE__
// Walk up three directories since that is where the .dylib files are located
// for build trees.
std::string additionalPath = programPath;
bool addPath = true;
for(int i = 0; i < 3; ++i)
{
std::size_t index = additionalPath.find_last_of('/');
if (index != std::string::npos)
{
additionalPath = additionalPath.substr(0, index);
}
else
{
addPath = false;
break;
}
}
if (addPath)
{
us::ModuleSettings::AddAutoLoadPath(additionalPath);
}
#endif
}
/*
* This is the module activator for the "Mitk" module. It registers core services
* like ...
*/
class MitkCoreActivator : public us::ModuleActivator
{
public:
void Load(us::ModuleContext* context)
{
// Handle messages from CppMicroServices
us::installMsgHandler(HandleMicroServicesMessages);
// Add the current application directory to the auto-load paths.
// This is useful for third-party executables.
std::string programPath = mitk::IOUtil::GetProgramPath();
if (programPath.empty())
{
MITK_WARN << "Could not get the program path.";
}
else
{
AddMitkAutoLoadPaths(programPath);
}
//m_RenderingManager = mitk::RenderingManager::New();
//context->RegisterService<mitk::RenderingManager>(renderingManager.GetPointer());
m_PlanePositionManager.reset(new mitk::PlanePositionManagerService);
context->RegisterService<mitk::PlanePositionManagerService>(m_PlanePositionManager.get());
m_CoreDataNodeReader.reset(new mitk::CoreDataNodeReader);
context->RegisterService<mitk::IDataNodeReader>(m_CoreDataNodeReader.get());
m_ShaderRepository.reset(new mitk::ShaderRepository);
context->RegisterService<mitk::IShaderRepository>(m_ShaderRepository.get());
m_PropertyAliases.reset(new mitk::PropertyAliases);
context->RegisterService<mitk::IPropertyAliases>(m_PropertyAliases.get());
m_PropertyDescriptions.reset(new mitk::PropertyDescriptions);
context->RegisterService<mitk::IPropertyDescriptions>(m_PropertyDescriptions.get());
m_PropertyExtensions.reset(new mitk::PropertyExtensions);
context->RegisterService<mitk::IPropertyExtensions>(m_PropertyExtensions.get());
m_PropertyFilters.reset(new mitk::PropertyFilters);
context->RegisterService<mitk::IPropertyFilters>(m_PropertyFilters.get());
context->AddModuleListener(this, &MitkCoreActivator::HandleModuleEvent);
/*
There IS an option to exchange ALL vtkTexture instances against vtkNeverTranslucentTextureFactory.
This code is left here as a reminder, just in case we might need to do that some time.
vtkNeverTranslucentTextureFactory* textureFactory = vtkNeverTranslucentTextureFactory::New();
vtkObjectFactory::RegisterFactory( textureFactory );
textureFactory->Delete();
*/
}
void Unload(us::ModuleContext* )
{
// The mitk::ModuleContext* argument of the Unload() method
// will always be 0 for the Mitk library. It makes no sense
// to use it at this stage anyway, since all libraries which
// know about the module system have already been unloaded.
}
private:
void HandleModuleEvent(const us::ModuleEvent moduleEvent);
std::map<long, std::vector<int> > moduleIdToShaderIds;
//mitk::RenderingManager::Pointer m_RenderingManager;
std::auto_ptr<mitk::PlanePositionManagerService> m_PlanePositionManager;
std::auto_ptr<mitk::CoreDataNodeReader> m_CoreDataNodeReader;
std::auto_ptr<mitk::ShaderRepository> m_ShaderRepository;
std::auto_ptr<mitk::PropertyAliases> m_PropertyAliases;
std::auto_ptr<mitk::PropertyDescriptions> m_PropertyDescriptions;
std::auto_ptr<mitk::PropertyExtensions> m_PropertyExtensions;
std::auto_ptr<mitk::PropertyFilters> m_PropertyFilters;
};
void MitkCoreActivator::HandleModuleEvent(const us::ModuleEvent moduleEvent)
{
if (moduleEvent.GetType() == us::ModuleEvent::LOADED)
{
// search and load shader files
std::vector<us::ModuleResource> shaderResoruces =
moduleEvent.GetModule()->FindResources("Shaders", "*.xml", true);
for (std::vector<us::ModuleResource>::iterator i = shaderResoruces.begin();
i != shaderResoruces.end(); ++i)
{
if (*i)
{
us::ModuleResourceStream rs(*i);
int id = m_ShaderRepository->LoadShader(rs, i->GetBaseName());
if (id >= 0)
{
moduleIdToShaderIds[moduleEvent.GetModule()->GetModuleId()].push_back(id);
}
}
}
}
else if (moduleEvent.GetType() == us::ModuleEvent::UNLOADED)
{
std::map<long, std::vector<int> >::iterator shaderIdsIter =
moduleIdToShaderIds.find(moduleEvent.GetModule()->GetModuleId());
if (shaderIdsIter != moduleIdToShaderIds.end())
{
for (std::vector<int>::iterator idIter = shaderIdsIter->second.begin();
idIter != shaderIdsIter->second.end(); ++idIter)
{
m_ShaderRepository->UnloadShader(*idIter);
}
moduleIdToShaderIds.erase(shaderIdsIter);
}
}
}
US_EXPORT_MODULE_ACTIVATOR(Mitk, MitkCoreActivator)
// Call CppMicroservices initialization code at the end of the file.
// This especially ensures that VTK object factories have already
// been registered (VTK initialization code is injected by implicitly
// include VTK header files at the top of this file).
US_INITIALIZE_MODULE("Mitk", "Mitk")
| bsd-3-clause |
lsbardel/django-amazoncloud | amazoncloud/__init__.py | 321 | import os
import sys
VERSION = (0, 1, 'alpha-pre')
def get_version():
if len(VERSION) == 3:
try:
vi = int(VERSION[2])
v = '%s.%s.%s' % VERSION
except:
v = '%s.%s_%s' % VERSION
else:
v = '%s.%s' % VERSION[:2]
return v
__version__ = get_version() | bsd-3-clause |
antoinecarme/sklearn_explain | tests/issues/issue_07/issue_07_iris_with_categorical_order_2.py | 1524 | from sklearn import datasets
import numpy as np
import pandas as pd
import sklearn_explain.explainer as expl
ds = datasets.load_iris();
print(ds.__dict__)
C1 = np.random.randint(3, size=ds.data.shape[0]).T.reshape(-1,1)
C2 = np.random.randint(5, size=ds.data.shape[0]).T.reshape(-1,1)
C2= C2 * 5
print(C1.shape, C2.shape, ds.data.shape)
X = np.concatenate((C1, C2, ds.data) , axis=1)
print(C1.shape, C2.shape, ds.data.shape , X.shape)
print(X[0:5,:])
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
clf = Pipeline([
('feature_selection', SelectKBest(chi2, k=2)),
('classification', RandomForestClassifier(n_estimators=12, random_state = 1960))])
clf.fit(X , ds.target)
lExplainer = expl.cModelScoreExplainer(clf)
lExplainer.mSettings.mFeatureNames = ["C1" , "C2"] + ds.feature_names
lExplainer.mSettings.mCategoricalFeatureNames = ["C1" , "C2"]
lExplainer.mSettings.mScoreBins = 10
lExplainer.mSettings.mFeatureBins = 10
lExplainer.mSettings.mMaxReasons = 2
lExplainer.mSettings.mExplanationOrder = 2
# lExplainer.mSettings.mClasses = ds.target_names # ['setosa', 'versicolor', 'virginica']
# lExplainer.mSettings.mMainClass = 'versicolor'
lExplainer.fit(X)
df_rc = lExplainer.explain(X)
cols = [col for col in df_rc.columns if col.startswith("C")]
print(df_rc[cols].head())
cols = [col for col in df_rc.columns if col.startswith("detailed_")]
print(df_rc[cols].head())
| bsd-3-clause |
benkaraban/anima-games-engine | Sources/HOO/HOOServer/NetworkMessageHandler/CloseSessionHandler.cpp | 2066 | /*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* 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 copyright holder 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 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.
*/
#include "CloseSessionHandler.h"
namespace HOOServer
{
CloseSessionHandler::CloseSessionHandler(ISessionManager & sessionManager)
: _sessionManager(sessionManager)
{}
CloseSessionHandler::~CloseSessionHandler()
{}
void CloseSessionHandler::handleMessage(Network::EMessageType msgType, int32 idSession)
{
_sessionManager.closeSession(idSession);
}
}//namespace HOOServer | bsd-3-clause |
adamretter/j8fu | src/main/java/com/evolvedbinary/j8fu/function/Function4E.java | 24714 | /**
* Copyright © 2016, Evolved Binary Ltd. <tech@evolvedbinary.com>
* 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 <organization> 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 <COPYRIGHT HOLDER> 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 com.evolvedbinary.j8fu.function;
import com.evolvedbinary.j8fu.Either;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
import static com.evolvedbinary.j8fu.Either.Left;
import static com.evolvedbinary.j8fu.Either.Right;
/**
* Similar to {@link FunctionE} but
* permits four statically known Exceptions to be thrown
*
* @param <T> Function parameter type
* @param <R> Function return type
* @param <E1> Function throws exception type
* @param <E2> Function throws exception type
* @param <E3> Function throws exception type
* @param <E4> Function throws exception type
*
* @author <a href="mailto:adam@evolvedbinary.com">Adam Retter</a>
*/
@FunctionalInterface
public interface Function4E<T, R, E1 extends Throwable, E2 extends Throwable, E3 extends Throwable, E4 extends Throwable> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*
* @throws E1 An exception of type {@code E1}
* @throws E2 An exception of type {@code E2}
* @throws E3 An exception of type {@code E3}
* @throws E4 An exception of type {@code E4}
*/
R apply(final T t) throws E1, E2, E3, E4;
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function4E)
*/
default <V> Function4E<V, R, E1, E2, E3, E4> compose(final Function4E<? super V, ? extends T, ? extends E1, ? extends E2, ? extends E3, ? extends E4> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B> BiFunction4E<A, B, R, E1, E2, E3, E4> compose(final BiFunction4E<? super A, ? super B, ? extends T, ? extends E1, ? extends E2, ? extends E3, ? extends E4> before) {
Objects.requireNonNull(before);
return (a, b) -> apply(before.apply(a, b));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param <C> the type of input to the third argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B, C> TriFunction4E<A, B, C, R, E1, E2, E3, E4> compose(final TriFunction4E<? super A, ? super B, ? super C, ? extends T, ? extends E1, ? extends E2, ? extends E3, ? extends E4> before) {
Objects.requireNonNull(before);
return (a, b, c) -> apply(before.apply(a, b, c));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function3E)
*/
default <V> Function4E<V, R, E1, E2, E3, E4> compose(final Function3E<? super V, ? extends T, ? extends E1, ? extends E2, ? extends E3> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B> BiFunction4E<A, B, R, E1, E2, E3, E4> compose(final BiFunction3E<? super A, ? super B, ? extends T, ? extends E1, ? extends E2, ? extends E3> before) {
Objects.requireNonNull(before);
return (a, b) -> apply(before.apply(a, b));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param <C> the type of input to the third argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B, C> TriFunction4E<A, B, C, R, E1, E2, E3, E4> compose(final TriFunction3E<? super A, ? super B, ? super C, ? extends T, ? extends E1, ? extends E2, ? extends E3> before) {
Objects.requireNonNull(before);
return (a, b, c) -> apply(before.apply(a, b, c));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function2E)
*/
default <V> Function4E<V, R, E1, E2, E3, E4> compose(final Function2E<? super V, ? extends T, ? extends E1, ? extends E2> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B> BiFunction4E<A, B, R, E1, E2, E3, E4> compose(final BiFunction2E<? super A, ? super B, ? extends T, ? extends E1, ? extends E2> before) {
Objects.requireNonNull(before);
return (a, b) -> apply(before.apply(a, b));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param <C> the type of input to the third argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B, C> TriFunction4E<A, B, C, R, E1, E2, E3, E4> compose(final TriFunction2E<? super A, ? super B, ? super C, ? extends T, ? extends E1, ? extends E2> before) {
Objects.requireNonNull(before);
return (a, b, c) -> apply(before.apply(a, b, c));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(FunctionE)
*/
default <V> Function4E<V, R, E1, E2, E3, E4> compose(final FunctionE<? super V, ? extends T, ? extends E1> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B> BiFunction4E<A, B, R, E1, E2, E3, E4> compose(final BiFunctionE<? super A, ? super B, ? extends T, ? extends E1> before) {
Objects.requireNonNull(before);
return (a, b) -> apply(before.apply(a, b));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param <C> the type of input to the third argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B, C> TriFunction4E<A, B, C, R, E1, E2, E3, E4> compose(final TriFunctionE<? super A, ? super B, ? super C, ? extends T, ? extends E1> before) {
Objects.requireNonNull(before);
return (a, b, c) -> apply(before.apply(a, b, c));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function)
*/
default <V> Function4E<V, R, E1, E2, E3, E4> compose(final Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B> BiFunction4E<A, B, R, E1, E2, E3, E4> compose(final BiFunction<? super A, ? super B, ? extends T> before) {
Objects.requireNonNull(before);
return (a, b) -> apply(before.apply(a, b));
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <A> the type of input to the first argument of the {@code before}
* function, and to the composed function
* @param <B> the type of input to the second argument of the {@code before}
* function, and to the composed function
* @param <C> the type of input to the third argument of the {@code before}
* function, and to the composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*/
default <A, B, C> TriFunction4E<A, B, C, R, E1, E2, E3, E4> compose(final TriFunction<? super A, ? super B, ? super C, ? extends T> before) {
Objects.requireNonNull(before);
return (a, b, c) -> apply(before.apply(a, b, c));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <R2> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function4E)
*/
default <R2> Function4E<T, R2, E1, E2, E3, E4> andThen(final Function4E<? super R, ? extends R2, ? extends E1, ? extends E2, ? extends E3, ? extends E4> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <R2> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function3E)
*/
default <R2> Function4E<T, R2, E1, E2, E3, E4> andThen(final Function3E<? super R, ? extends R2, ? extends E1, ? extends E2, ? extends E3> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <R2> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function2E)
*/
default <R2> Function4E<T, R2, E1, E2, E3, E4> andThen(final Function2E<? super R, ? extends R2, ? extends E1, ? extends E2> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <R2> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(FunctionE)
*/
default <R2> Function4E<T, R2, E1, E2, E3, E4> andThen(final FunctionE<? super R, ? extends R2, ? extends E1> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <R2> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default <R2> Function4E<T, R2, E1, E2, E3, E4> andThen(final Function<? super R, ? extends R2> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* Returns a function that applies this function and returns the
* result as an {@link Either}.
*
* @return a function which will return either a throwable or the result {@code R}.
*/
default Function<T, Either<Throwable, R>> toFunction() {
return (T t) -> {
try {
return Right(apply(t));
} catch (final Throwable e) {
return Left(e);
}
};
}
/**
* Returns a function that always returns its input argument.
*
* @param <T> the type of the input and output objects to the function
* @param <E1> Function throws exception type
* @param <E2> Function throws exception type
* @param <E3> Function throws exception type
* @param <E4> Function throws exception type
* @return a function that always returns its input argument
*/
static <T, E1 extends Throwable, E2 extends Throwable, E3 extends Throwable, E4 extends Throwable> Function4E<T, T, E1, E2, E3, E4> identity() {
return t -> t;
}
}
| bsd-3-clause |
hiqdev/composer-extension-plugin | tests/_bootstrap.php | 344 | <?php
/*
* Composer plugin for pluggable extensions
*
* @link https://github.com/hiqdev/composer-extension-plugin
* @package composer-extension-plugin
* @license BSD-3-Clause
* @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
*/
error_reporting(E_ALL & ~E_NOTICE);
require_once __DIR__ . '/../vendor/autoload.php';
| bsd-3-clause |
coolms/locale | src/Options/ModuleOptions.php | 1691 | <?php
/**
* CoolMS2 Locale Module (http://www.coolms.com/)
*
* @link http://github.com/coolms/locale for the canonical source repository
* @copyright Copyright (c) 2006-2015 Altgraphic, ALC (http://www.altgraphic.com)
* @license http://www.coolms.com/license/new-bsd New BSD License
* @author Dmitry Popov <d.popov@altgraphic.com>
*/
namespace CmsLocale\Options;
use Zend\Stdlib\AbstractOptions;
class ModuleOptions extends AbstractOptions implements ModuleOptionsInterface
{
/**
* Turn off strict options mode
*
* @var bool
*/
protected $__strictMode__ = false;
/**
* @var string
*/
protected $default = 'en';
/**
* @var array|string
*/
protected $locales = ['en', 'en-US', 'en-GB'];
/**
* @var array|string
*/
protected $strategies = [];
/**
* {@inheritDoc}
*/
public function setDefault($locale)
{
$this->default = (string) $locale;
return $this;
}
/**
* {@inheritDoc}
*/
public function getDefault()
{
return $this->default;
}
/**
* {@inheritDoc}
*/
public function setLocales($locales)
{
$this->locales = (array) $locales;
return $this;
}
/**
* {@inheritDoc}
*/
public function getLocales()
{
return $this->locales;
}
/**
* {@inheritDoc}
*/
public function setStrategies($strategies)
{
$this->strategies = (array) $strategies;
return $this;
}
/**
* {@inheritDoc}
*/
public function getStrategies()
{
return $this->strategies;
}
}
| bsd-3-clause |
praekelt/jmbo-foundry | foundry/tasks.py | 3280 | import unicodedata
import jellyfish
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import EmailMultiAlternatives
from django.db import transaction
from django.template.loader import get_template_from_string
from django.template import Context
from django.contrib.sites.models import Site
from django.utils.html import strip_tags
from django.utils.encoding import force_unicode
from django.conf import settings
from celery import task
from celery.task.schedules import crontab
from celery.decorators import periodic_task
from preferences import preferences
from foundry.models import FoundryComment
TEMPLATE = '''
<html>
<body>
{% for comment in comments %}
<div>
{{ comment.comment }}
<br />
<a href="http://{{ site_domain}}{% url "admin-remove-comment" comment.id %}" target="_">Remove this comment</a>
|
<a href="http://{{ site_domain}}{% url "admin-allow-comment" comment.id %}" target="_">Allow this comment</a>
</div>
<br />
{% endfor %}
</body>
<html>
'''
@periodic_task(run_every=crontab(hour='*', minute='*/10', day_of_week='*'), ignore_result=True)
def report_naughty_words():
# As long as reporting is done often this won't turn into a memory hog.
def flag(text, threshold, words):
"""Very simple check for naughty words"""
# Normalize diacritic characters into ASCII since current version of
# jaro_distance cannot handle them.
normalized_text = unicodedata.normalize('NFKD', force_unicode(text)).encode('ascii', 'ignore')
total_weight = 0
lwords = normalized_text.lower().split()
for naughty in words:
for word in lwords:
score = jellyfish.jaro_distance(word, naughty)
if score > 0.7:
total_weight = total_weight + (score * words[naughty])
return total_weight > threshold
threshold = preferences.NaughtyWordPreferences.threshold
words = {}
# Load words and weights
entries = preferences.NaughtyWordPreferences.entries
for entry in entries.split('\n'):
try:
k, v = entry.split(',')
k = k.strip()
v = int(v.strip())
except:
continue
words[k] = v
flagged = []
comments = FoundryComment.objects.filter(moderated=False).order_by('id')
for comment in comments:
if comment.content_object:
if flag(comment.comment, threshold, words):
flagged.append(comment)
else:
# If a comment passes the test it is marked as moderated
comment.moderated = True
comment.save()
# Compose a mail
if flagged:
site = Site.objects.get(id=settings.SITE_ID)
template = get_template_from_string(TEMPLATE)
c = dict(comments=flagged, site_domain=site.domain)
content = template.render(Context(c))
msg = EmailMultiAlternatives(
"Naughty words report on %s" % site.name,
strip_tags(content),
settings.DEFAULT_FROM_EMAIL,
preferences.NaughtyWordPreferences.email_recipients.split()
)
msg.attach_alternative(content, 'text/html')
msg.send()
| bsd-3-clause |
petlyakss/newTimetable | module/timetable/views/lessons/creator_index.php | 499 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\module\timetable\models\Lessons */
$this->title = 'Оберіть наступні параметри:';
$this->params['breadcrumbs'][] = ['label' => 'Редактор розкладу', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="lessons-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_beginForm', [
'model' => $model
]) ?>
</div>
| bsd-3-clause |
manachyn/imshop | modules/search/src/models/TermsFacet.php | 1430 | <?php
namespace im\search\models;
use im\eav\models\Attribute;
use im\search\components\query\facet\TermsFacetInterface;
/**
* Terms facet model class.
*/
class TermsFacet extends Facet implements TermsFacetInterface
{
const TYPE = self::TYPE_TERMS;
/**
* @inheritdoc
*/
public function getValues()
{
$values = parent::getValues();
if (!$values && strncmp($this->attribute_name, 'eAttributes.', 12) === 0) {
$name = substr($this->attribute_name, 12);
$attribute = Attribute::findByNameAndEntityType($name, $this->entity_type);
if ($attribute->isValuesPredefined()) {
$values = $attribute->getValues();
if ($values) {
foreach ($values as $value) {
$values[] = new FacetTerm([
'facet' => $this,
'term' => $value->value,
'display' => $value->presentation
]);
}
$this->populateRelation('values', $values);
}
}
}
return $values;
}
/**
* @inheritdoc
*/
public function getValueInstance(array $config)
{
return new FacetTerm($config);
}
/**
* @inheritdoc
*/
public function getEditView()
{
return '_form';
}
}
| bsd-3-clause |
awebc/web_yi | yunsong/shop/migrations/m160919_090754_order.php | 1727 | <?php
use yii\db\Migration;
use yii\db\mysql\Schema;
class m160919_090754_order extends Migration
{
public function safeUp()
{
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
$this->createTable('{{%order}}', [
'order_id' => Schema::TYPE_PK,
'user_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'star_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'order_no' => Schema::TYPE_STRING . '(45) NOT NULL',
'total_price' => Schema::TYPE_DECIMAL . '(10, 2) NOT NULL',
'shipping_fee' => Schema::TYPE_DECIMAL . '(10, 2) NOT NULL',
'payment_fee' => Schema::TYPE_DECIMAL . '(10, 2) NOT NULL',
'address' => Schema::TYPE_STRING . '(255) NOT NULL',
'memo' => Schema::TYPE_STRING . '(255) NOT NULL',//备注
'create_at' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'update_at' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'status' => Schema::TYPE_SMALLINT . '(1) NOT NULL default 0',
],$tableOptions);
$this->createTable('{{%order_item}}', [
'order_item_id' => Schema::TYPE_PK,
'order_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'item_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'price' => Schema::TYPE_DECIMAL . '(10, 2) NOT NULL',
'qty' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'name' => Schema::TYPE_STRING . '(255) NOT NULL',
'picture' => Schema::TYPE_STRING . '(255) NOT NULL',
],$tableOptions);
}
public function safeDown()
{
$this->dropTable('{{%order}}');
$this->dropTable('{{%order_item}}');
}
}
| bsd-3-clause |
gintas/BattleSats | src/lt/miliauskas/battlesats/BattleView.java | 2123 | package lt.miliauskas.battlesats;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class BattleView extends SurfaceView implements Callback {
/** The thread that actually draws the animation */
private BattleThread thread;
public BattleView(Context context, AttributeSet attrs) {
super(context, attrs);
// register our interest in hearing about changes to our surface
SurfaceHolder holder = getHolder();
holder.addCallback(this);
thread = new BattleThread(holder, context);
setOnTouchListener(new TouchHandler(thread));
}
public BattleThread getThread() {
return thread;
}
/**
* Standard window-focus override. Notice focus lost so we can pause on
* focus lost. e.g. user switches to take a call.
*/
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if (!hasWindowFocus) thread.pause();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// start the thread here so that we don't busy-wait in run()
// waiting for the surface to be created
thread.setRunning(true);
thread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
thread.setSurfaceSize(width, height);
}
/*
* Callback invoked when the Surface has been destroyed and must no longer
* be touched. WARNING: after this method returns, the Surface/Canvas must
* never be touched again!
*/
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
}
| bsd-3-clause |
zcbenz/cefode-chromium | ui/gl/vsync_provider.cc | 3718 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gl/vsync_provider.h"
#include "base/time.h"
namespace gfx {
VSyncProvider::VSyncProvider() {
}
VSyncProvider::~VSyncProvider() {
}
SyncControlVSyncProvider::SyncControlVSyncProvider()
: VSyncProvider(),
last_media_stream_counter_(0) {
// On platforms where we can't get an accurate reading on the refresh
// rate we fall back to the assumption that we're displaying 60 frames
// per second.
last_good_interval_ = base::TimeDelta::FromSeconds(1) / 60;
}
SyncControlVSyncProvider::~SyncControlVSyncProvider() {
}
void SyncControlVSyncProvider::GetVSyncParameters(
const UpdateVSyncCallback& callback) {
#if defined(OS_LINUX)
base::TimeTicks timebase;
// The actual clock used for the system time returned by glXGetSyncValuesOML
// is unspecified. In practice, the clock used is likely to be either
// CLOCK_REALTIME or CLOCK_MONOTONIC, so we compare the returned time to the
// current time according to both clocks, and assume that the returned time
// was produced by the clock whose current time is closest to it, subject
// to the restriction that the returned time must not be in the future
// (since it is the time of a vblank that has already occurred).
int64 system_time;
int64 media_stream_counter;
int64 swap_buffer_counter;
if (!GetSyncValues(&system_time,
&media_stream_counter,
&swap_buffer_counter))
return;
struct timespec real_time;
struct timespec monotonic_time;
clock_gettime(CLOCK_REALTIME, &real_time);
clock_gettime(CLOCK_MONOTONIC, &monotonic_time);
int64 real_time_in_microseconds =
real_time.tv_sec * base::Time::kMicrosecondsPerSecond +
real_time.tv_nsec / base::Time::kNanosecondsPerMicrosecond;
int64 monotonic_time_in_microseconds =
monotonic_time.tv_sec * base::Time::kMicrosecondsPerSecond +
monotonic_time.tv_nsec / base::Time::kNanosecondsPerMicrosecond;
// We need the time according to CLOCK_MONOTONIC, so if we've been given
// a time from CLOCK_REALTIME, we need to convert.
bool time_conversion_needed =
llabs(system_time - real_time_in_microseconds) <
llabs(system_time - monotonic_time_in_microseconds);
if (time_conversion_needed)
system_time += monotonic_time_in_microseconds - real_time_in_microseconds;
// Return if |system_time| is more than 1 frames in the future.
int64 interval_in_microseconds = last_good_interval_.InMicroseconds();
if (system_time > monotonic_time_in_microseconds + interval_in_microseconds)
return;
// If |system_time| is slightly in the future, adjust it to the previous
// frame and use the last frame counter to prevent issues in the callback.
if (system_time > monotonic_time_in_microseconds) {
system_time -= interval_in_microseconds;
media_stream_counter--;
}
timebase = base::TimeTicks::FromInternalValue(system_time);
int32 numerator, denominator;
if (GetMscRate(&numerator, &denominator)) {
last_good_interval_ =
base::TimeDelta::FromSeconds(denominator) / numerator;
} else if (!last_timebase_.is_null()) {
base::TimeDelta timebase_diff = timebase - last_timebase_;
uint64 counter_diff = media_stream_counter -
last_media_stream_counter_;
if (counter_diff > 0 && timebase > last_timebase_)
last_good_interval_ = timebase_diff / counter_diff;
}
last_timebase_ = timebase;
last_media_stream_counter_ = media_stream_counter;
callback.Run(timebase, last_good_interval_);
#endif // defined(OS_LINUX)
}
} // namespace gfx
| bsd-3-clause |
karthiksekarnz/educulas | tests/Zend/Feed/Entry/RssTest.php | 2473 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Feed
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: RssTest.php 24594 2012-01-05 21:27:01Z matthew $
*/
/**
* @see Zend_Feed
*/
require_once 'Zend/Feed.php';
/**
* @category Zend
* @package Zend_Feed
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Feed
*/
class Zend_Feed_Entry_RssTest extends PHPUnit_Framework_TestCase
{
public function testContentEncodedSupport()
{
$feed = Zend_Feed::importFile(dirname(__FILE__) . '/../_files/TestFeedEntryRssContentEncoded.xml');
$this->assertType('Zend_Feed_Rss', $feed);
$item = $feed->current();
$this->assertType('Zend_Feed_Entry_Rss', $item);
$this->assertTrue(isset($item->content));
$this->assertContains(
'http://framework.zend.com/fisheye/changelog/Zend_Framework/?cs=7757',
$item->content->__toString()
);
$this->assertContains(
'http://framework.zend.com/fisheye/changelog/Zend_Framework/?cs=7757',
$item->content()
);
$item->content = 'foo';
$this->assertEquals('foo', $item->content->__toString());
}
public function testContentEncodedNullIfEmpty()
{
$feed = Zend_Feed::importFile(dirname(__FILE__) . '/../_files/TestFeedEntryRssContentEncoded.xml');
$this->assertType('Zend_Feed_Rss', $feed);
$feed->next();
$item = $feed->current();
$this->assertType('Zend_Feed_Entry_Rss', $item);
$this->assertFalse(isset($item->content));
$this->assertNull($item->content());
// $this->assertNull($item->content); // always return DOMElement Object
}
}
| bsd-3-clause |
bennybp/BPPrint | bpprint/Format.cpp | 4448 | #include <cstring>
#include "bpprint/Format.hpp"
namespace bpprint {
namespace detail {
bool get_next_format_(FormatInfo & fi, const std::string & str)
{
///////////////////////////////////////////////
// PrintF format
//%[flags][width][.precision][length]spec
// flags: -+#0 or space
// width: number
//precision: number
// length: characters
// spec: letter
///////////////////////////////////////////////
// WARNING - str may be a reference to fi.suffix
// Also remember - prefix will contain what to print out
// if this function returns false
const size_t len = str.length();
// doesn't actually release the memory (I don't think)
fi.prefix.clear();
fi.format.clear();
// If there is no string...
if(len == 0)
return false;
// Find a % not followed by another %, copying
// into prefix as we go.
// We need to replace %% with %
size_t idx;
for(idx = 0; idx < len; ++idx)
{
if(str[idx] == '%')
{
// we know len > 0 (already checked), so subtracting 1 is safe
if(str[idx] == '%' && idx < (len-1) && str[idx+1] == '%')
{
fi.prefix += '%';
idx++; // skip the second %
}
else
break; // We found a format spec!
}
else
fi.prefix += str[idx]; // copy to the prefix member
}
// Did we copy the whole string into the prefix? (ie, didn't find a spec)
// If so, we are done.
if(idx >= len)
return false;
// So we found a format spec. Decompose it
// into its various parts
size_t fmt_begin = idx;
size_t flag_begin = fmt_begin+1;
// first, the flag characters
const char * validflags = "+- #0";
size_t width_begin = flag_begin;
while(width_begin < len && strchr(validflags, str[width_begin]) != nullptr)
width_begin++;
// now the width
size_t prec_begin = width_begin;
while(prec_begin < len && isdigit(str[prec_begin]))
prec_begin++;
// precision, including period
size_t length_begin = prec_begin;
if(length_begin < len && str[length_begin] == '.')
{
length_begin++;
while(length_begin < len && isdigit(str[length_begin]))
length_begin++;
}
// length
size_t spec_begin = length_begin;
const char * validlengthchars = "hljztL";
while(spec_begin < len && strchr(validlengthchars, str[spec_begin]) != nullptr)
spec_begin++;
// specifier
size_t end = spec_begin;
const char * validspec = "diuoxXfFeEgGaAcsp?"; // n not supported, %% handled elsewhere
if(end < len && strchr(validspec, str[end]) != nullptr)
end++;
// check some things
// Specifier must be one character
if(end-spec_begin != 1)
throw std::runtime_error("Zero characters for type specifier");
// Length must be 0, 1, or 2 characters
size_t length_len = spec_begin-length_begin;
if(length_len > 2)
throw std::runtime_error("Format length specification must be 0, 1, or 2 characters");
// now we have the format
fi.format = str.substr(fmt_begin, length_begin-fmt_begin);
// length
memset(fi.length, 0, 3*sizeof(char));
memcpy(fi.length, str.c_str()+length_begin, length_len);
// length can only be certain combinations
const char * validlengths[8] = { "hh", "h", "l", "ll", "j", "z", "t", "L" };
bool found = false;
for(int i = 0; i < 8; i++)
{
if(strcmp(validlengths[i], fi.length))
found = true;
}
if(!found)
throw std::runtime_error("Invalid length specifier");
// spec
fi.spec = str[spec_begin];
// suffix last, since it may be aliased
fi.suffix = str.substr(end);
return true;
}
// This is an overload for terminating the variadic template
void format_(std::ostream & os, FormatInfo & fi, const std::string & str)
{
// If get_next_format_ returns true, we have a format spec, but
// we aren't given something to put there
//
// If get_next_format_ returns false, fi.prefix contains the
// string with appropriate substitutions for %%, etc
if(get_next_format_(fi, str))
throw std::runtime_error("Not enough arguments given to format string");
else
os << fi.prefix;
}
} // close namespace detail
} // close namespace bpprint
| bsd-3-clause |
juniops/nutrirbox | backend/views/sign-in/profile.php | 3350 | <?php
use common\models\UserProfile;
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\models\UserProfile */
/* @var $form yii\bootstrap\ActiveForm */
$this->title = Yii::t('backend', 'Edit profile')
?>
<div class="user-profile-form">
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-lg-6">
<div class="box box-primary">
<div class="box-header with-border">
<i class="fa fa-user"></i>
<h3 class="box-title">Informações</h3>
<div class="box-body">
<div class="row">
<div class="col-lg-4">
<?php echo $form->field($model, 'picture')->widget(\trntv\filekit\widget\Upload::classname(), [
'url' => ['avatar-upload']
]) ?>
</div>
<div class="col-lg-8">
<?php echo $form->field($model, 'firstname')->textInput(['maxlength' => 255]) ?>
<?php echo $form->field($model, 'middlename')->textInput(['maxlength' => 255]) ?>
<?php echo $form->field($model, 'lastname')->textInput(['maxlength' => 255]) ?>
</div>
</div>
<?php echo $form->field($model, 'date_of_birth')->textInput(['class'=>'form-control data','start-date'=>'-30y']) ?>
<?php echo $form->field($model, 'gender')->dropDownlist([
UserProfile::GENDER_FEMALE => Yii::t('backend', 'Female'),
UserProfile::GENDER_MALE => Yii::t('backend', 'Male')
]) ?>
<?php echo $form->field($model, 'locale')->dropDownlist(Yii::$app->params['availableLocales']) ?>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="box box-primary">
<div class="box-header with-border">
<i class="fa fa-phone"></i>
<h3 class="box-title">Contato</h3>
<div class="box-body">
<?php echo $form->field($model, 'phone')->textInput(['maxlength' => true, 'class'=>'form-control telefone']) ?>
<?php echo $form->field($model, 'cell_phone')->textInput(['maxlength' => true, 'class'=>'form-control telefone']) ?>
<?php echo $form->field($model, 'cep')->textInput(['maxlength' => true, 'class'=>'form-control cep']) ?>
<?php echo $form->field($model, 'city')->textInput(['maxlength' => true]) ?>
<?php echo $form->field($model, 'neighborhood')->textInput(['maxlength' => true]) ?>
<?php echo $form->field($model, 'address')->textInput(['maxlength' => true]) ?>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<?php echo Html::submitButton(Yii::t('backend', 'Update'), ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| bsd-3-clause |
toidi/hadoop-yarn-api-python-client | yarn_api_client/application_master.py | 10172 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .base import BaseYarnAPI, get_logger
from .hadoop_conf import get_webproxy_endpoint
log = get_logger(__name__)
class ApplicationMaster(BaseYarnAPI):
"""
The MapReduce Application Master REST API's allow the user to get status
on the running MapReduce application master. Currently this is the
equivalent to a running MapReduce job. The information includes the jobs
the app master is running and all the job particulars like tasks,
counters, configuration, attempts, etc.
If `address` argument is `None` client will try to extract `address` and
`port` from Hadoop configuration files.
:param str service_endpoint: ApplicationMaster HTTP(S) address
:param int timeout: API connection timeout in seconds
:param AuthBase auth: Auth to use for requests
:param boolean verify: Either a boolean, in which case it controls whether
we verify the server's TLS certificate, or a string, in which case it must
be a path to a CA bundle to use. Defaults to ``True``
"""
def __init__(self, service_endpoint=None, timeout=30, auth=None, verify=True):
if not service_endpoint:
service_endpoint = get_webproxy_endpoint(timeout, auth, verify)
super(ApplicationMaster, self).__init__(service_endpoint, timeout, auth, verify)
def application_information(self, application_id):
"""
The MapReduce application master information resource provides overall
information about that mapreduce application master.
This includes application id, time it was started, user, name, etc.
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/info'.format(
appid=application_id)
return self.request(path)
def jobs(self, application_id):
"""
The jobs resource provides a list of the jobs running on this
application master.
:param str application_id: The application id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs'.format(
appid=application_id)
return self.request(path)
def job(self, application_id, job_id):
"""
A job resource contains information about a particular job that was
started by this application master. Certain fields are only accessible
if user has permissions - depends on acl settings.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_attempts(self, application_id, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent the job attempts.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/jobattempts'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_counters(self, application_id, job_id):
"""
With the job counters API, you can object a collection of resources
that represent all the counters for that job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/counters'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_conf(self, application_id, job_id):
"""
A job configuration resource contains information about the job
configuration for this job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/conf'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_tasks(self, application_id, job_id):
"""
With the tasks API, you can obtain a collection of resources that
represent all the tasks for a job.
:param str application_id: The application id
:param str job_id: The job id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks'.format(
appid=application_id, jobid=job_id)
return self.request(path)
def job_task(self, application_id, job_id, task_id):
"""
A Task resource contains information about a particular
task within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_counters(self, application_id, job_id, task_id):
"""
With the task counters API, you can object a collection of resources
that represent all the counters for that task.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempts(self, application_id, job_id, task_id):
"""
With the task attempts API, you can obtain a collection of resources
that represent a task attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts'.format(
appid=application_id, jobid=job_id, taskid=task_id)
return self.request(path)
def task_attempt(self, application_id, job_id, task_id, attempt_id):
"""
A Task Attempt resource contains information about a particular task
attempt within a job.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
def task_attempt_state(self, application_id, job_id, task_id, attempt_id):
"""
With the task attempt state API, you can query the state of a submitted
task attempt.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/state'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
def task_attempt_state_kill(self, application_id, job_id, task_id, attempt_id):
"""
Kill specific attempt using task attempt state API.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
data = {"state": "KILLED"}
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/state'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path, 'PUT', json=data)
def task_attempt_counters(self, application_id, job_id, task_id, attempt_id):
"""
With the task attempt counters API, you can object a collection
of resources that represent al the counters for that task attempt.
:param str application_id: The application id
:param str job_id: The job id
:param str task_id: The task id
:param str attempt_id: The attempt id
:returns: API response object with JSON data
:rtype: :py:class:`yarn_api_client.base.Response`
"""
path = '/proxy/{appid}/ws/v1/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters'.format(
appid=application_id, jobid=job_id, taskid=task_id,
attemptid=attempt_id)
return self.request(path)
| bsd-3-clause |
NCIP/stats-analysis | cacoretoolkit 3.1/src/gov/nih/nci/evs/domain/Silo.java | 1751 | /*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/stats-analysis/LICENSE.txt for details.
*/
package gov.nih.nci.evs.domain;
import java.util.*;
/**
* Silo is a repository of customized concept terminology data from a knowledgebase. There can be a
* single silo or multiple silos, each consisting of semantically related concepts and extracted
* character strings associated with those concepts.
*
*/
public class Silo
implements java.io.Serializable
{
private static final long serialVersionUID = 1234567890L;
/**
* The identifier of this Silo
*/
private int id;
/**
* Returns the id for this Silo
* @return - id
*/
public int getId(){
return id;
}
/**
* Sets the specified id for this Silo
* @param - id
*/
public void setId(int id){
this.id = id;
}
/**
* This is the name of this Silo
*/
private java.lang.String name;
/**
* Returns the name of this Silo
* @return - name
*/
public java.lang.String getName(){
return name;
}
/**
* Sets the specified name for this Silo
* @param - name
*/
public void setName( java.lang.String name){
this.name = name;
}
public boolean equals(Object obj){
boolean eq = false;
if(obj instanceof Silo) {
Silo c =(Silo)obj;
String thisKey = getName();
if(thisKey!= null && thisKey.equals(c.getName())) {
eq = true;
}
}
return eq;
}
public int hashCode(){
int h = 0;
if(getName() != null) {
h += getName().hashCode();
}
return h;
}
}
| bsd-3-clause |
kakada/dhis2 | dhis-api/src/main/java/org/hisp/dhis/schema/AuthorityType.java | 1779 | package org.hisp.dhis.schema;
/*
* Copyright (c) 2004-2015, University of Oslo
* 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 HISP project 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 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.
*/
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
public enum AuthorityType
{
CREATE,
CREATE_PUBLIC,
CREATE_PRIVATE,
EXTERNALIZE,
READ,
UPDATE,
DELETE
}
| bsd-3-clause |
dava/dava.engine | Programs/QuickEd/Classes/Modules/ModernPropertiesModule/Editors/ModernPropertyEditor.cpp | 8866 | #include "Modules/ModernPropertiesModule/Editors/ModernPropertyEditor.h"
#include "Model/ControlProperties/ValueProperty.h"
#include "Model/ControlProperties/RootProperty.h"
#include "Model/PackageHierarchy/ControlNode.h"
#include "Modules/DocumentsModule/DocumentData.h"
#include "QECommands/ChangePropertyValueCommand.h"
#include "QECommands/ChangeBindingCommand.h"
#include "QECommands/ChangePropertyForceOverrideCommand.h"
#include <TArc/Core/ContextAccessor.h>
#include <TArc/DataProcessing/DataContext.h>
#include <Base/Any.h>
#include <Engine/Engine.h>
#include <UI/UIControl.h>
#include <UI/UIControlSystem.h>
#include <UI/Styles/UIStyleSheetSystem.h>
#include <UI/Layouts/UILayoutSystem.h>
#include <UI/Layouts/UILayoutIsolationComponent.h>
#include <QHBoxLayout>
#include <QLabel>
#include <QAction>
#include <QLineEdit>
#include <QStyle>
#include <QEvent>
#include <QMenu>
ModernPropertyContext::ModernPropertyContext(RootProperty* root_, DAVA::ContextAccessor* accessor_, DAVA::OperationInvoker* invoker_, QWidget* parent_)
: accessor(accessor_)
, invoker(invoker_)
, parent(parent_)
{
root = root_;
}
ModernPropertyContext::~ModernPropertyContext()
{
}
RootProperty* ModernPropertyContext::GetRoot() const
{
return root.Get();
}
DAVA::ContextAccessor* ModernPropertyContext::GetAccessor() const
{
return accessor;
}
DAVA::OperationInvoker* ModernPropertyContext::GetInvoker() const
{
return invoker;
}
QWidget* ModernPropertyContext::GetParent() const
{
return parent;
}
ModernPropertyEditor::ModernPropertyEditor(const std::shared_ptr<ModernPropertyContext>& context_, ValueProperty* property_)
: QObject(context_->GetParent())
, context(context_)
{
property = property_;
isLayoutSensitive = property->GetName() == "size" || property->GetName() == "position";
resetAction = new QAction("Reset", context->GetParent());
QObject::connect(resetAction, &QAction::triggered, this, &ModernPropertyEditor::ResetProperty);
forceOverrideAction = new QAction("Force Override", context->GetParent());
QObject::connect(forceOverrideAction, &QAction::triggered, this, &ModernPropertyEditor::ForceOverride);
bindAction = new QAction("Bind", context->GetParent());
QObject::connect(bindAction, &QAction::triggered, this, &ModernPropertyEditor::BindProperty);
GetRootProperty()->propertyChanged.Connect(this, &ModernPropertyEditor::PropertyChanged);
DAVA::GetEngineContext()->uiControlSystem->GetStyleSheetSystem()->stylePropertiesChanged.Connect(this, &ModernPropertyEditor::OnStylePropertiesChanged);
DAVA::GetEngineContext()->uiControlSystem->GetLayoutSystem()->controlLayouted.Connect(this, &ModernPropertyEditor::OnControlLayouted);
}
ModernPropertyEditor::~ModernPropertyEditor()
{
GetRootProperty()->propertyChanged.Disconnect(this);
DAVA::GetEngineContext()->uiControlSystem->GetStyleSheetSystem()->stylePropertiesChanged.Disconnect(this);
DAVA::GetEngineContext()->uiControlSystem->GetLayoutSystem()->controlLayouted.Disconnect(this);
}
bool ModernPropertyEditor::IsBindingEditor() const
{
return false;
}
ValueProperty* ModernPropertyEditor::GetProperty() const
{
return property.Get();
}
void ModernPropertyEditor::ChangeProperty(const DAVA::Any& value)
{
if (!property->IsReadOnly())
{
DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
if (activeContext)
{
DocumentData* documentData = activeContext->GetData<DocumentData>();
DVASSERT(documentData != nullptr);
RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
documentData->ExecCommand<ChangePropertyValueCommand>(root->GetControlNode(), property.Get(), value);
}
}
}
void ModernPropertyEditor::ChangeBinding(const DAVA::String& expr, DAVA::int32 mode)
{
if (!property->IsReadOnly())
{
DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
if (activeContext)
{
DocumentData* documentData = activeContext->GetData<DocumentData>();
DVASSERT(documentData != nullptr);
RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
documentData->ExecCommand<ChangeBindingCommand>(root->GetControlNode(), property.Get(), expr, mode);
}
}
}
void ModernPropertyEditor::ApplyStyleToWidget(QWidget* widget)
{
widget->setProperty("overriden", overriden);
widget->setProperty("setByStyle", setByStyle);
widget->setProperty("inherited", inherited);
widget->style()->unpolish(widget);
widget->style()->polish(widget);
}
void ModernPropertyEditor::OnPropertyChanged()
{
overriden = property->IsOverriddenLocally();
setByStyle = false;
DAVA::int32 propertyIndex = property->GetStylePropertyIndex();
DAVA::UIControl* control = context->GetRoot()->GetControlNode()->GetControl();
if (propertyIndex != -1 && !control->GetLocalPropertySet().test(propertyIndex))
{
setByStyle = control->GetStyledPropertySet().test(propertyIndex);
}
inherited = property->GetFlags() & AbstractProperty::EF_INHERITED;
}
RootProperty* ModernPropertyEditor::GetRootProperty() const
{
return context->GetRoot();
}
DAVA::ContextAccessor* ModernPropertyEditor::GetAccessor() const
{
return context->GetAccessor();
}
DAVA::OperationInvoker* ModernPropertyEditor::GetInvoker() const
{
return context->GetInvoker();
}
QWidget* ModernPropertyEditor::GetParentWidget() const
{
return context->GetParent();
}
void ModernPropertyEditor::PropertyChanged(AbstractProperty* property_)
{
if (property.Get() == property_)
{
OnPropertyChanged();
}
}
void ModernPropertyEditor::OnStylePropertiesChanged(DAVA::UIControl* control, const DAVA::UIStyleSheetPropertySet& properties)
{
DAVA::int32 propertyIndex = property->GetStylePropertyIndex();
if (propertyIndex != -1 &&
properties.test(propertyIndex) &&
control == context->GetRoot()->GetControlNode()->GetControl())
{
OnPropertyChanged();
}
}
void ModernPropertyEditor::OnControlLayouted(DAVA::UIControl* control)
{
DAVA::UIControl* propertyControl = GetRootProperty()->GetControlNode()->GetControl();
if (isLayoutSensitive)
{
for (DAVA::UIControl* p = propertyControl; p != nullptr; p = p->GetParent())
{
if (p == control)
{
OnPropertyChanged();
break;
}
if (p->GetComponent<DAVA::UILayoutIsolationComponent>() != nullptr)
{
break;
}
}
}
}
void ModernPropertyEditor::ResetProperty()
{
if (!property->IsReadOnly())
{
DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
DVASSERT(activeContext != nullptr);
DocumentData* documentData = activeContext->GetData<DocumentData>();
DVASSERT(documentData != nullptr);
RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
documentData->ExecCommand<ChangePropertyValueCommand>(root->GetControlNode(), property.Get(), DAVA::Any());
}
}
void ModernPropertyEditor::BindProperty()
{
if (!property->IsReadOnly())
{
DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
DVASSERT(activeContext != nullptr);
DocumentData* documentData = activeContext->GetData<DocumentData>();
DVASSERT(documentData != nullptr);
RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
documentData->ExecCommand<ChangeBindingCommand>(root->GetControlNode(), property.Get(), "", 0);
}
}
void ModernPropertyEditor::ShowActionsMenu(const QPoint& pos)
{
QMenu menu;
menu.addAction(resetAction);
menu.addAction(forceOverrideAction);
if (property->IsBindable() && !property->IsBound())
{
menu.addAction(bindAction);
}
menu.exec(pos);
}
void ModernPropertyEditor::ForceOverride()
{
if (!property->IsReadOnly())
{
DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
DVASSERT(activeContext != nullptr);
DocumentData* documentData = activeContext->GetData<DocumentData>();
DVASSERT(documentData != nullptr);
RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
documentData->ExecCommand<ChangePropertyForceOverrideCommand>(root->GetControlNode(), property.Get());
}
}
bool ModernPropertyEditor::eventFilter(QObject* o, QEvent* e)
{
if (e->type() == QEvent::Wheel)
{
e->ignore();
return true;
}
return QObject::eventFilter(o, e);
}
| bsd-3-clause |
techvn/webstore | public/assets/backend/system/upload-file/editor/scripts/language/it-IT/length.js | 225 | function loadTxt()
{
document.getElementById("btnCancel").value = "cancella";
document.getElementById("btnOk").value = " ok ";
}
function writeTitle()
{
document.write("<title>Lunghezza</title>")
} | bsd-3-clause |
djparente/coevol-utils | src/filterFastaBySequence.py | 756 | #!/cygdrive/c/Python27/python.exe
# Daniel J. Parente
# MD/PhD Candidate
# Swint-Kruse Laboratory
# University of Kansas Medical Center
import sys
import Bio.SeqIO
# Filters a FASTA-formatted alignment (to stdin), retaining sequences
# only if the (ungapped) sequence occurs in the alignment specified
# as argument 1
def chomp(line):
return line.rstrip("\n").rstrip("\r")
def main():
includeMSA = list(Bio.SeqIO.parse(sys.argv[1], "fasta"))
includeDict = { str(x.seq).replace("-","") : 0 for x in includeMSA }
msa = list(Bio.SeqIO.parse(sys.stdin, "fasta"))
msa = [x for x in msa if str(x.seq).replace("-","") in includeDict]
for x in msa:
print ">" + x.name
print x.seq
if __name__=='__main__':
main() | bsd-3-clause |
SEL-Columbia/commcare-hq | corehq/apps/app_manager/management/commands/ptop_fast_reindex_apps.py | 467 | from corehq.apps.app_manager.models import ApplicationBase
from corehq.apps.hqcase.management.commands.ptop_fast_reindexer import ElasticReindexer
from corehq.pillows.application import AppPillow
CHUNK_SIZE = 500
POOL_SIZE = 15
class Command(ElasticReindexer):
help = "Fast reindex of app elastic index by using the applications view and reindexing apps"
doc_class = ApplicationBase
view_name = 'app_manager/applications'
pillow_class = AppPillow
| bsd-3-clause |
DominicDirkx/tudat | Tudat/InputOutput/solarActivityData.cpp | 6983 | /* Copyright (c) 2010-2018, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
* References
* Data file:
* http://celestrak.com/SpaceData/sw19571001.txt
* Data format explanation:
* http://celestrak.com/SpaceData/SpaceWx-format.asp
*
*/
#include <istream>
#include <string>
#include <vector>
#include "Tudat/Basics/testMacros.h"
#include "Tudat/InputOutput/solarActivityData.h"
#include "Tudat/InputOutput/parsedDataVectorUtilities.h"
#include "Tudat/InputOutput/parseSolarActivityData.h"
#include "Tudat/InputOutput/extractSolarActivityData.h"
#include "Tudat/InputOutput/basicInputOutput.h"
#include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h"
namespace tudat
{
namespace input_output
{
namespace solar_activity
{
//! Default constructor.
SolarActivityData::SolarActivityData( ) : year( 0 ), month( 0 ), day( 0 ),
bartelsSolarRotationNumber( 0 ), dayOfBartelsCycle( 0 ), planetaryRangeIndexSum( 0 ),
planetaryEquivalentAmplitudeAverage( 0 ), planetaryDailyCharacterFigure( -0.0 ),
planetaryDailyCharacterFigureConverted( 0 ), internationalSunspotNumber( 0 ),
solarRadioFlux107Adjusted( -0.0 ), fluxQualifier( 0 ),
centered81DaySolarRadioFlux107Adjusted( -0.0 ), last81DaySolarRadioFlux107Adjusted ( -0.0 ),
solarRadioFlux107Observed( -0.0 ), centered81DaySolarRadioFlux107Observed( -0.0 ),
last81DaySolarRadioFlux107Observed ( -0.0 ), planetaryRangeIndexVector( Eigen::VectorXd::Zero( 8 ) ),
planetaryEquivalentAmplitudeVector( Eigen::VectorXd::Zero( 8 ) ), dataType( 0 ) { }
//! Overload ostream to print class information.
std::ostream& operator << ( std::ostream& stream,
SolarActivityData& solarActivityData )
{
stream << "This is a Solar Activity data object." << std::endl;
stream << "The solar activity information is stored as: " << std::endl;
stream << "Year: " << solarActivityData.year << std::endl;
stream << "Month: " << solarActivityData.month << std::endl;
stream << "Day: " << solarActivityData.day << std::endl;
stream << "BSRN: " << solarActivityData.bartelsSolarRotationNumber << std::endl;
stream << "ND: " << solarActivityData.dayOfBartelsCycle << std::endl;
stream << "Kp (0000-0300 UT): " << solarActivityData.planetaryRangeIndexVector(0) << std::endl;
stream << "Kp (0300-0600 UT): " << solarActivityData.planetaryRangeIndexVector(1) << std::endl;
stream << "Kp (0600-0900 UT): " << solarActivityData.planetaryRangeIndexVector(2) << std::endl;
stream << "Kp (0900-1200 UT): " << solarActivityData.planetaryRangeIndexVector(3) << std::endl;
stream << "Kp (1200-1500 UT): " << solarActivityData.planetaryRangeIndexVector(4) << std::endl;
stream << "Kp (1500-1800 UT): " << solarActivityData.planetaryRangeIndexVector(5) << std::endl;
stream << "Kp (1800-2100 UT): " << solarActivityData.planetaryRangeIndexVector(6) << std::endl;
stream << "Kp (2100-0000 UT): " << solarActivityData.planetaryRangeIndexVector(7) << std::endl;
stream << "Kp-sum: " << solarActivityData.planetaryRangeIndexSum << std::endl;
stream << "Ap (0000-0300 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(0) << std::endl;
stream << "Ap (0300-0600 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(1) << std::endl;
stream << "Ap (0600-0900 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(2) << std::endl;
stream << "Ap (0900-1200 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(3) << std::endl;
stream << "Ap (1200-1500 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(4) << std::endl;
stream << "Ap (1500-1800 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(5) << std::endl;
stream << "Ap (1800-2100 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(6) << std::endl;
stream << "Ap (2100-0000 UT): " << solarActivityData.planetaryEquivalentAmplitudeVector(7) << std::endl;
stream << "Ap-average: " << solarActivityData.planetaryEquivalentAmplitudeAverage << std::endl;
stream << "Cp: " << solarActivityData.planetaryDailyCharacterFigure << std::endl;
stream << "C9: " << solarActivityData.planetaryDailyCharacterFigureConverted << std::endl;
stream << "ISN: " << solarActivityData.internationalSunspotNumber << std::endl;
stream << "F10.7 (Adjusted): " << solarActivityData.solarRadioFlux107Adjusted << std::endl;
stream << "Q: " << solarActivityData.fluxQualifier << std::endl;
stream << "Ctr81 (Adjusted): " << solarActivityData.centered81DaySolarRadioFlux107Adjusted << std::endl;
stream << "Lst81 (Adjusted): " << solarActivityData.last81DaySolarRadioFlux107Adjusted << std::endl;
stream << "F10.7 (Observed): " << solarActivityData.solarRadioFlux107Observed << std::endl;
stream << "Ctr81 (Observed): " << solarActivityData.centered81DaySolarRadioFlux107Observed << std::endl;
stream << "Lst81 (Observed): " << solarActivityData.last81DaySolarRadioFlux107Observed << std::endl;
stream << "Datatype: " << solarActivityData.dataType << std::endl;
// Return stream.
return stream;
}
//! This function reads a SpaceWeather data file and returns a map with SolarActivityData
SolarActivityDataMap readSolarActivityData( std::string filePath )
{
// Data Vector container
tudat::input_output::parsed_data_vector_utilities::ParsedDataVectorPtr parsedDataVector;
// datafile Parser and Extractor
tudat::input_output::solar_activity::ParseSolarActivityData solarActivityParser;
tudat::input_output::solar_activity::ExtractSolarActivityData solarActivityExtractor;
// Open dataFile and Parse
std::ifstream dataFile;
dataFile.open( filePath.c_str( ), std::ifstream::in );
parsedDataVector = solarActivityParser.parse( dataFile );
dataFile.close( );
int numberOfLines = parsedDataVector->size( );
SolarActivityDataMap dataMap;
double julianDate = TUDAT_NAN;
// Save each line to datamap
for(int i = 0 ; i < numberOfLines ; i++ ){
julianDate = tudat::basic_astrodynamics::convertCalendarDateToJulianDay(
solarActivityExtractor.extract( parsedDataVector->at( i ) )->year,
solarActivityExtractor.extract( parsedDataVector->at( i ) )->month,
solarActivityExtractor.extract( parsedDataVector->at( i ) )->day,
0, 0, 0.0 ) ;
dataMap[ julianDate ] = solarActivityExtractor.extract( parsedDataVector->at( i ) ) ;
}
return dataMap;
}
} // solar_activity
} // input_output
} // tudat
| bsd-3-clause |
MadCat34/zend-log | test/WriterPluginManagerTest.php | 879 | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Log;
use Zend\Log\WriterPluginManager;
use Zend\ServiceManager\ServiceManager;
/**
* @group Zend_Log
*/
class WriterPluginManagerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var WriterPluginManager
*/
protected $plugins;
public function setUp()
{
$this->plugins = new WriterPluginManager(new ServiceManager());
}
public function testInvokableClassFirephp()
{
$firephp = $this->plugins->get('firephp');
$this->assertInstanceOf('Zend\Log\Writer\Firephp', $firephp);
}
}
| bsd-3-clause |
buaasun/grappa | applications/graphlab/graphlab_naive.hpp | 7588 | ////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2015, University of Washington and Battelle
// Memorial Institute. 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 University of Washington, Battelle
// Memorial Institute, or the names of their 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 THE
// UNIVERSITY OF WASHINGTON OR BATTELLE MEMORIAL INSTITUTE 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.
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/// GraphLab is an API and runtime system for graph-parallel computation.
/// This is a rough prototype implementation of the programming model to
/// demonstrate using Grappa as a platform for other models.
/// More information on the actual GraphLab system can be found at:
/// graphlab.org.
////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Simplified GraphLab API, implemented for Grappa's builtin Graph structure.
// (included from graphlab.hpp)
#pragma once
/// Additional vertex state needed for GraphLab engine. Your Graph's VertexData
/// must be a subclass of this to use the NaiveGraphlabEngine.
template< typename Subclass >
struct GraphlabVertexData {
static Reducer<int64_t,ReducerType::Add> total_active;
void* prog;
bool active, active_minor_step;
GraphlabVertexData(): active(false) {}
void activate() { if (!active) { total_active++; active = true; } }
void deactivate() { if (active) { total_active--; active = false; } }
};
/// Additional state for tracking active vertices in NaiveGraphlabEngine
template< typename Subclass >
Reducer<int64_t,ReducerType::Add> GraphlabVertexData<Subclass>::total_active;
/// Activate all vertices (for NaiveGraphlabEngine)
template< typename V, typename E >
void activate_all(GlobalAddress<Graph<V,E>> g) {
forall(g, [](typename Graph<V,E>::Vertex& v){ v->activate(); });
}
/// Activate a single vertex (for NaiveGraphlabEngine)
template< typename V >
void activate(GlobalAddress<V> v) {
delegate::call(v, [](V& v){ v->activate(); });
}
/// Graphlab engine implemented over the naive Grappa graph structure.
///
/// Because Grappa's Graph only has out-edges per vertex, this engine can
/// only execute a subset of Graphlab vertex programs. Namely, it forces
/// the following:
///
/// - gather_edges: IN_EDGES | NONE, represented as a bool
/// (note: ALL_EDGES can also be done if the graph is constructed as
/// "undirected" as edges will then be duplicated)
/// - scatter_edges: OUT_EDGES | NONE, represented as a bool
/// - If the graph was constructed as "undirected", then both bools above
/// instead indicate ALL_EDGES | NONE.
/// - Delta caching is assumed to be *enabled* (if you have no Gather type,
/// this won't bother you)
///
/// A couple additional caveats:
/// - only one Engine can be executed at a time in the system
/// - Gather type must be POD
///
/// @tparam G Graph type
/// @tparam VertexProg Vertex program, subclass of GraphlabVertexProgram.
///
template< typename G, typename VertexProg >
struct NaiveGraphlabEngine {
using Vertex = typename G::Vertex;
using Edge = typename G::Edge;
using Gather = typename VertexProg::Gather;
static GlobalAddress<G> g;
static Reducer<int64_t,ReducerType::Add> ct;
static VertexProg& prog(Vertex& v) {
return *static_cast<VertexProg*>(v->prog);
}
static void _do_scatter(const VertexProg& prog_copy, Edge& e,
Gather (VertexProg::*f)(Vertex&) const) {
call<async>(e.ga, [=](Vertex& ve){
auto gather_delta = prog_copy.scatter(ve);
prog(ve).post_delta(gather_delta);
});
}
static void _do_scatter(const VertexProg& prog_copy, Edge& e,
Gather (VertexProg::*f)(const Edge&, Vertex&) const) {
auto e_id = e.id;
auto e_data = e.data;
call<async>(e.ga, [=](Vertex& ve){
auto local_e_data = e_data;
Edge e = { e_id, g->vs+e_id, local_e_data };
auto gather_delta = prog_copy.scatter(e, ve);
prog(ve).post_delta(gather_delta);
});
}
/// Run synchronous engine, assumes:
/// - Delta caching enabled
/// - gather_edges:IN_EDGES, scatter_edges:(OUT_EDGES || NONE)
template< typename V, typename E >
static void run_sync(GlobalAddress<Graph<V,E>> _g) {
call_on_all_cores([=]{ g = _g; });
ct = 0;
// initialize GraphlabVertexProgram
forall(g, [=](Vertex& v){
v->prog = new VertexProg(v);
if (prog(v).gather_edges(v)) ct++;
});
if (ct > 0) {
forall(g, [=](Vertex& v){
forall<async>(adj(g,v), [=,&v](Edge& e){
// gather
auto delta = prog(v).gather(v, e);
call<async>(e.ga, [=](Vertex& ve){
prog(ve).post_delta(delta);
});
});
});
}
int iteration = 0;
size_t active = V::total_active;
while ( active > 0 && iteration < FLAGS_max_iterations )
GRAPPA_TIME_REGION(iteration_time) {
VLOG(1) << "iteration " << std::setw(3) << iteration;
VLOG(1) << " active: " << active;
double t = walltime();
forall(g, [=](Vertex& v){
if (!v->active) return;
v->deactivate();
auto& p = prog(v);
// apply
p.apply(v, p.cache);
v->active_minor_step = p.scatter_edges(v);
});
forall(g, [=](Vertex& v){
if (v->active_minor_step) {
v->active_minor_step = false;
auto prog_copy = prog(v);
// scatter
forall<async>(adj(g,v), [=](Edge& e){
_do_scatter(prog_copy, e, &VertexProg::scatter);
});
}
});
iteration++;
VLOG(1) << " time: " << walltime()-t;
active = V::total_active;
}
forall(g, [](Vertex& v){ delete static_cast<VertexProg*>(v->prog); });
}
};
template< typename G, typename VertexProg >
GlobalAddress<G> NaiveGraphlabEngine<G,VertexProg>::g;
template< typename G, typename VertexProg >
Reducer<int64_t,ReducerType::Add> NaiveGraphlabEngine<G,VertexProg>::ct;
| bsd-3-clause |
boldprogressives/akcode | main/diff.py | 16825 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2004-2009 Edgewall Software
# Copyright (C) 2004-2006 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Christopher Lenz <cmlenz@gmx.de>
import difflib
import re
from genshi import Markup, escape
def classes(*args, **kwargs):
"""Helper function for dynamically assembling a list of CSS class names
in templates.
Any positional arguments are added to the list of class names. All
positional arguments must be strings:
>>> classes('foo', 'bar')
u'foo bar'
In addition, the names of any supplied keyword arguments are added if they
have a truth value:
>>> classes('foo', bar=True)
u'foo bar'
>>> classes('foo', bar=False)
u'foo'
If none of the arguments are added to the list, this function returns
`None`:
>>> classes(bar=False)
"""
classes = list(filter(None, args)) + [k for k, v in kwargs.items() if v]
if not classes:
return None
return u' '.join(classes)
def first_last(idx, seq):
"""Generate ``first`` or ``last`` or both, according to the
position `idx` in sequence `seq`.
"""
return classes(first=idx == 0, last=idx == len(seq) - 1)
def expandtabs(s, tabstop=8, ignoring=None):
"""Expand tab characters `'\\\\t'` into spaces.
:param tabstop: number of space characters per tab
(defaults to the canonical 8)
:param ignoring: if not `None`, the expansion will be "smart" and
go from one tabstop to the next. In addition,
this parameter lists characters which can be
ignored when computing the indent.
"""
if '\t' not in s:
return s
if ignoring is None:
return s.expandtabs(tabstop)
outlines = []
for line in s.split('\n'):
if '\t' not in line:
outlines.append(line)
continue
p = 0
s = []
for c in line:
if c == '\t':
n = tabstop - p % tabstop
s.append(' ' * n)
p += n
elif not ignoring or c not in ignoring:
p += 1
s.append(c)
else:
s.append(c)
outlines.append(''.join(s))
return '\n'.join(outlines)
def get_change_extent(str1, str2):
"""Determines the extent of differences between two strings.
Returns a pair containing the offset at which the changes start,
and the negative offset at which the changes end.
If the two strings have neither a common prefix nor a common
suffix, ``(0, 0)`` is returned.
"""
start = 0
limit = min(len(str1), len(str2))
while start < limit and str1[start] == str2[start]:
start += 1
end = -1
limit = limit - start
while -end <= limit and str1[end] == str2[end]:
end -= 1
return (start, end + 1)
def get_filtered_hunks(fromlines, tolines, context=None,
ignore_blank_lines=False, ignore_case=False,
ignore_space_changes=False):
"""Retrieve differences in the form of `difflib.SequenceMatcher`
opcodes, grouped according to the ``context`` and ``ignore_*``
parameters.
:param fromlines: list of lines corresponding to the old content
:param tolines: list of lines corresponding to the new content
:param ignore_blank_lines: differences about empty lines only are ignored
:param ignore_case: upper case / lower case only differences are ignored
:param ignore_space_changes: differences in amount of spaces are ignored
:param context: the number of "equal" lines kept for representing
the context of the change
:return: generator of grouped `difflib.SequenceMatcher` opcodes
If none of the ``ignore_*`` parameters is `True`, there's nothing
to filter out the results will come straight from the
SequenceMatcher.
"""
hunks = get_hunks(fromlines, tolines, context)
if ignore_space_changes or ignore_case or ignore_blank_lines:
hunks = filter_ignorable_lines(hunks, fromlines, tolines, context,
ignore_blank_lines, ignore_case,
ignore_space_changes)
return hunks
def get_hunks(fromlines, tolines, context=None):
"""Generator yielding grouped opcodes describing differences .
See `get_filtered_hunks` for the parameter descriptions.
"""
matcher = difflib.SequenceMatcher(None, fromlines, tolines)
if context is None:
return (hunk for hunk in [matcher.get_opcodes()])
else:
return matcher.get_grouped_opcodes(context)
def filter_ignorable_lines(hunks, fromlines, tolines, context,
ignore_blank_lines, ignore_case,
ignore_space_changes):
"""Detect line changes that should be ignored and emits them as
tagged as "equal", possibly joined with the preceding and/or
following "equal" block.
See `get_filtered_hunks` for the parameter descriptions.
"""
def is_ignorable(tag, fromlines, tolines):
if tag == 'delete' and ignore_blank_lines:
if ''.join(fromlines) == '':
return True
elif tag == 'insert' and ignore_blank_lines:
if ''.join(tolines) == '':
return True
elif tag == 'replace' and (ignore_case or ignore_space_changes):
if len(fromlines) != len(tolines):
return False
def f(str):
if ignore_case:
str = str.lower()
if ignore_space_changes:
str = ' '.join(str.split())
return str
for i in range(len(fromlines)):
if f(fromlines[i]) != f(tolines[i]):
return False
return True
hunks = list(hunks)
opcodes = []
ignored_lines = False
prev = None
for hunk in hunks:
for tag, i1, i2, j1, j2 in hunk:
if tag == 'equal':
if prev:
prev = (tag, prev[1], i2, prev[3], j2)
else:
prev = (tag, i1, i2, j1, j2)
else:
if is_ignorable(tag, fromlines[i1:i2], tolines[j1:j2]):
ignored_lines = True
if prev:
prev = 'equal', prev[1], i2, prev[3], j2
else:
prev = 'equal', i1, i2, j1, j2
continue
if prev:
opcodes.append(prev)
opcodes.append((tag, i1, i2, j1, j2))
prev = None
if prev:
opcodes.append(prev)
if ignored_lines:
if context is None:
yield opcodes
else:
# we leave at most n lines with the tag 'equal' before and after
# every change
n = context
nn = n + n
group = []
def all_equal():
all(op[0] == 'equal' for op in group)
for idx, (tag, i1, i2, j1, j2) in enumerate(opcodes):
if idx == 0 and tag == 'equal': # Fixup leading unchanged block
i1, j1 = max(i1, i2 - n), max(j1, j2 - n)
elif tag == 'equal' and i2 - i1 > nn:
group.append((tag, i1, min(i2, i1 + n), j1,
min(j2, j1 + n)))
if not all_equal():
yield group
group = []
i1, j1 = max(i1, i2 - n), max(j1, j2 - n)
group.append((tag, i1, i2, j1, j2))
if group and not (len(group) == 1 and group[0][0] == 'equal'):
if group[-1][0] == 'equal': # Fixup trailing unchanged block
tag, i1, i2, j1, j2 = group[-1]
group[-1] = tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)
if not all_equal():
yield group
else:
for hunk in hunks:
yield hunk
def hdf_diff(*args, **kwargs):
""":deprecated: use `diff_blocks` (will be removed in 1.1.1)"""
return diff_blocks(*args, **kwargs)
def diff_blocks(fromlines, tolines, context=None, tabwidth=8,
ignore_blank_lines=0, ignore_case=0, ignore_space_changes=0):
"""Return an array that is adequate for adding to the data dictionary
See `get_filtered_hunks` for the parameter descriptions.
See also the diff_div.html template.
"""
type_map = {'replace': 'mod', 'delete': 'rem', 'insert': 'add',
'equal': 'unmod'}
space_re = re.compile(' ( +)|^ ')
def htmlify(match):
div, mod = divmod(len(match.group(0)), 2)
return div * ' ' + mod * ' '
def markup_intraline_changes(opcodes):
for tag, i1, i2, j1, j2 in opcodes:
if tag == 'replace' and i2 - i1 == j2 - j1:
for i in range(i2 - i1):
fromline, toline = fromlines[i1 + i], tolines[j1 + i]
(start, end) = get_change_extent(fromline, toline)
if start != 0 or end != 0:
last = end + len(fromline)
fromlines[i1 + i] = (
fromline[:start] + '\0' + fromline[start:last] +
'\1' + fromline[last:])
last = end+len(toline)
tolines[j1 + i] = (
toline[:start] + '\0' + toline[start:last] +
'\1' + toline[last:])
yield tag, i1, i2, j1, j2
changes = []
for group in get_filtered_hunks(fromlines, tolines, context,
ignore_blank_lines, ignore_case,
ignore_space_changes):
blocks = []
last_tag = None
for tag, i1, i2, j1, j2 in markup_intraline_changes(group):
if tag != last_tag:
blocks.append({'type': type_map[tag],
'base': {'offset': i1, 'lines': []},
'changed': {'offset': j1, 'lines': []}})
if tag == 'equal':
for line in fromlines[i1:i2]:
line = line.expandtabs(tabwidth)
line = space_re.sub(htmlify, escape(line, quotes=False))
blocks[-1]['base']['lines'].append(Markup(unicode(line)))
for line in tolines[j1:j2]:
line = line.expandtabs(tabwidth)
line = space_re.sub(htmlify, escape(line, quotes=False))
blocks[-1]['changed']['lines'].append(Markup(unicode(line)))
else:
if tag in ('replace', 'delete'):
for line in fromlines[i1:i2]:
line = expandtabs(line, tabwidth, '\0\1')
line = escape(line, quotes=False)
line = '<del>'.join([space_re.sub(htmlify, seg)
for seg in line.split('\0')])
line = line.replace('\1', '</del>')
blocks[-1]['base']['lines'].append(
Markup(unicode(line)))
if tag in ('replace', 'insert'):
for line in tolines[j1:j2]:
line = expandtabs(line, tabwidth, '\0\1')
line = escape(line, quotes=False)
line = '<ins>'.join([space_re.sub(htmlify, seg)
for seg in line.split('\0')])
line = line.replace('\1', '</ins>')
blocks[-1]['changed']['lines'].append(
Markup(unicode(line)))
changes.append(blocks)
return changes
def unified_diff(fromlines, tolines, context=None, ignore_blank_lines=0,
ignore_case=0, ignore_space_changes=0):
"""Generator producing lines corresponding to a textual diff.
See `get_filtered_hunks` for the parameter descriptions.
"""
for group in get_filtered_hunks(fromlines, tolines, context,
ignore_blank_lines, ignore_case,
ignore_space_changes):
i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
if i1 == 0 and i2 == 0:
i1, i2 = -1, -1 # support for 'A'dd changes
yield '@@ -%d,%d +%d,%d @@' % (i1 + 1, i2 - i1, j1 + 1, j2 - j1)
for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
for line in fromlines[i1:i2]:
yield ' ' + line
else:
if tag in ('replace', 'delete'):
for line in fromlines[i1:i2]:
yield '-' + line
if tag in ('replace', 'insert'):
for line in tolines[j1:j2]:
yield '+' + line
def get_diff_options(req):
"""Retrieve user preferences for diffs.
:return: ``(style, options, data)`` triple.
``style``
can be ``'inline'`` or ``'sidebyside'``,
``options``
a sequence of "diff" flags,
``data``
the style and options information represented as
key/value pairs in dictionaries, for example::
{'style': u'sidebyside',
'options': {'contextall': 1, 'contextlines': 2,
'ignorecase': 0, 'ignoreblanklines': 0,
'ignorewhitespace': 1}}
"""
options_data = {}
data = {'options': options_data}
def get_bool_option(name, default=0):
pref = int(req.session.get('diff_' + name, default))
arg = int(name in req.args)
if 'update' in req.args and arg != pref:
req.session.set('diff_' + name, arg, default)
else:
arg = pref
return arg
pref = req.session.get('diff_style', 'inline')
style = req.args.get('style', pref)
if 'update' in req.args and style != pref:
req.session.set('diff_style', style, 'inline')
data['style'] = style
pref = int(req.session.get('diff_contextlines', 2))
try:
context = int(req.args.get('contextlines', pref))
except ValueError:
context = -1
if 'update' in req.args and context != pref:
req.session.set('diff_contextlines', context, 2)
options_data['contextlines'] = context
arg = int(req.args.get('contextall', 0))
options_data['contextall'] = arg
options = ['-U%d' % (-1 if arg else context)]
arg = get_bool_option('ignoreblanklines')
if arg:
options.append('-B')
options_data['ignoreblanklines'] = arg
arg = get_bool_option('ignorecase')
if arg:
options.append('-i')
options_data['ignorecase'] = arg
arg = get_bool_option('ignorewhitespace')
if arg:
options.append('-b')
options_data['ignorewhitespace'] = arg
return (style, options, data)
from django.conf import settings
from genshi.template import TemplateLoader
genshi_loader = TemplateLoader([settings.GENSHI_TEMPLATE_DIR])
def make_diff_snippet(block1, block2,
block1_filename, block2_filename,
block1_rev, block2_rev,
block1_href, block2_href,
context_lines=3):
diffs = diff_blocks(block1.splitlines(), block2.splitlines(),
context=context_lines,
ignore_blank_lines=True,
ignore_space_changes=True)
changes = [{'diffs': diffs, 'props': [],
'old': {'path': block1_filename, 'rev': block1_rev, 'shortrev': block1_rev[:4], 'href': block1_href},
'new': {'path': block2_filename, 'rev': block2_rev, 'shortrev': block2_rev[:4], 'href': block2_href},
}]
diff_tmpl = genshi_loader.load("diff_div.html")
stream = diff_tmpl.generate(changes=changes,
no_id=False,
diff={'style': "inline"},
longcol="Revision",
first_last=first_last,
shortcol='')
diff_code = stream.render()
return diff_code
| bsd-3-clause |
ellmetha/django-machina | machina/apps/forum_tracking/abstract_models.py | 2050 | """
Forum tracking abstract models
==============================
This module defines abstract models provided by the ``forum_tracking`` application.
"""
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from machina.core.loading import get_class
ForumReadTrackManager = get_class('forum_tracking.managers', 'ForumReadTrackManager')
class AbstractForumReadTrack(models.Model):
""" Represents a track which records which forums have been read by a given user. """
user = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='forum_tracks', on_delete=models.CASCADE,
verbose_name=_('User'),
)
forum = models.ForeignKey(
'forum.Forum', related_name='tracks', on_delete=models.CASCADE, verbose_name=_('Forum'),
)
mark_time = models.DateTimeField(auto_now=True, db_index=True)
objects = ForumReadTrackManager()
class Meta:
abstract = True
app_label = 'forum_tracking'
unique_together = ['user', 'forum', ]
verbose_name = _('Forum track')
verbose_name_plural = _('Forum tracks')
def __str__(self):
return '{} - {}'.format(self.user, self.forum)
class AbstractTopicReadTrack(models.Model):
""" Represents a track which records which topics have been read by a given user. """
user = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='topic_tracks', on_delete=models.CASCADE,
verbose_name=_('User'),
)
topic = models.ForeignKey(
'forum_conversation.Topic', related_name='tracks', on_delete=models.CASCADE,
verbose_name=_('Topic'),
)
mark_time = models.DateTimeField(auto_now=True, db_index=True)
class Meta:
abstract = True
app_label = 'forum_tracking'
unique_together = ['user', 'topic', ]
verbose_name = _('Topic track')
verbose_name_plural = _('Topic tracks')
def __str__(self):
return '{} - {}'.format(self.user, self.topic)
| bsd-3-clause |
kaushik94/react | packages/react-dom/src/__tests__/ReactCompositeComponent-test.js | 47969 | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let ChildUpdates;
let MorphingComponent;
let React;
let ReactDOM;
let ReactDOMServer;
let ReactCurrentOwner;
let ReactTestUtils;
let PropTypes;
describe('ReactCompositeComponent', () => {
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA: mixed, objB: mixed): boolean {
if (Object.is(objA, objB)) {
return true;
}
if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
for (let i = 0; i < keysA.length; i++) {
if (
!hasOwnProperty.call(objB, keysA[i]) ||
!Object.is(objA[keysA[i]], objB[keysA[i]])
) {
return false;
}
}
return true;
}
function shallowCompare(instance, nextProps, nextState) {
return (
!shallowEqual(instance.props, nextProps) ||
!shallowEqual(instance.state, nextState)
);
}
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMServer = require('react-dom/server');
ReactCurrentOwner = require('react')
.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner;
ReactTestUtils = require('react-dom/test-utils');
PropTypes = require('prop-types');
MorphingComponent = class extends React.Component {
state = {activated: false};
_toggleActivatedState = () => {
this.setState({activated: !this.state.activated});
};
render() {
const toggleActivatedState = this._toggleActivatedState;
return !this.state.activated ? (
<a ref="x" onClick={toggleActivatedState} />
) : (
<b ref="x" onClick={toggleActivatedState} />
);
}
};
/**
* We'll use this to ensure that an old version is not cached when it is
* reallocated again.
*/
ChildUpdates = class extends React.Component {
getAnchor = () => {
return this.refs.anch;
};
render() {
const className = this.props.anchorClassOn ? 'anchorClass' : '';
return this.props.renderAnchor ? (
<a ref="anch" className={className} />
) : (
<b />
);
}
};
});
it('should support module pattern components', () => {
function Child({test}) {
return {
render() {
return <div>{test}</div>;
},
};
}
const el = document.createElement('div');
ReactDOM.render(<Child test="test" />, el);
expect(el.textContent).toBe('test');
});
it('should support rendering to different child types over time', () => {
const instance = ReactTestUtils.renderIntoDocument(<MorphingComponent />);
let el = ReactDOM.findDOMNode(instance);
expect(el.tagName).toBe('A');
instance._toggleActivatedState();
el = ReactDOM.findDOMNode(instance);
expect(el.tagName).toBe('B');
instance._toggleActivatedState();
el = ReactDOM.findDOMNode(instance);
expect(el.tagName).toBe('A');
});
it('should not thrash a server rendered layout with client side one', () => {
class Child extends React.Component {
render() {
return null;
}
}
class Parent extends React.Component {
render() {
return (
<div>
<Child />
</div>
);
}
}
const markup = ReactDOMServer.renderToString(<Parent />);
// Old API based on heuristic
let container = document.createElement('div');
container.innerHTML = markup;
expect(() => ReactDOM.render(<Parent />, container)).toLowPriorityWarnDev(
'render(): Calling ReactDOM.render() to hydrate server-rendered markup ' +
'will stop working in React v17. Replace the ReactDOM.render() call ' +
'with ReactDOM.hydrate() if you want React to attach to the server HTML.',
{withoutStack: true},
);
// New explicit API
container = document.createElement('div');
container.innerHTML = markup;
ReactDOM.hydrate(<Parent />, container);
});
it('should react to state changes from callbacks', () => {
const container = document.createElement('div');
document.body.appendChild(container);
try {
const instance = ReactDOM.render(<MorphingComponent />, container);
let el = ReactDOM.findDOMNode(instance);
expect(el.tagName).toBe('A');
el.click();
el = ReactDOM.findDOMNode(instance);
expect(el.tagName).toBe('B');
} finally {
document.body.removeChild(container);
}
});
it('should rewire refs when rendering to different child types', () => {
const instance = ReactTestUtils.renderIntoDocument(<MorphingComponent />);
expect(instance.refs.x.tagName).toBe('A');
instance._toggleActivatedState();
expect(instance.refs.x.tagName).toBe('B');
instance._toggleActivatedState();
expect(instance.refs.x.tagName).toBe('A');
});
it('should not cache old DOM nodes when switching constructors', () => {
const container = document.createElement('div');
const instance = ReactDOM.render(
<ChildUpdates renderAnchor={true} anchorClassOn={false} />,
container,
);
ReactDOM.render(
// Warm any cache
<ChildUpdates renderAnchor={true} anchorClassOn={true} />,
container,
);
ReactDOM.render(
// Clear out the anchor
<ChildUpdates renderAnchor={false} anchorClassOn={true} />,
container,
);
ReactDOM.render(
// rerender
<ChildUpdates renderAnchor={true} anchorClassOn={false} />,
container,
);
expect(instance.getAnchor().className).toBe('');
});
it('should use default values for undefined props', () => {
class Component extends React.Component {
static defaultProps = {prop: 'testKey'};
render() {
return <span />;
}
}
const instance1 = ReactTestUtils.renderIntoDocument(<Component />);
expect(instance1.props).toEqual({prop: 'testKey'});
const instance2 = ReactTestUtils.renderIntoDocument(
<Component prop={undefined} />,
);
expect(instance2.props).toEqual({prop: 'testKey'});
const instance3 = ReactTestUtils.renderIntoDocument(
<Component prop={null} />,
);
expect(instance3.props).toEqual({prop: null});
});
it('should not mutate passed-in props object', () => {
class Component extends React.Component {
static defaultProps = {prop: 'testKey'};
render() {
return <span />;
}
}
const inputProps = {};
let instance1 = <Component {...inputProps} />;
instance1 = ReactTestUtils.renderIntoDocument(instance1);
expect(instance1.props.prop).toBe('testKey');
// We don't mutate the input, just in case the caller wants to do something
// with it after using it to instantiate a component
expect(inputProps.prop).not.toBeDefined();
});
it('should warn about `forceUpdate` on not-yet-mounted components', () => {
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.forceUpdate();
}
render() {
return <div />;
}
}
const container = document.createElement('div');
expect(() => ReactDOM.render(<MyComponent />, container)).toWarnDev(
"Warning: Can't call forceUpdate on a component that is not yet mounted. " +
'This is a no-op, but it might indicate a bug in your application. ' +
'Instead, assign to `this.state` directly or define a `state = {};` ' +
'class property with the desired state in the MyComponent component.',
{withoutStack: true},
);
// No additional warning should be recorded
const container2 = document.createElement('div');
ReactDOM.render(<MyComponent />, container2);
});
it('should warn about `setState` on not-yet-mounted components', () => {
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.setState();
}
render() {
return <div />;
}
}
const container = document.createElement('div');
expect(() => ReactDOM.render(<MyComponent />, container)).toWarnDev(
"Warning: Can't call setState on a component that is not yet mounted. " +
'This is a no-op, but it might indicate a bug in your application. ' +
'Instead, assign to `this.state` directly or define a `state = {};` ' +
'class property with the desired state in the MyComponent component.',
{withoutStack: true},
);
// No additional warning should be recorded
const container2 = document.createElement('div');
ReactDOM.render(<MyComponent />, container2);
});
it('should warn about `forceUpdate` on unmounted components', () => {
const container = document.createElement('div');
document.body.appendChild(container);
class Component extends React.Component {
render() {
return <div />;
}
}
let instance = <Component />;
expect(instance.forceUpdate).not.toBeDefined();
instance = ReactDOM.render(instance, container);
instance.forceUpdate();
ReactDOM.unmountComponentAtNode(container);
expect(() => instance.forceUpdate()).toWarnDev(
"Warning: Can't perform a React state update on an unmounted " +
'component. This is a no-op, but it indicates a memory leak in your ' +
'application. To fix, cancel all subscriptions and asynchronous ' +
'tasks in the componentWillUnmount method.\n' +
' in Component (at **)',
);
// No additional warning should be recorded
instance.forceUpdate();
});
it('should warn about `setState` on unmounted components', () => {
const container = document.createElement('div');
document.body.appendChild(container);
let renders = 0;
class Component extends React.Component {
state = {value: 0};
render() {
renders++;
return <div />;
}
}
let instance;
ReactDOM.render(
<div>
<span>
<Component ref={c => (instance = c || instance)} />
</span>
</div>,
container,
);
expect(renders).toBe(1);
instance.setState({value: 1});
expect(renders).toBe(2);
ReactDOM.render(<div />, container);
expect(() => {
instance.setState({value: 2});
}).toWarnDev(
"Warning: Can't perform a React state update on an unmounted " +
'component. This is a no-op, but it indicates a memory leak in your ' +
'application. To fix, cancel all subscriptions and asynchronous ' +
'tasks in the componentWillUnmount method.\n' +
' in Component (at **)\n' +
' in span',
);
expect(renders).toBe(2);
});
it('should silently allow `setState`, not call cb on unmounting components', () => {
let cbCalled = false;
const container = document.createElement('div');
document.body.appendChild(container);
class Component extends React.Component {
state = {value: 0};
componentWillUnmount() {
expect(() => {
this.setState({value: 2}, function() {
cbCalled = true;
});
}).not.toThrow();
}
render() {
return <div />;
}
}
const instance = ReactDOM.render(<Component />, container);
instance.setState({value: 1});
ReactDOM.unmountComponentAtNode(container);
expect(cbCalled).toBe(false);
});
it('should warn when rendering a class with a render method that does not extend React.Component', () => {
const container = document.createElement('div');
class ClassWithRenderNotExtended {
render() {
return <div />;
}
}
expect(() => {
expect(() => {
ReactDOM.render(<ClassWithRenderNotExtended />, container);
}).toThrow(TypeError);
}).toWarnDev(
'Warning: The <ClassWithRenderNotExtended /> component appears to have a render method, ' +
"but doesn't extend React.Component. This is likely to cause errors. " +
'Change ClassWithRenderNotExtended to extend React.Component instead.',
{withoutStack: true},
);
// Test deduplication
expect(() => {
ReactDOM.render(<ClassWithRenderNotExtended />, container);
}).toThrow(TypeError);
});
it('should warn about `setState` in render', () => {
const container = document.createElement('div');
let renderedState = -1;
let renderPasses = 0;
class Component extends React.Component {
state = {value: 0};
render() {
renderPasses++;
renderedState = this.state.value;
if (this.state.value === 0) {
this.setState({value: 1});
}
return <div />;
}
}
let instance;
expect(() => {
instance = ReactDOM.render(<Component />, container);
}).toWarnDev(
'Cannot update during an existing state transition (such as within ' +
'`render`). Render methods should be a pure function of props and state.',
{withoutStack: true},
);
// The setState call is queued and then executed as a second pass. This
// behavior is undefined though so we're free to change it to suit the
// implementation details.
expect(renderPasses).toBe(2);
expect(renderedState).toBe(1);
expect(instance.state.value).toBe(1);
// Forcing a rerender anywhere will cause the update to happen.
const instance2 = ReactDOM.render(<Component prop={123} />, container);
expect(instance).toBe(instance2);
expect(renderedState).toBe(1);
expect(instance2.state.value).toBe(1);
// Test deduplication; (no additional warnings are expected).
ReactDOM.unmountComponentAtNode(container);
ReactDOM.render(<Component prop={123} />, container);
});
it('should warn about `setState` in getChildContext', () => {
const container = document.createElement('div');
let renderPasses = 0;
class Component extends React.Component {
state = {value: 0};
getChildContext() {
if (this.state.value === 0) {
this.setState({value: 1});
}
}
render() {
renderPasses++;
return <div />;
}
}
Component.childContextTypes = {};
let instance;
expect(() => {
instance = ReactDOM.render(<Component />, container);
}).toWarnDev(
'Warning: setState(...): Cannot call setState() inside getChildContext()',
{withoutStack: true},
);
expect(renderPasses).toBe(2);
expect(instance.state.value).toBe(1);
// Test deduplication; (no additional warnings are expected).
ReactDOM.unmountComponentAtNode(container);
ReactDOM.render(<Component />, container);
});
it('should cleanup even if render() fatals', () => {
class BadComponent extends React.Component {
render() {
throw new Error();
}
}
let instance = <BadComponent />;
expect(ReactCurrentOwner.current).toBe(null);
expect(() => {
instance = ReactTestUtils.renderIntoDocument(instance);
}).toThrow();
expect(ReactCurrentOwner.current).toBe(null);
});
it('should call componentWillUnmount before unmounting', () => {
const container = document.createElement('div');
let innerUnmounted = false;
class Component extends React.Component {
render() {
return (
<div>
<Inner />
Text
</div>
);
}
}
class Inner extends React.Component {
componentWillUnmount() {
innerUnmounted = true;
}
render() {
return <div />;
}
}
ReactDOM.render(<Component />, container);
ReactDOM.unmountComponentAtNode(container);
expect(innerUnmounted).toBe(true);
});
it('should warn when shouldComponentUpdate() returns undefined', () => {
class Component extends React.Component {
state = {bogus: false};
shouldComponentUpdate() {
return undefined;
}
render() {
return <div />;
}
}
const instance = ReactTestUtils.renderIntoDocument(<Component />);
expect(() => instance.setState({bogus: true})).toWarnDev(
'Warning: Component.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.',
{withoutStack: true},
);
});
it('should warn when componentDidUnmount method is defined', () => {
class Component extends React.Component {
componentDidUnmount = () => {};
render() {
return <div />;
}
}
expect(() => ReactTestUtils.renderIntoDocument(<Component />)).toWarnDev(
'Warning: Component has a method called ' +
'componentDidUnmount(). But there is no such lifecycle method. ' +
'Did you mean componentWillUnmount()?',
{withoutStack: true},
);
});
it('should warn when componentDidReceiveProps method is defined', () => {
class Component extends React.Component {
componentDidReceiveProps = () => {};
render() {
return <div />;
}
}
expect(() => ReactTestUtils.renderIntoDocument(<Component />)).toWarnDev(
'Warning: Component has a method called ' +
'componentDidReceiveProps(). But there is no such lifecycle method. ' +
'If you meant to update the state in response to changing props, ' +
'use componentWillReceiveProps(). If you meant to fetch data or ' +
'run side-effects or mutations after React has updated the UI, use componentDidUpdate().',
{withoutStack: true},
);
});
it('should warn when defaultProps was defined as an instance property', () => {
class Component extends React.Component {
constructor(props) {
super(props);
this.defaultProps = {name: 'Abhay'};
}
render() {
return <div />;
}
}
expect(() => ReactTestUtils.renderIntoDocument(<Component />)).toWarnDev(
'Warning: Setting defaultProps as an instance property on Component is not supported ' +
'and will be ignored. Instead, define defaultProps as a static property on Component.',
{withoutStack: true},
);
});
it('should pass context to children when not owner', () => {
class Parent extends React.Component {
render() {
return (
<Child>
<Grandchild />
</Child>
);
}
}
class Child extends React.Component {
static childContextTypes = {
foo: PropTypes.string,
};
getChildContext() {
return {
foo: 'bar',
};
}
render() {
return React.Children.only(this.props.children);
}
}
class Grandchild extends React.Component {
static contextTypes = {
foo: PropTypes.string,
};
render() {
return <div>{this.context.foo}</div>;
}
}
const component = ReactTestUtils.renderIntoDocument(<Parent />);
expect(ReactDOM.findDOMNode(component).innerHTML).toBe('bar');
});
it('should skip update when rerendering element in container', () => {
class Parent extends React.Component {
render() {
return <div>{this.props.children}</div>;
}
}
let childRenders = 0;
class Child extends React.Component {
render() {
childRenders++;
return <div />;
}
}
const container = document.createElement('div');
const child = <Child />;
ReactDOM.render(<Parent>{child}</Parent>, container);
ReactDOM.render(<Parent>{child}</Parent>, container);
expect(childRenders).toBe(1);
});
it('should pass context when re-rendered for static child', () => {
let parentInstance = null;
let childInstance = null;
class Parent extends React.Component {
static childContextTypes = {
foo: PropTypes.string,
flag: PropTypes.bool,
};
state = {
flag: false,
};
getChildContext() {
return {
foo: 'bar',
flag: this.state.flag,
};
}
render() {
return React.Children.only(this.props.children);
}
}
class Middle extends React.Component {
render() {
return this.props.children;
}
}
class Child extends React.Component {
static contextTypes = {
foo: PropTypes.string,
flag: PropTypes.bool,
};
render() {
childInstance = this;
return <span>Child</span>;
}
}
parentInstance = ReactTestUtils.renderIntoDocument(
<Parent>
<Middle>
<Child />
</Middle>
</Parent>,
);
expect(parentInstance.state.flag).toBe(false);
expect(childInstance.context).toEqual({foo: 'bar', flag: false});
parentInstance.setState({flag: true});
expect(parentInstance.state.flag).toBe(true);
expect(childInstance.context).toEqual({foo: 'bar', flag: true});
});
it('should pass context when re-rendered for static child within a composite component', () => {
class Parent extends React.Component {
static childContextTypes = {
flag: PropTypes.bool,
};
state = {
flag: true,
};
getChildContext() {
return {
flag: this.state.flag,
};
}
render() {
return <div>{this.props.children}</div>;
}
}
class Child extends React.Component {
static contextTypes = {
flag: PropTypes.bool,
};
render() {
return <div />;
}
}
class Wrapper extends React.Component {
render() {
return (
<Parent ref="parent">
<Child ref="child" />
</Parent>
);
}
}
const wrapper = ReactTestUtils.renderIntoDocument(<Wrapper />);
expect(wrapper.refs.parent.state.flag).toEqual(true);
expect(wrapper.refs.child.context).toEqual({flag: true});
// We update <Parent /> while <Child /> is still a static prop relative to this update
wrapper.refs.parent.setState({flag: false});
expect(wrapper.refs.parent.state.flag).toEqual(false);
expect(wrapper.refs.child.context).toEqual({flag: false});
});
it('should pass context transitively', () => {
let childInstance = null;
let grandchildInstance = null;
class Parent extends React.Component {
static childContextTypes = {
foo: PropTypes.string,
depth: PropTypes.number,
};
getChildContext() {
return {
foo: 'bar',
depth: 0,
};
}
render() {
return <Child />;
}
}
class Child extends React.Component {
static contextTypes = {
foo: PropTypes.string,
depth: PropTypes.number,
};
static childContextTypes = {
depth: PropTypes.number,
};
getChildContext() {
return {
depth: this.context.depth + 1,
};
}
render() {
childInstance = this;
return <Grandchild />;
}
}
class Grandchild extends React.Component {
static contextTypes = {
foo: PropTypes.string,
depth: PropTypes.number,
};
render() {
grandchildInstance = this;
return <div />;
}
}
ReactTestUtils.renderIntoDocument(<Parent />);
expect(childInstance.context).toEqual({foo: 'bar', depth: 0});
expect(grandchildInstance.context).toEqual({foo: 'bar', depth: 1});
});
it('should pass context when re-rendered', () => {
let parentInstance = null;
let childInstance = null;
class Parent extends React.Component {
static childContextTypes = {
foo: PropTypes.string,
depth: PropTypes.number,
};
state = {
flag: false,
};
getChildContext() {
return {
foo: 'bar',
depth: 0,
};
}
render() {
let output = <Child />;
if (!this.state.flag) {
output = <span>Child</span>;
}
return output;
}
}
class Child extends React.Component {
static contextTypes = {
foo: PropTypes.string,
depth: PropTypes.number,
};
render() {
childInstance = this;
return <span>Child</span>;
}
}
parentInstance = ReactTestUtils.renderIntoDocument(<Parent />);
expect(childInstance).toBeNull();
expect(parentInstance.state.flag).toBe(false);
ReactDOM.unstable_batchedUpdates(function() {
parentInstance.setState({flag: true});
});
expect(parentInstance.state.flag).toBe(true);
expect(childInstance.context).toEqual({foo: 'bar', depth: 0});
});
it('unmasked context propagates through updates', () => {
class Leaf extends React.Component {
static contextTypes = {
foo: PropTypes.string.isRequired,
};
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
expect('foo' in nextContext).toBe(true);
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
expect('foo' in nextContext).toBe(true);
return true;
}
render() {
return <span>{this.context.foo}</span>;
}
}
class Intermediary extends React.Component {
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
expect('foo' in nextContext).toBe(false);
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
expect('foo' in nextContext).toBe(false);
return true;
}
render() {
return <Leaf />;
}
}
class Parent extends React.Component {
static childContextTypes = {
foo: PropTypes.string,
};
getChildContext() {
return {
foo: this.props.cntxt,
};
}
render() {
return <Intermediary />;
}
}
const div = document.createElement('div');
ReactDOM.render(<Parent cntxt="noise" />, div);
expect(div.children[0].innerHTML).toBe('noise');
div.children[0].innerHTML = 'aliens';
div.children[0].id = 'aliens';
expect(div.children[0].innerHTML).toBe('aliens');
expect(div.children[0].id).toBe('aliens');
ReactDOM.render(<Parent cntxt="bar" />, div);
expect(div.children[0].innerHTML).toBe('bar');
expect(div.children[0].id).toBe('aliens');
});
it('should trigger componentWillReceiveProps for context changes', () => {
let contextChanges = 0;
let propChanges = 0;
class GrandChild extends React.Component {
static contextTypes = {
foo: PropTypes.string.isRequired,
};
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
expect('foo' in nextContext).toBe(true);
if (nextProps !== this.props) {
propChanges++;
}
if (nextContext !== this.context) {
contextChanges++;
}
}
render() {
return <span className="grand-child">{this.props.children}</span>;
}
}
class ChildWithContext extends React.Component {
static contextTypes = {
foo: PropTypes.string.isRequired,
};
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
expect('foo' in nextContext).toBe(true);
if (nextProps !== this.props) {
propChanges++;
}
if (nextContext !== this.context) {
contextChanges++;
}
}
render() {
return <div className="child-with">{this.props.children}</div>;
}
}
class ChildWithoutContext extends React.Component {
UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
expect('foo' in nextContext).toBe(false);
if (nextProps !== this.props) {
propChanges++;
}
if (nextContext !== this.context) {
contextChanges++;
}
}
render() {
return <div className="child-without">{this.props.children}</div>;
}
}
class Parent extends React.Component {
static childContextTypes = {
foo: PropTypes.string,
};
state = {
foo: 'abc',
};
getChildContext() {
return {
foo: this.state.foo,
};
}
render() {
return <div className="parent">{this.props.children}</div>;
}
}
const div = document.createElement('div');
let parentInstance = null;
ReactDOM.render(
<Parent ref={inst => (parentInstance = inst)}>
<ChildWithoutContext>
A1
<GrandChild>A2</GrandChild>
</ChildWithoutContext>
<ChildWithContext>
B1
<GrandChild>B2</GrandChild>
</ChildWithContext>
</Parent>,
div,
);
parentInstance.setState({
foo: 'def',
});
expect(propChanges).toBe(0);
expect(contextChanges).toBe(3); // ChildWithContext, GrandChild x 2
});
it('should disallow nested render calls', () => {
class Inner extends React.Component {
render() {
return <div />;
}
}
class Outer extends React.Component {
render() {
ReactTestUtils.renderIntoDocument(<Inner />);
return <div />;
}
}
expect(() => ReactTestUtils.renderIntoDocument(<Outer />)).toWarnDev(
'Render methods should be a pure function of props and state; ' +
'triggering nested component updates from render is not allowed. If ' +
'necessary, trigger nested updates in componentDidUpdate.\n\nCheck the ' +
'render method of Outer.',
{withoutStack: true},
);
});
it('only renders once if updated in componentWillReceiveProps', () => {
let renders = 0;
class Component extends React.Component {
state = {updated: false};
UNSAFE_componentWillReceiveProps(props) {
expect(props.update).toBe(1);
expect(renders).toBe(1);
this.setState({updated: true});
expect(renders).toBe(1);
}
render() {
renders++;
return <div />;
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<Component update={0} />, container);
expect(renders).toBe(1);
expect(instance.state.updated).toBe(false);
ReactDOM.render(<Component update={1} />, container);
expect(renders).toBe(2);
expect(instance.state.updated).toBe(true);
});
it('only renders once if updated in componentWillReceiveProps when batching', () => {
let renders = 0;
class Component extends React.Component {
state = {updated: false};
UNSAFE_componentWillReceiveProps(props) {
expect(props.update).toBe(1);
expect(renders).toBe(1);
this.setState({updated: true});
expect(renders).toBe(1);
}
render() {
renders++;
return <div />;
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<Component update={0} />, container);
expect(renders).toBe(1);
expect(instance.state.updated).toBe(false);
ReactDOM.unstable_batchedUpdates(() => {
ReactDOM.render(<Component update={1} />, container);
});
expect(renders).toBe(2);
expect(instance.state.updated).toBe(true);
});
it('should update refs if shouldComponentUpdate gives false', () => {
class Static extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
return <div>{this.props.children}</div>;
}
}
class Component extends React.Component {
render() {
if (this.props.flipped) {
return (
<div>
<Static ref="static0" key="B">
B (ignored)
</Static>
<Static ref="static1" key="A">
A (ignored)
</Static>
</div>
);
} else {
return (
<div>
<Static ref="static0" key="A">
A
</Static>
<Static ref="static1" key="B">
B
</Static>
</div>
);
}
}
}
const container = document.createElement('div');
const comp = ReactDOM.render(<Component flipped={false} />, container);
expect(ReactDOM.findDOMNode(comp.refs.static0).textContent).toBe('A');
expect(ReactDOM.findDOMNode(comp.refs.static1).textContent).toBe('B');
// When flipping the order, the refs should update even though the actual
// contents do not
ReactDOM.render(<Component flipped={true} />, container);
expect(ReactDOM.findDOMNode(comp.refs.static0).textContent).toBe('B');
expect(ReactDOM.findDOMNode(comp.refs.static1).textContent).toBe('A');
});
it('should allow access to findDOMNode in componentWillUnmount', () => {
let a = null;
let b = null;
class Component extends React.Component {
componentDidMount() {
a = ReactDOM.findDOMNode(this);
expect(a).not.toBe(null);
}
componentWillUnmount() {
b = ReactDOM.findDOMNode(this);
expect(b).not.toBe(null);
}
render() {
return <div />;
}
}
const container = document.createElement('div');
expect(a).toBe(container.firstChild);
ReactDOM.render(<Component />, container);
ReactDOM.unmountComponentAtNode(container);
expect(a).toBe(b);
});
it('context should be passed down from the parent', () => {
class Parent extends React.Component {
static childContextTypes = {
foo: PropTypes.string,
};
getChildContext() {
return {
foo: 'bar',
};
}
render() {
return <div>{this.props.children}</div>;
}
}
class Component extends React.Component {
static contextTypes = {
foo: PropTypes.string.isRequired,
};
render() {
return <div />;
}
}
const div = document.createElement('div');
ReactDOM.render(
<Parent>
<Component />
</Parent>,
div,
);
});
it('should replace state', () => {
class Moo extends React.Component {
state = {x: 1};
render() {
return <div />;
}
}
const moo = ReactTestUtils.renderIntoDocument(<Moo />);
// No longer a public API, but we can test that it works internally by
// reaching into the updater.
moo.updater.enqueueReplaceState(moo, {y: 2});
expect('x' in moo.state).toBe(false);
expect(moo.state.y).toBe(2);
});
it('should support objects with prototypes as state', () => {
const NotActuallyImmutable = function(str) {
this.str = str;
};
NotActuallyImmutable.prototype.amIImmutable = function() {
return true;
};
class Moo extends React.Component {
state = new NotActuallyImmutable('first');
// No longer a public API, but we can test that it works internally by
// reaching into the updater.
_replaceState = update => this.updater.enqueueReplaceState(this, update);
render() {
return <div />;
}
}
const moo = ReactTestUtils.renderIntoDocument(<Moo />);
expect(moo.state.str).toBe('first');
expect(moo.state.amIImmutable()).toBe(true);
const secondState = new NotActuallyImmutable('second');
moo._replaceState(secondState);
expect(moo.state.str).toBe('second');
expect(moo.state.amIImmutable()).toBe(true);
expect(moo.state).toBe(secondState);
moo.setState({str: 'third'});
expect(moo.state.str).toBe('third');
// Here we lose the prototype.
expect(moo.state.amIImmutable).toBe(undefined);
// When more than one state update is enqueued, we have the same behavior
const fifthState = new NotActuallyImmutable('fifth');
ReactDOM.unstable_batchedUpdates(function() {
moo.setState({str: 'fourth'});
moo._replaceState(fifthState);
});
expect(moo.state).toBe(fifthState);
// When more than one state update is enqueued, we have the same behavior
const sixthState = new NotActuallyImmutable('sixth');
ReactDOM.unstable_batchedUpdates(function() {
moo._replaceState(sixthState);
moo.setState({str: 'seventh'});
});
expect(moo.state.str).toBe('seventh');
expect(moo.state.amIImmutable).toBe(undefined);
});
it('should not warn about unmounting during unmounting', () => {
const container = document.createElement('div');
const layer = document.createElement('div');
class Component extends React.Component {
componentDidMount() {
ReactDOM.render(<div />, layer);
}
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(layer);
}
render() {
return <div />;
}
}
class Outer extends React.Component {
render() {
return <div>{this.props.children}</div>;
}
}
ReactDOM.render(
<Outer>
<Component />
</Outer>,
container,
);
ReactDOM.render(<Outer />, container);
});
it('should warn when mutated props are passed', () => {
const container = document.createElement('div');
class Foo extends React.Component {
constructor(props) {
const _props = {idx: props.idx + '!'};
super(_props);
}
render() {
return <span />;
}
}
expect(() => ReactDOM.render(<Foo idx="qwe" />, container)).toWarnDev(
'Foo(...): When calling super() in `Foo`, make sure to pass ' +
"up the same props that your component's constructor was passed.",
{withoutStack: true},
);
});
it('should only call componentWillUnmount once', () => {
let app;
let count = 0;
class App extends React.Component {
render() {
if (this.props.stage === 1) {
return <UnunmountableComponent />;
} else {
return null;
}
}
}
class UnunmountableComponent extends React.Component {
componentWillUnmount() {
app.setState({});
count++;
throw Error('always fails');
}
render() {
return <div>Hello {this.props.name}</div>;
}
}
const container = document.createElement('div');
const setRef = ref => {
if (ref) {
app = ref;
}
};
expect(() => {
ReactDOM.render(<App ref={setRef} stage={1} />, container);
ReactDOM.render(<App ref={setRef} stage={2} />, container);
}).toThrow();
expect(count).toBe(1);
});
it('prepares new child before unmounting old', () => {
const log = [];
class Spy extends React.Component {
UNSAFE_componentWillMount() {
log.push(this.props.name + ' componentWillMount');
}
render() {
log.push(this.props.name + ' render');
return <div />;
}
componentDidMount() {
log.push(this.props.name + ' componentDidMount');
}
componentWillUnmount() {
log.push(this.props.name + ' componentWillUnmount');
}
}
class Wrapper extends React.Component {
render() {
return <Spy key={this.props.name} name={this.props.name} />;
}
}
const container = document.createElement('div');
ReactDOM.render(<Wrapper name="A" />, container);
ReactDOM.render(<Wrapper name="B" />, container);
expect(log).toEqual([
'A componentWillMount',
'A render',
'A componentDidMount',
'B componentWillMount',
'B render',
'A componentWillUnmount',
'B componentDidMount',
]);
});
it('respects a shallow shouldComponentUpdate implementation', () => {
let renderCalls = 0;
class PlasticWrap extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
color: 'green',
};
}
render() {
return <Apple color={this.state.color} ref="apple" />;
}
}
class Apple extends React.Component {
state = {
cut: false,
slices: 1,
};
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
cut() {
this.setState({
cut: true,
slices: 10,
});
}
eatSlice() {
this.setState({
slices: this.state.slices - 1,
});
}
render() {
renderCalls++;
return <div />;
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<PlasticWrap />, container);
expect(renderCalls).toBe(1);
// Do not re-render based on props
instance.setState({color: 'green'});
expect(renderCalls).toBe(1);
// Re-render based on props
instance.setState({color: 'red'});
expect(renderCalls).toBe(2);
// Re-render base on state
instance.refs.apple.cut();
expect(renderCalls).toBe(3);
// No re-render based on state
instance.refs.apple.cut();
expect(renderCalls).toBe(3);
// Re-render based on state again
instance.refs.apple.eatSlice();
expect(renderCalls).toBe(4);
});
it('does not do a deep comparison for a shallow shouldComponentUpdate implementation', () => {
function getInitialState() {
return {
foo: [1, 2, 3],
bar: {a: 4, b: 5, c: 6},
};
}
let renderCalls = 0;
const initialSettings = getInitialState();
class Component extends React.Component {
state = initialSettings;
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
render() {
renderCalls++;
return <div />;
}
}
const container = document.createElement('div');
const instance = ReactDOM.render(<Component />, container);
expect(renderCalls).toBe(1);
// Do not re-render if state is equal
const settings = {
foo: initialSettings.foo,
bar: initialSettings.bar,
};
instance.setState(settings);
expect(renderCalls).toBe(1);
// Re-render because one field changed
initialSettings.foo = [1, 2, 3];
instance.setState(initialSettings);
expect(renderCalls).toBe(2);
// Re-render because the object changed
instance.setState(getInitialState());
expect(renderCalls).toBe(3);
});
it('should call setState callback with no arguments', () => {
let mockArgs;
class Component extends React.Component {
componentDidMount() {
this.setState({}, (...args) => (mockArgs = args));
}
render() {
return false;
}
}
ReactTestUtils.renderIntoDocument(<Component />);
expect(mockArgs.length).toEqual(0);
});
it('this.state should be updated on setState callback inside componentWillMount', () => {
const div = document.createElement('div');
let stateSuccessfullyUpdated = false;
class Component extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
hasUpdatedState: false,
};
}
UNSAFE_componentWillMount() {
this.setState(
{hasUpdatedState: true},
() => (stateSuccessfullyUpdated = this.state.hasUpdatedState),
);
}
render() {
return <div>{this.props.children}</div>;
}
}
ReactDOM.render(<Component />, div);
expect(stateSuccessfullyUpdated).toBe(true);
});
it('should call the setState callback even if shouldComponentUpdate = false', done => {
const mockFn = jest.fn().mockReturnValue(false);
const div = document.createElement('div');
let instance;
class Component extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
hasUpdatedState: false,
};
}
UNSAFE_componentWillMount() {
instance = this;
}
shouldComponentUpdate() {
return mockFn();
}
render() {
return <div>{this.state.hasUpdatedState}</div>;
}
}
ReactDOM.render(<Component />, div);
expect(instance).toBeDefined();
expect(mockFn).not.toBeCalled();
instance.setState({hasUpdatedState: true}, () => {
expect(mockFn).toBeCalled();
expect(instance.state.hasUpdatedState).toBe(true);
done();
});
});
it('should return a meaningful warning when constructor is returned', () => {
class RenderTextInvalidConstructor extends React.Component {
constructor(props) {
super(props);
return {something: false};
}
render() {
return <div />;
}
}
expect(() => {
expect(() => {
ReactTestUtils.renderIntoDocument(<RenderTextInvalidConstructor />);
}).toThrow();
}).toWarnDev(
[
// Expect two errors because invokeGuardedCallback will dispatch an error event,
// Causing the warning to be logged again.
'Warning: RenderTextInvalidConstructor(...): No `render` method found on the returned component instance: ' +
'did you accidentally return an object from the constructor?',
'Warning: RenderTextInvalidConstructor(...): No `render` method found on the returned component instance: ' +
'did you accidentally return an object from the constructor?',
],
{withoutStack: true},
);
});
it('should warn about reassigning this.props while rendering', () => {
class Bad extends React.Component {
componentDidMount() {}
componentDidUpdate() {}
render() {
this.props = {...this.props};
return null;
}
}
const container = document.createElement('div');
expect(() => {
ReactDOM.render(<Bad />, container);
}).toWarnDev(
'It looks like Bad is reassigning its own `this.props` while rendering. ' +
'This is not supported and can lead to confusing bugs.',
);
});
it('should return error if render is not defined', () => {
class RenderTestUndefinedRender extends React.Component {}
expect(() => {
expect(() => {
ReactTestUtils.renderIntoDocument(<RenderTestUndefinedRender />);
}).toThrow();
}).toWarnDev(
[
// Expect two errors because invokeGuardedCallback will dispatch an error event,
// Causing the warning to be logged again.
'Warning: RenderTestUndefinedRender(...): No `render` method found on the returned ' +
'component instance: you may have forgotten to define `render`.',
'Warning: RenderTestUndefinedRender(...): No `render` method found on the returned ' +
'component instance: you may have forgotten to define `render`.',
],
{withoutStack: true},
);
});
// Regression test for accidental breaking change
// https://github.com/facebook/react/issues/13580
it('should support classes shadowing isReactComponent', () => {
class Shadow extends React.Component {
isReactComponent() {}
render() {
return <div />;
}
}
const container = document.createElement('div');
ReactDOM.render(<Shadow />, container);
expect(container.firstChild.tagName).toBe('DIV');
});
});
| bsd-3-clause |
datastream/probab | cmd/poissonRateBayes/poissonRateBayes.go | 712 | // Summary of the posterior distribution of the Poisson parameter.
package main
import (
"github.com/datastream/probab/bayes"
"fmt"
)
// Summary of the posterior distribution of the Poisson parameter.
func main() {
var (
x, n int64
r, v float64
)
fmt.Scanf("%d %d %f %f", &x, &n, &r, &v)
// fmt.Println("%d %d %f %f", x, n, r, v)
pr := []float64{0.005, 0.01, 0.025, 0.05, 0.5, 0.95, 0.975, 0.99, 0.995}
if r < 0 || v < 0 {
panic("Shape parameter r and rate parameter v must be greater than or equal to zero")
}
fmt.Println("\nProb.\t\tQuantile \n")
for i := 0; i < 9; i++ {
qtl := bayes.PoissonLambdaQtlGPri(x, n, r, v)
fmt.Println(pr[i], "\t\t", qtl(pr[i]))
}
fmt.Println("\n")
}
| bsd-3-clause |
expandjs/expandjs | lib/isEquivalent.js | 1641 | /**
* @license
* Copyright (c) 2017 The expand.js authors. All rights reserved.
* This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
* The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
*/
const isFalse = require('./isFalse'),
isObject = require('./isObject'),
isUseful = require('./isUseful');
/**
* Performs a JSON comparison between two values to determine if they are equivalent.
*
* ```js
* let object = {name: 'fred', age: undefined},
* other = {name: 'fred', age: null};
*
* object === other;
* // => false
*
* XP.isEqual(object, other);
* // => false
*
* XP.isEquivalent(object, other);
* // => true
* ```
*
* @function isEquivalent
* @since 1.0.0
* @category tester
* @description Performs a JSON comparison between two values to determine if they are equivalent
* @source https://github.com/expandjs/expandjs/blog/master/lib/isEquivalent.js
*
* @param {*} value The target value
* @param {*} other The other value to compare
* @returns {boolean} Returns `true` or `false` based on the check
*/
module.exports = function isEquivalent(value, other) {
// Polisher
function polish(key, val) {
if (isFalse(val) || !isUseful(val)) { return; }
if (isObject(val)) { return Object.keys(val).sort().reduce((obj, key) => { obj[key] = val[key]; return obj; }, {}); }
return val;
}
// Returning
return JSON.stringify(value, polish) === JSON.stringify(other, polish);
};
| bsd-3-clause |
NCIP/digital-model-repository | dmr-tests/src/org/cvit/cabig/dmr/integration/dmrservice/AbstractDmrServiceTests.java | 7316 | /*L
* Copyright The General Hospital Corporation d/b/a Massachusetts General Hospital
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/digital-model-repository/LICENSE.txt for details.
*/
package org.cvit.cabig.dmr.integration.dmrservice ;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.cvit.cabig.dmr.anzo.AnzoDMRService;
import org.cvit.cabig.dmr.anzo.AnzoIo;
import org.cvit.cabig.dmr.anzo.AnzoIoException;
import org.cvit.cabig.dmr.domain.DataClassification;
import org.cvit.cabig.dmr.domain.Entry;
import org.cvit.cabig.dmr.domain.Image;
import org.cvit.cabig.dmr.domain.Organization;
import org.cvit.cabig.dmr.domain.Paper;
import org.cvit.cabig.dmr.domain.Reference;
import org.cvit.cabig.dmr.integration.InMemoryDmrFactory;
import org.junit.Before;
import org.openanzo.client.RemoteGraph;
import org.openanzo.common.exceptions.AnzoException;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AbstractDmrServiceTests {
public Logger logger = LoggerFactory.getLogger(this.getClass()) ;
public static final String PI = "pi" ;
public static final String CONTRIBUTOR = "co" ;
public static final String ENTRY2_ID = "urn:lsid:telar.cambridgesemantics.com:telar0.544376318697641" ;
//Entry with Contributor "co", Published to "reader"
protected Entry ENTRY1 ;
protected Image DATA1 ;
protected Paper REF1 ;
protected Organization DOD ;
@Before
public void initTestDataIds() {
ENTRY1 = new Entry() ;
ENTRY1.setId("urn:lsid:telar.cambridgesemantics.com:telar0.6345350254148658") ;
DATA1 = new Image() ;
DATA1.setId("urn:lsid:telar.cambridgesemantics.com:telar0.2224178270121437") ;
REF1 = new Paper() ;
REF1.setId("urn:lsid:telar.cambridgesemantics.com:telar0.24492447633762038") ;
DOD = new Organization() ;
DOD.setId("urn:lsid:telar.cambridgesemantics.com:cvit#dod") ;
}
private InMemoryDmrFactory factory = new InMemoryDmrFactory() ;
public AbstractDmrServiceTests() {
super() ;
}
protected File getDataFile(String... path) {
StringBuilder relativePath = new StringBuilder() ;
for (String part : path) {
relativePath.append(part + File.separatorChar) ;
}
relativePath.deleteCharAt(relativePath.length() - 1) ;
return new File(getDataDirectory(), relativePath.toString()) ;
}
protected File getDataDirectory() {
return new File("./test-data/dmrservice-tests") ;
}
@Before
public void initDmrService() {
AnzoIo anzoIo = new AnzoIo() ;
try {
anzoIo.resetAnzo(factory.getDatasetService(), getDataFile("init.ttl"), getDataFile("manifest.ttl")) ;
} catch (AnzoIoException e) {
throw new RuntimeException("Exception while reseting dataset service.", e) ;
}
}
protected AnzoDMRService getService() {
return factory.getService() ;
}
protected static void assertEqualEntries(Entry expected, Entry actual) {
assertEqualAttributes("id", expected.getId(), actual.getId()) ;
assertEqualAttributes("title", expected.getTitle(), actual.getTitle()) ;
assertEqualAttributes("description", expected.getDescription(), actual.getDescription()) ;
assertEqualAttributes("abstract", expected.getAbstractText(), actual.getAbstractText()) ;
assertEqualAttributes("concept", expected.getConcept(), actual.getConcept()) ;
assertEqualAttributes("hypothesis", expected.getHypothesis(), actual.getHypothesis()) ;
assertEqualAttributes("conclusion", expected.getConclusion(), actual.getConclusion()) ;
assertEqualAttributes("note", expected.getNote(), actual.getNote()) ;
assertEqualAttributes("keywords", asSet(expected.getKeywords()), asSet(actual.getKeywords())) ;
}
protected static void assertEqualData(DataClassification expected, DataClassification actual) {
assertEqualAttributes("id", expected.getId(), actual.getId()) ;
assertEqualAttributes("title", expected.getTitle(), actual.getTitle()) ;
assertEqualAttributes("description", expected.getDescription(), actual.getDescription()) ;
assertEqualAttributes("source", expected.getSource(), actual.getSource()) ;
assertEqualAttributes("comment", expected.getComment(), actual.getComment()) ;
}
protected static void assertEqualReferences(Reference expected, Reference actual) {
assertEqualAttributes("id", expected.getId(), actual.getId()) ;
assertEqualAttributes("title", expected.getTitle(), actual.getTitle()) ;
assertEqualAttributes("description", expected.getDescription(), actual.getDescription()) ;
assertEqualAttributes("source", expected.getSource(), actual.getSource()) ;
assertEqualAttributes("comment", expected.getComment(), actual.getComment()) ;
}
protected static void assertEqualAttributes(String attr, Object expected, Object actual) {
if (expected == null) {
if (actual != null) {
throw new AssertionError("Attribute " + attr + ": Expected: null; but was: " + actual) ;
}
return ;
}
if (!expected.equals(actual)) {
throw new AssertionError("Attribute " + attr + ": Expected: " + expected + "; but was: " + actual) ;
}
}
protected void assertHasStatements(URI graphUri, Statement... statements) {
RemoteGraph graph = null ;
try {
graph = factory.getSystemService().getRemoteGraph(graphUri, false) ;
for (Statement stmt : statements) {
if (!graph.contains(stmt)) {
throw new AssertionError("Graph does not have statement: " + stmt + ".") ;
}
}
} catch (AnzoException e) {
throw new RuntimeException("Exception checking graph: " + graphUri + ".", e) ;
} finally {
if (graph != null) {
graph.close() ;
}
}
}
protected void dumpDatasetService(File outputDir) {
try {
new AnzoIo().dumpAll(factory.getSystemService(), outputDir) ;
} catch (Exception e) {
throw new RuntimeException("Exception while dumping dataset service.", e) ;
}
}
protected Statement statement(Resource subject, URI predicate, Value object) {
return getValueFactory().createStatement(subject, predicate, object) ;
}
protected URI uri(String uri) {
return getValueFactory().createURI(uri) ;
}
private ValueFactory getValueFactory() {
return factory.getDatasetService().getValueFactory() ;
}
private static <T> Set<T> asSet(Collection<T> objects) {
if (objects == null) {
return null ;
}
Set<T> result = new HashSet<T>() ;
result.addAll(objects) ;
return result ;
}
}
| bsd-3-clause |
rgarro/zf2 | library/Zend/Db/Adapter/Pdo/Pgsql.php | 11951 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @namespace
*/
namespace Zend\Db\Adapter\Pdo;
use Zend\Db;
use Zend\Db\Adapter;
/**
* Class for connecting to PostgreSQL databases and performing common operations.
*
* @uses \Zend\Db\Db
* @uses \Zend\Db\Adapter\Exception
* @uses \Zend\Db\Adapter\Pdo\AbstractPdo
* @category Zend
* @package Zend_Db
* @subpackage Adapter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Pgsql extends \Zend\Db\Adapter\AbstractPdoAdapter
{
/**
* Pdo type.
*
* @var string
*/
protected $_pdoType = 'pgsql';
/**
* Keys are UPPERCASE SQL datatypes or the constants
* Zend_Db::INT_TYPE, Zend_Db::BIGINT_TYPE, or Zend_Db::FLOAT_TYPE.
*
* Values are:
* 0 = 32-bit integer
* 1 = 64-bit integer
* 2 = float or decimal
*
* @var array Associative array of datatypes to values 0, 1, or 2.
*/
protected $_numericDataTypes = array(
Db\Db::INT_TYPE => Db\Db::INT_TYPE,
Db\Db::BIGINT_TYPE => Db\Db::BIGINT_TYPE,
Db\Db::FLOAT_TYPE => Db\Db::FLOAT_TYPE,
'INTEGER' => Db\Db::INT_TYPE,
'SERIAL' => Db\Db::INT_TYPE,
'SMALLINT' => Db\Db::INT_TYPE,
'BIGINT' => Db\Db::BIGINT_TYPE,
'BIGSERIAL' => Db\Db::BIGINT_TYPE,
'DECIMAL' => Db\Db::FLOAT_TYPE,
'DOUBLE PRECISION' => Db\Db::FLOAT_TYPE,
'NUMERIC' => Db\Db::FLOAT_TYPE,
'REAL' => Db\Db::FLOAT_TYPE
);
/**
* Creates a Pdo object and connects to the database.
*
* @return void
* @throws \Zend\Db\Adapter\Exception
*/
protected function _connect()
{
if ($this->_connection) {
return;
}
parent::_connect();
if (!empty($this->_config['charset'])) {
$sql = "SET NAMES '" . $this->_config['charset'] . "'";
$this->_connection->exec($sql);
}
}
/**
* Returns a list of the tables in the database.
*
* @return array
*/
public function listTables()
{
// @todo use a better query with joins instead of subqueries
$sql = "SELECT c.relname AS table_name "
. "FROM pg_class c, pg_user u "
. "WHERE c.relowner = u.usesysid AND c.relkind = 'r' "
. "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
. "AND c.relname !~ '^(pg_|sql_)' "
. "UNION "
. "SELECT c.relname AS table_name "
. "FROM pg_class c "
. "WHERE c.relkind = 'r' "
. "AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) "
. "AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) "
. "AND c.relname !~ '^pg_'";
return $this->fetchCol($sql);
}
/**
* Returns the column descriptions for a table.
*
* The return value is an associative array keyed by the column name,
* as returned by the RDBMS.
*
* The value of each array element is an associative array
* with the following keys:
*
* SCHEMA_NAME => string; name of database or schema
* TABLE_NAME => string;
* COLUMN_NAME => string; column name
* COLUMN_POSITION => number; ordinal position of column in table
* DATA_TYPE => string; SQL datatype name of column
* DEFAULT => string; default expression of column, null if none
* NULLABLE => boolean; true if column can have nulls
* LENGTH => number; length of CHAR/VARCHAR
* SCALE => number; scale of NUMERIC/DECIMAL
* PRECISION => number; precision of NUMERIC/DECIMAL
* UNSIGNED => boolean; unsigned property of an integer type
* PRIMARY => boolean; true if column is part of the primary key
* PRIMARY_POSITION => integer; position of column in primary key
* IDENTITY => integer; true if column is auto-generated with unique values
*
* @todo Discover integer unsigned property.
*
* @param string $tableName
* @param string $schemaName OPTIONAL
* @return array
*/
public function describeTable($tableName, $schemaName = null)
{
$sql = "SELECT
a.attnum,
n.nspname,
c.relname,
a.attname AS colname,
t.typname AS type,
a.atttypmod,
FORMAT_TYPE(a.atttypid, a.atttypmod) AS complete_type,
d.adsrc AS default_value,
a.attnotnull AS notnull,
a.attlen AS length,
co.contype,
ARRAY_TO_STRING(co.conkey, ',') AS conkey
FROM pg_attribute AS a
JOIN pg_class AS c ON a.attrelid = c.oid
JOIN pg_namespace AS n ON c.relnamespace = n.oid
JOIN pg_type AS t ON a.atttypid = t.oid
LEFT OUTER JOIN pg_constraint AS co ON (co.conrelid = c.oid
AND a.attnum = ANY(co.conkey) AND co.contype = 'p')
LEFT OUTER JOIN pg_attrdef AS d ON d.adrelid = c.oid AND d.adnum = a.attnum
WHERE a.attnum > 0 AND c.relname = ".$this->quote($tableName);
if ($schemaName) {
$sql .= " AND n.nspname = ".$this->quote($schemaName);
}
$sql .= ' ORDER BY a.attnum';
$stmt = $this->query($sql);
// Use FETCH_NUM so we are not dependent on the CASE attribute of the Pdo connection
$result = $stmt->fetchAll(Db\Db::FETCH_NUM);
$attnum = 0;
$nspname = 1;
$relname = 2;
$colname = 3;
$type = 4;
$atttypemod = 5;
$complete_type = 6;
$default_value = 7;
$notnull = 8;
$length = 9;
$contype = 10;
$conkey = 11;
$desc = array();
foreach ($result as $key => $row) {
$defaultValue = $row[$default_value];
if ($row[$type] == 'varchar' || $row[$type] == 'bpchar' ) {
if (preg_match('/character(?: varying)?(?:\((\d+)\))?/', $row[$complete_type], $matches)) {
if (isset($matches[1])) {
$row[$length] = $matches[1];
} else {
$row[$length] = null; // unlimited
}
}
if (preg_match("/^'(.*?)'::(?:character varying|bpchar)$/", $defaultValue, $matches)) {
$defaultValue = $matches[1];
}
}
list($primary, $primaryPosition, $identity) = array(false, null, false);
if ($row[$contype] == 'p') {
$primary = true;
$primaryPosition = array_search($row[$attnum], explode(',', $row[$conkey])) + 1;
$identity = (bool) (preg_match('/^nextval/', $row[$default_value]));
}
$desc[$this->foldCase($row[$colname])] = array(
'SCHEMA_NAME' => $this->foldCase($row[$nspname]),
'TABLE_NAME' => $this->foldCase($row[$relname]),
'COLUMN_NAME' => $this->foldCase($row[$colname]),
'COLUMN_POSITION' => $row[$attnum],
'DATA_TYPE' => $row[$type],
'DEFAULT' => $defaultValue,
'NULLABLE' => (bool) ($row[$notnull] != 't'),
'LENGTH' => $row[$length],
'SCALE' => null, // @todo
'PRECISION' => null, // @todo
'UNSIGNED' => null, // @todo
'PRIMARY' => $primary,
'PRIMARY_POSITION' => $primaryPosition,
'IDENTITY' => $identity
);
}
return $desc;
}
/**
* Adds an adapter-specific LIMIT clause to the SELECT statement.
*
* @param string $sql
* @param integer $count
* @param integer $offset OPTIONAL
* @return string
*/
public function limit($sql, $count, $offset = 0)
{
$count = intval($count);
if ($count <= 0) {
throw new Adapter\Exception("LIMIT argument count=$count is not valid");
}
$offset = intval($offset);
if ($offset < 0) {
throw new Adapter\Exception("LIMIT argument offset=$offset is not valid");
}
$sql .= " LIMIT $count";
if ($offset > 0) {
$sql .= " OFFSET $offset";
}
return $sql;
}
/**
* Return the most recent value from the specified sequence in the database.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, Db2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function lastSequenceId($sequenceName)
{
$this->_connect();
$sequenceName = trim((string) $sequenceName, $this->getQuoteIdentifierSymbol());
$value = $this->fetchOne("SELECT CURRVAL("
. $this->quote($this->quoteIdentifier($sequenceName, true))
. ")");
return $value;
}
/**
* Generate a new value from the specified sequence in the database, and return it.
* This is supported only on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, Db2). Other RDBMS brands return null.
*
* @param string $sequenceName
* @return string
*/
public function nextSequenceId($sequenceName)
{
$this->_connect();
$sequenceName = trim((string) $sequenceName, $this->getQuoteIdentifierSymbol());
$value = $this->fetchOne("SELECT NEXTVAL("
. $this->quote($this->quoteIdentifier($sequenceName, true))
. ")");
return $value;
}
/**
* Gets the last ID generated automatically by an IDENTITY/AUTOINCREMENT column.
*
* As a convention, on RDBMS brands that support sequences
* (e.g. Oracle, PostgreSQL, Db2), this method forms the name of a sequence
* from the arguments and returns the last id generated by that sequence.
* On RDBMS brands that support IDENTITY/AUTOINCREMENT columns, this method
* returns the last value generated for such a column, and the table name
* argument is disregarded.
*
* @param string $tableName OPTIONAL Name of table.
* @param string $primaryKey OPTIONAL Name of primary key column.
* @return string
*/
public function lastInsertId($tableName = null, $primaryKey = null)
{
if ($tableName !== null) {
$sequenceName = $tableName;
if ($primaryKey) {
$sequenceName .= "_$primaryKey";
}
$sequenceName .= '_seq';
return $this->lastSequenceId($sequenceName);
}
return $this->_connection->lastInsertId($tableName);
}
}
| bsd-3-clause |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractTambutranslationsBlogspotCom.py | 572 |
def extractTambutranslationsBlogspotCom(item):
'''
Parser for 'tambutranslations.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
| bsd-3-clause |
rajanishtimes/partnerapi | common/models/McpRoles.php | 929 | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "mcp_roles".
*
* @property integer $id
* @property string $role
* @property string $type
*/
class McpRoles extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'mcp_roles';
}
/**
* @return \yii\db\Connection the database connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('oldcmsdb');
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['role'], 'string', 'max' => 200],
[['type'], 'string', 'max' => 30]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'role' => 'Role',
'type' => 'Type',
];
}
}
| bsd-3-clause |
NCIP/iso21090 | code/hibernate/src/main/java/gov/nih/nci/iso21090/hibernate/node/SimpleNode.java | 1885 | //============================================================================
// Copyright 5AM Solutions, Inc
// Copyright Ekagra Software Technologies Ltd.
// Copyright Guidewire Architecture
// Copyright The Ohio State University Research Foundation
// Copyright SAIC
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/iso21090/LICENSE.txt for details.
//============================================================================
package gov.nih.nci.iso21090.hibernate.node;
import org.apache.commons.lang.builder.EqualsBuilder;
/**
* Node representing the database column mapping for sub attribute.
*
* @author patelsat
*
*/
public class SimpleNode extends Node {
private String columnName;
/**
* Default constructor.
* @param name name of the node.
*/
public SimpleNode(String name) {
setNodeType("simple");
setName(name);
}
/**
* @return name of the column.
*/
public String getColumnName() {
return columnName;
}
/**
* @param columnName name of the column.
*/
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (!(obj instanceof Node)) {
return false;
}
SimpleNode x = (SimpleNode) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(this.getColumnName(), x.getColumnName())
.isEquals();
}
/* public int compareTo(Object o) {
SimpleNode x = (SimpleNode)o;
int comparison = this.columnName.compareTo(x.columnName);
if ( comparison != 0) return comparison;
return 0;
}*/
} | bsd-3-clause |
mysoft-mall/vr-building | modules/admin/views/manage/panorama.php | 3632 | <?php
/**
* Material Page
* Created by PhpStorm.
* User: liuxh04
* Date: 2016/6/29
* Time: 21:17
*/
?>
<?php
$baseUrl = \Yii::$app->urlManager->getBaseUrl();
?>
<?php $this->beginBlock('css') ?>
<link rel="stylesheet" href="<?=$baseUrl?>/css/manage/panorama.css?v=232361">
<link rel="stylesheet" href="<?=$baseUrl?>/dist/paging/pagination.css?v=232361">
<?php $this->endBlock('css') ?>
<!-- content -->
<div class="pad-publisher">
<div class="tab-nav">
<button class="btn-scene">作品管理</button>
</div>
<div class="pad-main">
<div class="x-row">
<span class="tip-statistics">已有全景素材 <b id="thumb-count">0</b> 个</span>
</div>
<div class="pad-function">
<div class="zone-default" id="zone-thumb">
<table width="100%" class="table-pano">
<thead>
<tr>
<td class="td-checkbox"></td>
<td>作品</td>
<td>分享</td>
<td>操作</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div>
<div></div>
</div>
</div>
<div style="clear:both"></div>
<div id="Pagination" class="pagination"><!-- 这里显示分页 --></div>
</div>
</div>
<script id="test" type="text/html">
{{each items as item}}
<tr>
<td class="td-checkbox"></td>
<td>
<div class="div-pano">
<div class="pano-img">
<img src="{{ item.thumb_url }}" width="40" height="40"/>
</div>
<div class="pano-info">
<div class="title">{{item.title}}</div>
<div class="time">{{item.created_on}}</div>
</div>
</div>
</td>
<td>
<a data-url="{{item.panorama_url}}" class="a-qrcode" style="margin-right:20px">分享 </a>
<a href="{{item.panorama_url}}" target="_blank" class="" >浏览 </a>
</td>
<td>
<a data-id="{{item.id}}" class="a-dele">删除</a>
</td>
</tr>
{{/each}}
</script>
<div id="content"></div>
<?php $this->beginBlock('modal')?>
<div id="modal-qrcode" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
<div class="modal-dialog modal-sm">
<div class="modal-content" >
<div class="row-title">
<span class="modal-title">微信扫一扫查看</span>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="opacity: 1.0; color:#ddd"><span aria-hidden="true">×</span></button>
</div>
<div id="qrcode">
</div>
</div>
</div>
</div>
<?php $this->endBlock('modal')?>
<?php $this->beginBlock('js') ?>
<script src="<?=$baseUrl ?>/dist/template.js"></script>
<script src="<?=$baseUrl ?>/dist/paging/jquery.pagination.js"></script>
<script type="text/javascript" src="http://cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
<script src="<?=$baseUrl ?>/js/manage/panorama.js?v=34632673"></script>
<?php $this->endBlock('js') ?>
| bsd-3-clause |
MJuddBooth/pandas | pandas/compat/__init__.py | 12785 | """
compat
======
Cross-compatible functions for Python 2 and 3.
Key items to import for 2/3 compatible code:
* iterators: range(), map(), zip(), filter(), reduce()
* lists: lrange(), lmap(), lzip(), lfilter()
* unicode: u() [no unicode builtin in Python 3]
* longs: long (int in Python 3)
* iterable method compatibility: iteritems, iterkeys, itervalues
* Uses the original method if available, otherwise uses items, keys, values.
* types:
* text_type: unicode in Python 2, str in Python 3
* binary_type: str in Python 2, bytes in Python 3
* string_types: basestring in Python 2, str in Python 3
* bind_method: binds functions to classes
* add_metaclass(metaclass) - class decorator that recreates class with with the
given metaclass instead (and avoids intermediary class creation)
Other items:
* platform checker
"""
# pylint disable=W0611
# flake8: noqa
import re
import functools
import itertools
from distutils.version import LooseVersion
from itertools import product
import sys
import platform
import types
from unicodedata import east_asian_width
import struct
import inspect
from collections import namedtuple
import collections
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] >= 3
PY35 = sys.version_info >= (3, 5)
PY36 = sys.version_info >= (3, 6)
PY37 = sys.version_info >= (3, 7)
PYPY = platform.python_implementation() == 'PyPy'
try:
import __builtin__ as builtins
# not writeable when instantiated with string, doesn't handle unicode well
from cStringIO import StringIO as cStringIO
# always writeable
from StringIO import StringIO
BytesIO = StringIO
import cPickle
import httplib
except ImportError:
import builtins
from io import StringIO, BytesIO
cStringIO = StringIO
import pickle as cPickle
import http.client as httplib
from pandas.compat.chainmap import DeepChainMap
if PY3:
def isidentifier(s):
return s.isidentifier()
def str_to_bytes(s, encoding=None):
return s.encode(encoding or 'ascii')
def bytes_to_str(b, encoding=None):
return b.decode(encoding or 'utf-8')
# The signature version below is directly copied from Django,
# https://github.com/django/django/pull/4846
def signature(f):
sig = inspect.signature(f)
args = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
]
varargs = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.VAR_POSITIONAL
]
varargs = varargs[0] if varargs else None
keywords = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.VAR_KEYWORD
]
keywords = keywords[0] if keywords else None
defaults = [
p.default for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
and p.default is not p.empty
] or None
argspec = namedtuple('Signature', ['args', 'defaults',
'varargs', 'keywords'])
return argspec(args, defaults, varargs, keywords)
def get_range_parameters(data):
"""Gets the start, stop, and step parameters from a range object"""
return data.start, data.stop, data.step
# have to explicitly put builtins into the namespace
range = range
map = map
zip = zip
filter = filter
intern = sys.intern
reduce = functools.reduce
long = int
unichr = chr
# This was introduced in Python 3.3, but we don't support
# Python 3.x < 3.5, so checking PY3 is safe.
FileNotFoundError = FileNotFoundError
# list-producing versions of the major Python iterating functions
def lrange(*args, **kwargs):
return list(range(*args, **kwargs))
def lzip(*args, **kwargs):
return list(zip(*args, **kwargs))
def lmap(*args, **kwargs):
return list(map(*args, **kwargs))
def lfilter(*args, **kwargs):
return list(filter(*args, **kwargs))
from importlib import reload
reload = reload
Hashable = collections.abc.Hashable
Iterable = collections.abc.Iterable
Iterator = collections.abc.Iterator
Mapping = collections.abc.Mapping
MutableMapping = collections.abc.MutableMapping
Sequence = collections.abc.Sequence
Sized = collections.abc.Sized
Set = collections.abc.Set
else:
# Python 2
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
FileNotFoundError = IOError
def isidentifier(s, dotted=False):
return bool(_name_re.match(s))
def str_to_bytes(s, encoding='ascii'):
return s
def bytes_to_str(b, encoding='ascii'):
return b
def signature(f):
return inspect.getargspec(f)
def get_range_parameters(data):
"""Gets the start, stop, and step parameters from a range object"""
# seems we only have indexing ops to infer
# rather than direct accessors
if len(data) > 1:
step = data[1] - data[0]
stop = data[-1] + step
start = data[0]
elif len(data):
start = data[0]
stop = data[0] + 1
step = 1
else:
start = stop = 0
step = 1
return start, stop, step
# import iterator versions of these functions
range = xrange
intern = intern
zip = itertools.izip
filter = itertools.ifilter
map = itertools.imap
reduce = reduce
long = long
unichr = unichr
# Python 2-builtin ranges produce lists
lrange = builtins.range
lzip = builtins.zip
lmap = builtins.map
lfilter = builtins.filter
reload = builtins.reload
Hashable = collections.Hashable
Iterable = collections.Iterable
Iterator = collections.Iterator
Mapping = collections.Mapping
MutableMapping = collections.MutableMapping
Sequence = collections.Sequence
Sized = collections.Sized
Set = collections.Set
if PY2:
def iteritems(obj, **kw):
return obj.iteritems(**kw)
def iterkeys(obj, **kw):
return obj.iterkeys(**kw)
def itervalues(obj, **kw):
return obj.itervalues(**kw)
next = lambda it: it.next()
else:
def iteritems(obj, **kw):
return iter(obj.items(**kw))
def iterkeys(obj, **kw):
return iter(obj.keys(**kw))
def itervalues(obj, **kw):
return iter(obj.values(**kw))
next = next
def bind_method(cls, name, func):
"""Bind a method to class, python 2 and python 3 compatible.
Parameters
----------
cls : type
class to receive bound method
name : basestring
name of method on class instance
func : function
function to be bound as method
Returns
-------
None
"""
# only python 2 has bound/unbound method issue
if not PY3:
setattr(cls, name, types.MethodType(func, None, cls))
else:
setattr(cls, name, func)
# ----------------------------------------------------------------------------
# functions largely based / taken from the six module
# Much of the code in this module comes from Benjamin Peterson's six library.
# The license for this library can be found in LICENSES/SIX and the code can be
# found at https://bitbucket.org/gutworth/six
# Definition of East Asian Width
# http://unicode.org/reports/tr11/
# Ambiguous width can be changed by option
_EAW_MAP = {'Na': 1, 'N': 1, 'W': 2, 'F': 2, 'H': 1}
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
def u(s):
return s
def u_safe(s):
return s
def to_str(s):
"""
Convert bytes and non-string into Python 3 str
"""
if isinstance(s, binary_type):
s = bytes_to_str(s)
elif not isinstance(s, string_types):
s = str(s)
return s
def strlen(data, encoding=None):
# encoding is for compat with PY2
return len(data)
def east_asian_len(data, encoding=None, ambiguous_width=1):
"""
Calculate display width considering unicode East Asian Width
"""
if isinstance(data, text_type):
return sum(_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data)
else:
return len(data)
def import_lzma():
""" import lzma from the std library """
import lzma
return lzma
def set_function_name(f, name, cls):
""" Bind the name/qualname attributes of the function """
f.__name__ = name
f.__qualname__ = '{klass}.{name}'.format(
klass=cls.__name__,
name=name)
f.__module__ = cls.__module__
return f
ResourceWarning = ResourceWarning
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
def u(s):
return unicode(s, "unicode_escape")
def u_safe(s):
try:
return unicode(s, "unicode_escape")
except:
return s
def to_str(s):
"""
Convert unicode and non-string into Python 2 str
"""
if not isinstance(s, string_types):
s = str(s)
return s
def strlen(data, encoding=None):
try:
data = data.decode(encoding)
except UnicodeError:
pass
return len(data)
def east_asian_len(data, encoding=None, ambiguous_width=1):
"""
Calculate display width considering unicode East Asian Width
"""
if isinstance(data, text_type):
try:
data = data.decode(encoding)
except UnicodeError:
pass
return sum(_EAW_MAP.get(east_asian_width(c), ambiguous_width) for c in data)
else:
return len(data)
def import_lzma():
""" import the backported lzma library
or raise ImportError if not available """
from backports import lzma
return lzma
def set_function_name(f, name, cls):
""" Bind the name attributes of the function """
f.__name__ = name
return f
class ResourceWarning(Warning):
pass
string_and_binary_types = string_types + (binary_type,)
if PY2:
# In PY2 functools.wraps doesn't provide metadata pytest needs to generate
# decorated tests using parametrization. See pytest GH issue #2782
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
def wrapper(f):
f = functools.wraps(wrapped, assigned, updated)(f)
f.__wrapped__ = wrapped
return f
return wrapper
else:
wraps = functools.wraps
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_vars.get('__slots__', ()):
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
if PY3:
def raise_with_traceback(exc, traceback=Ellipsis):
if traceback == Ellipsis:
_, _, traceback = sys.exc_info()
raise exc.with_traceback(traceback)
else:
# this version of raise is a syntax error in Python 3
exec("""
def raise_with_traceback(exc, traceback=Ellipsis):
if traceback == Ellipsis:
_, _, traceback = sys.exc_info()
raise exc, None, traceback
""")
raise_with_traceback.__doc__ = """Raise exception with existing traceback.
If traceback is not passed, uses sys.exc_info() to get traceback."""
# dateutil minimum version
import dateutil
if LooseVersion(dateutil.__version__) < LooseVersion('2.5'):
raise ImportError('dateutil 2.5.0 is the minimum required version')
from dateutil import parser as _date_parser
parse_date = _date_parser.parse
# In Python 3.7, the private re._pattern_type is removed.
# Python 3.5+ have typing.re.Pattern
if PY36:
import typing
re_type = typing.re.Pattern
else:
re_type = type(re.compile(''))
# https://github.com/pandas-dev/pandas/pull/9123
def is_platform_little_endian():
""" am I little endian """
return sys.byteorder == 'little'
def is_platform_windows():
return sys.platform == 'win32' or sys.platform == 'cygwin'
def is_platform_linux():
return sys.platform == 'linux2'
def is_platform_mac():
return sys.platform == 'darwin'
def is_platform_32bit():
return struct.calcsize("P") * 8 < 64
| bsd-3-clause |
gooddata/gooddata-js | src/DataLayer/converters/tests/fixtures/FilterConverter.afm.fixtures.ts | 2316 | // (C) 2007-2020 GoodData Corporation
import { AFM } from "@gooddata/typings";
import { Granularities } from "../../../constants/granularities";
export const absoluteDateFilter: AFM.IAbsoluteDateFilter = {
absoluteDateFilter: {
dataSet: {
uri: "ds",
},
from: "2016-01-01",
to: "2017-01-01",
},
};
export const absoluteDateFilterWithIdentifier: AFM.IAbsoluteDateFilter = {
absoluteDateFilter: {
dataSet: {
identifier: "ds",
},
from: "2016-01-01",
to: "2017-01-01",
},
};
export const relativeDateFilter: AFM.IRelativeDateFilter = {
relativeDateFilter: {
dataSet: {
uri: "ds",
},
granularity: Granularities.DATE,
from: -10,
to: 0,
},
};
export const relativeDateFilterWithIdentifier: AFM.IRelativeDateFilter = {
relativeDateFilter: {
dataSet: {
identifier: "ds",
},
granularity: Granularities.DATE,
from: -10,
to: 0,
},
};
export const positiveAttrFilter: AFM.IPositiveAttributeFilter = {
positiveAttributeFilter: {
displayForm: {
uri: "df",
},
in: ["a?id=1", "a?id=2"],
},
};
export const negativeAttrFilter: AFM.INegativeAttributeFilter = {
negativeAttributeFilter: {
displayForm: {
uri: "df",
},
notIn: ["a?id=1", "a?id=2"],
},
};
export const comparisonMeasureValueFilter: AFM.IMeasureValueFilter = {
measureValueFilter: {
measure: {
localIdentifier: "df",
},
condition: {
comparison: {
operator: "GREATER_THAN",
value: 50,
},
},
},
};
export const rangeMeasureValueFilter: AFM.IMeasureValueFilter = {
measureValueFilter: {
measure: {
localIdentifier: "df",
},
condition: {
range: {
operator: "BETWEEN",
from: 10,
to: 100,
},
},
},
};
export const rankingFilter: AFM.IRankingFilter = {
rankingFilter: {
measures: [
{
uri: "some/measure",
},
],
operator: "BOTTOM",
value: 42,
},
};
| bsd-3-clause |
dreadatour/Cactus | cactus/listener/polling.py | 2076 | # coding:utf-8
import os
import time
import threading
import six
from cactus.utils.filesystem import fileList
from cactus.utils.network import retry
class PollingListener(object):
def __init__(self, path, f, delay=.5, ignore=None):
self.path = path
self.f = f
self.delay = delay
self.ignore = ignore
self._pause = False
self._checksums = {}
def checksums(self):
checksumMap = {}
for f in fileList(self.path):
if f.startswith('.'):
continue
if self.ignore and self.ignore(f):
continue
try:
checksumMap[f] = int(os.stat(f).st_mtime)
except OSError:
continue
return checksumMap
def run(self):
# self._loop()
t = threading.Thread(target=self._loop)
t.daemon = True
t.start()
def pause(self):
self._pause = True
def resume(self):
self._checksums = self.checksums()
self._pause = False
def _loop(self):
self._checksums = self.checksums()
while True:
self._run()
@retry((Exception,), tries=5, delay=0.5)
def _run(self):
if not self._pause:
oldChecksums = self._checksums
newChecksums = self.checksums()
result = {
'added': [],
'deleted': [],
'changed': [],
}
for k, v in six.iteritems(oldChecksums):
if k not in newChecksums:
result['deleted'].append(k)
elif v != newChecksums[k]:
result['changed'].append(k)
for k, v in six.iteritems(newChecksums):
if k not in oldChecksums:
result['added'].append(k)
result['any'] = result['added'] + result['deleted'] + result['changed']
if result['any']:
self._checksums = newChecksums
self.f(result)
time.sleep(self.delay)
| bsd-3-clause |
endlessm/chromium-browser | content/browser/service_worker/service_worker_disk_cache.cc | 3799 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/service_worker/service_worker_disk_cache.h"
#include <utility>
#include "content/common/service_worker/service_worker_utils.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
namespace content {
namespace {
void DidReadInfo(base::WeakPtr<AppCacheResponseIO> reader,
scoped_refptr<HttpResponseInfoIOBuffer> io_buffer,
ServiceWorkerResponseReader::ReadResponseHeadCallback callback,
int result) {
DCHECK(io_buffer);
if (result < 0) {
std::move(callback).Run(result, /*response_head=*/nullptr,
/*metadata=*/nullptr);
return;
}
DCHECK(io_buffer->http_info);
auto response_and_metadata =
ServiceWorkerUtils::CreateResourceResponseHeadAndMetadata(
io_buffer->http_info.get(),
/*options=*/network::mojom::kURLLoadOptionSendSSLInfoWithResponse,
/*request_start_time=*/base::TimeTicks(),
/*response_start_time=*/base::TimeTicks::Now(),
io_buffer->response_data_size);
std::move(callback).Run(result, std::move(response_and_metadata.head),
std::move(response_and_metadata.metadata));
}
} // namespace
ServiceWorkerDiskCache::ServiceWorkerDiskCache()
: AppCacheDiskCache(/*use_simple_cache=*/true) {}
ServiceWorkerResponseReader::ServiceWorkerResponseReader(
int64_t resource_id,
base::WeakPtr<AppCacheDiskCache> disk_cache)
: AppCacheResponseReader(resource_id, std::move(disk_cache)) {}
void ServiceWorkerResponseReader::ReadResponseHead(
ReadResponseHeadCallback callback) {
auto io_buffer = base::MakeRefCounted<HttpResponseInfoIOBuffer>();
ReadInfo(io_buffer.get(), base::BindOnce(&DidReadInfo, GetWeakPtr(),
io_buffer, std::move(callback)));
}
ServiceWorkerResponseWriter::ServiceWorkerResponseWriter(
int64_t resource_id,
base::WeakPtr<AppCacheDiskCache> disk_cache)
: AppCacheResponseWriter(resource_id, std::move(disk_cache)) {}
void ServiceWorkerResponseWriter::WriteResponseHead(
const network::mojom::URLResponseHead& response_head,
int response_data_size,
net::CompletionOnceCallback callback) {
// This is copied from CreateHttpResponseInfoAndCheckHeaders().
// TODO(bashi): Use CreateHttpResponseInfoAndCheckHeaders()
// once we remove URLResponseHead -> HttpResponseInfo -> URLResponseHead
// conversion, which drops some information needed for validation
// (e.g. mime type).
auto response_info = std::make_unique<net::HttpResponseInfo>();
response_info->headers = response_head.headers;
if (response_head.ssl_info.has_value())
response_info->ssl_info = *response_head.ssl_info;
response_info->was_fetched_via_spdy = response_head.was_fetched_via_spdy;
response_info->was_alpn_negotiated = response_head.was_alpn_negotiated;
response_info->alpn_negotiated_protocol =
response_head.alpn_negotiated_protocol;
response_info->connection_info = response_head.connection_info;
response_info->remote_endpoint = response_head.remote_endpoint;
response_info->response_time = response_head.response_time;
auto info_buffer =
base::MakeRefCounted<HttpResponseInfoIOBuffer>(std::move(response_info));
info_buffer->response_data_size = response_data_size;
WriteInfo(info_buffer.get(), std::move(callback));
}
ServiceWorkerResponseMetadataWriter::ServiceWorkerResponseMetadataWriter(
int64_t resource_id,
base::WeakPtr<AppCacheDiskCache> disk_cache)
: AppCacheResponseMetadataWriter(resource_id, std::move(disk_cache)) {}
} // namespace content
| bsd-3-clause |
giovannicode/djangoseller | users/urls.py | 554 | from django.conf.urls import url, patterns
import views
urlpatterns = patterns('',
url(r'signup', views.UserCreateView.as_view(), name='signup'),
url(r'signin', views.UserLoginView.as_view(), name='signin'),
url(r'signout', views.signout, name='signout'),
url(r'forgot-password', views.ForgotPasswordView.as_view(), name='forgot-password'),
url(
r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.ResetPasswordView.as_view(),
name='password_reset_confirm'
),
)
| bsd-3-clause |
themayna/crawler | vendor/doctrine/mongodb/lib/Doctrine/MongoDB/Util/ReadPreference.php | 4514 | <?php
/*
* 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 software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\MongoDB\Util;
/**
* Utility class for converting read preferences.
*
* This is necessary for versions of the driver <=1.3.2, where values returned
* by getReadPreference() are not consistent with those expected by
* setReadPreference(). See: https://jira.mongodb.org/browse/PHP-638.
*
* @since 1.0
* @author Jeremy Mikola <jmikola@gmail.com>
* @deprecated 1.3 No longer required; will be removed for 2.0
*/
final class ReadPreference
{
/**
* Read preference types.
*
* The indexes correspond to the numeric values for each read preference
* returned by getReadPreference() methods, while the values correspond to
* the string constants expected by setReadPreference() methods.
*/
private static $types = [
\MongoClient::RP_PRIMARY,
\MongoClient::RP_PRIMARY_PREFERRED,
\MongoClient::RP_SECONDARY,
\MongoClient::RP_SECONDARY_PREFERRED,
\MongoClient::RP_NEAREST,
];
/**
* Private constructor (prevents instantiation)
*/
private function __construct() {}
/**
* Converts a numeric type returned by getReadPreference() methods to the
* constant accepted by setReadPreference() methods.
*
* @param integer $type
* @return string
*/
public static function convertNumericType($type)
{
if (!isset(self::$types[$type])) {
throw new \InvalidArgumentException('Unknown numeric read preference type: ' . $type);
}
return self::$types[$type];
}
/**
* Converts return values from getReadPreference() methods to the format
* accepted by setReadPreference() methods.
*
* This is necessary for MongoClient, MongoDB, and MongoCollection classes
* in driver versions between 1.3.0 and 1.3.3.
*
* @since 1.1
* @param array $readPref
* @return array
*/
public static function convertReadPreference(array $readPref)
{
if (is_numeric($readPref['type'])) {
$readPref['type'] = self::convertNumericType($readPref['type']);
}
if (isset($readPref['type_string'])) {
unset($readPref['type_string']);
}
if ( ! empty($readPref['tagsets'])) {
$readPref['tagsets'] = self::convertTagSets($readPref['tagsets']);
}
return $readPref;
}
/**
* Converts tag sets returned by getReadPreference() methods to the format
* accepted by setReadPreference() methods.
*
* Example input:
*
* [['dc:east', 'use:reporting'], ['dc:west'], []]
*
* Example output:
*
* [['dc' => 'east', 'use' => 'reporting'], ['dc' => 'west'], []]
*
* @param array $tagSets
* @return array
*/
public static function convertTagSets(array $tagSets)
{
return array_map(function(array $tagSet) {
/* If the tag set does not contain a zeroth element, or that element
* does not contain a colon character, we can assume this tag set is
* already in the format expected by setReadPreference().
*/
if (!isset($tagSet[0]) || false === strpos($tagSet[0], ':')) {
return $tagSet;
}
$result = [];
foreach ($tagSet as $tagAndValue) {
list($tag, $value) = explode(':', $tagAndValue, 2);
$result[$tag] = $value;
}
return $result;
}, $tagSets);
}
}
| bsd-3-clause |
SalzmanGroup/spree_product_documents | app/models/spree/product_document_product.rb | 167 | class Spree::ProductDocumentProduct < ActiveRecord::Base
belongs_to :product
belongs_to :product_document
validates_presence_of :product, :product_document
end
| bsd-3-clause |
nschloe/seacas | docs/ioss_html/namespaceanonymous__namespace_02Ioss__Map_8C_03.js | 367 | var namespaceanonymous__namespace_02Ioss__Map_8C_03 =
[
[ "IdPairCompare", "classanonymous__namespace_02Ioss__Map_8C_03_1_1IdPairCompare.html", "classanonymous__namespace_02Ioss__Map_8C_03_1_1IdPairCompare" ],
[ "IdPairEqual", "classanonymous__namespace_02Ioss__Map_8C_03_1_1IdPairEqual.html", "classanonymous__namespace_02Ioss__Map_8C_03_1_1IdPairEqual" ]
]; | bsd-3-clause |
nitikayad96/chandra_suli | chandra_suli/work_within_directory.py | 262 | import contextlib
import os
@contextlib.contextmanager
def work_within_directory(directory):
original_directory = os.getcwd()
os.chdir(directory)
try:
yield
except:
raise
finally:
os.chdir(original_directory)
| bsd-3-clause |
adem-team/advanced | lukisongroup/widget/views/pilotproject/_indexCRUD-experiment2.php | 19872 | <?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\Modal;
use yii\web\JsExpression;
use ptrnov\fullcalendar\FullcalendarScheduler;
use lukisongroup\widget\models\Pilotproject;
use yii\helpers\ArrayHelper;
/* $personalUser=Yii::$app->getUserOpt->Profile_user();
print_r($personalUser ); */
/* $JSCode = <<<EOF
function( start, end, jsEvent, view) {
//alert('Event: ' + jsEvent.title);
//alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
//$.get('/widget/pilotproject/createparent',{'tgl1':tgl1,'tgl2':tgl2},function(data){
$.get('/fullcalendar/test/test-form',function(data){
$('#modal-select').modal('show')
.find('#modalContent')
.html(data);
});
}
EOF; */
$JSSelect = <<<EOF
function(calEvent, jsEvent, view) {
var dateTime1 = new Date(calEvent.start);
var dateTime2 = new Date(calEvent.end);
var tgl1 = moment(dateTime1).format('YYYY-MM-DD LTS');
var tgl2 = moment(dateTime2).subtract(1, 'days').format('YYYY-MM-DD LTS');
$.fn.modal.Constructor.prototype.enforceFocus = function(){};
$.get('/widget/pilotproject/set-data-select',{'start':tgl1,'end':tgl2},function(data){
$('#modal-rooms').modal('show')
.find('#modalContentRooms')
.html(data);
});
}
EOF;
$JSEventClick = <<<EOF
function(calEvent, jsEvent, event,view) {
$('#calendar_test').fullCalendar('refetchEvents');
var dateTime1 = new Date(calEvent.start);
var dateTime2 = new Date(calEvent.end);
var tgl1 = moment(dateTime1).format('YYYY-MM-DD LTS');
var tgl2 = moment(dateTime2).subtract(1, 'days').format('YYYY-MM-DD LTS');
$.fn.modal.Constructor.prototype.enforceFocus = function(){};
//alert(calEvent.resourceId);
$.get('/widget/pilotproject/detail-pilot',{'id':calEvent.resourceId},function(data){
$('#modal-up').modal('show')
.find('#modalContentUp')
.html(data);
});
}
EOF;
$Jseventcolor = <<<EOF
function (event, element, view) {
var status1 = event.status;
var tgl = event.start;
//alert(tgl);
if(status1 == 1)
{
element.html('close');
};
}
EOF;
$afterAllRender = <<<EOF
function(){
$('#calendar_test').fullCalendar( 'changeView', 'timelineDay' );
}
EOF;
$view = <<<EOF
function(view, element) {
console.log("The view's title is " + view.intervalStart.format());
console.log("The view's title is " + view.name);
}
EOF;
$JSaddButtonRooms = <<<EOF
function() {
//alert('test');
$.fn.modal.Constructor.prototype.enforceFocus = function(){};
$.get('/widget/pilotproject/room-form',function(data){
$('#modal-rooms').modal('show')
.find('#modalContentRooms')
.html(data);
});
}
EOF;
$JSaddAddRow= <<<EOF
function() {
//alert('test');
//$.get('/widget/pilotproject/tambah-row?tgl=2016-10-16',function(data){
$('#calendar_test').fullCalendar( 'addResource',
function(callback) {
somethingAsynchonous(function(data) {
callback(data);
})},
scroll );
//});
// setTimeout(function(){
// $('#calendar_test').fullCalendar('refetchEvents');
// },50);
}
EOF;
$JSaddGrp= <<<EOF
function () {
/**
* Remove/add Resources and Event render fullcalendar
* author piter novian [ptr.nov@gmail.com]
*/
$.get('http://lukisongroup.com/widget/pilotproject/render-data-resources', function(data, status){
//var obj = new JSONObject(data);
coba = JSON.parse(data);
for (var key in coba) {
$('#calendar_test').fullCalendar('removeResource',coba[key].id);
console.log(coba[key].id);
};
//alert(coba[1].id);
//alert(coba.count);
});
setTimeout(function(){
var tglCurrent = $('#calendar_test').fullCalendar('getDate');
var tgl=moment(tglCurrent).format('YYYY-MM-DD');
$.get('http://lukisongroup.com/widget/pilotproject/update-data-resources?start='+tgl, function(datarcvd, status){
rcvd = JSON.parse(datarcvd);
for (var key in rcvd) {
$('#calendar_test').fullCalendar('addResource',
rcvd[key]
, scroll );
console.log(rcvd[1]);
};
});
var calendarOptions = $('#calendar_test')
.fullCalendar('getView').options.resourceGroupField;
//alert(calendarOptions);
$('#calendar_test').fullCalendar('option',{
resourceGroupField: calendarOptions==''?'srcparent':'',
isRTL: false, //kiri/kanan
});
$('#calendar_test').fullCalendar('refetchResources');
$('#calendar_test').fullCalendar('refetchEvents');
//$('#calendar_test').fullCalendar('rerenderEvents');
},100);
}
EOF;
/* $JSDropEvent = <<<EOF
function(event, element, view) {
var child = event.parent;
var status = event.status;
var dateTime2 = new Date(event.end);
var dateTime1 = new Date(event.start);
var tgl1 = moment(dateTime1).format("YYYY-MM-DD");
var tgl2 = moment(dateTime2).subtract(1, "days").format("YYYY-MM-DD");
alert(tgl1);
var id = event.id;
if(child != 0 && status != 1){
$.get('/widget/pilotproject/drop-child',{'id':id,'tgl1':tgl1,'tgl2':tgl2});
}
}
EOF; */
$JsBeforeRender = <<<EOF
function(){
//if(window.onload) {
//setTimeout(function(){
var elem = document.getElementById('calendar_test');
//var list1 = elem.getElementsByTagName('button')[7];
var list1 = elem.getElementsByClassName('fc-timelineOneDays-button');
console.log(list1[0].innerText);
list1[0].click();
//},60000);
//};
}
EOF;
$wgCalendar=FullcalendarScheduler::widget([
'modalSelect'=>[
/**
* modalSelect for cell Select
* 'clientOptions' => ['selectable' => true] //makseure set true.
* 'clientOptions' => ['select' => function or JsExpression] //makseure disable/empty. if set it, used JsExpressio to callback.
* @author piter novian [ptr.nov@gmail.com] //"https://github.com/ptrnov/yii2-fullcalendar".
*/
'id' => 'modal-select', //set it, if used FullcalendarScheduler more the one on page.
'id_content'=>'modalContent', //set it, if used FullcalendarScheduler more the one on page.
'headerLabel' => 'Model Header Label', //your modal title,as your set.
'modal-size'=>'modal-lg' //size of modal (modal-xs,modal-sm,modal-sm,modal-lg).
],
'header' => [
'left' => 'plus,today, prev,next, details, group, excel-export',
'center' => 'title',
'right' => 'timelineOneDays,agendaWeek,month,listWeek',
],
'options'=>[
'id'=> 'calendar_test', //set it, if used FullcalendarScheduler more the one on page.
'language'=>'id',
],
'optionsEventUrl'=>[
'events' => Url::to(['/widget/pilotproject/render-data-events','claster'=>'event']), //should be set data event "your Controller link"
//'resources'=> Url::to(['/widget/pilotproject/render-data-resources']), //should be set "your Controller link"
'resources'=>[], //should be set "your Controller link"
//'resources'=> Url::to(['/widget/pilotproject/render-data-resources','start'=>'2016-10-12']), //should be set "your Controller link"
// 'resources'=> Url::to(['/widget/pilotproject/render-data-resources','start'=>'{moment($(#calendar_test).fullCalendar(getDate).format(YYYY-MM-DD)}']), //should be set "your Controller link"
//'resources'=> Url::to(['/widget/pilotproject/render-data-resources','tgl'=>'
//{moment($this.fullCalendar("getDate").format("YYYY-MM-DD");
// }
//']), //should be set "your Controller link"
// 'eventSelectUrl'=>'/widget/pilotproject/set-data-select', //should be set "your Controller link" to get(start,end) from select. You can use model for scenario
'changeDropUrl'=>'/widget/pilotproject/change-data-drop', //should be set "your Controller link" to get(start,end) from select. You can use model for scenario.
'dragableReceiveUrl'=>'/widget/pilotproject/dragable-receive', //dragable, new data, star date, end date, id form increment db
'dragableDropUrl'=>'/widget/pilotproject/dragable-drop', //dragable, new data, star date, end date, id form increment db
],
'clientOptions' => [
'theme'=> true,
'customButtons'=>[ //additional button
'details'=>[
'text'=>'Rooms',
'click'=>new JsExpression($JSaddButtonRooms),
],
'group'=>[
'text'=>'Group',
'click'=>new JsExpression($JSaddGrp),
],
'plus'=>[
'text'=>'Plus',
'click'=>new JsExpression($JSaddAddRow),
],
'excel-export'=>[
'text'=>'Excel-Export',
//'click'=>new JsExpression($JSaddButton),
]
],
'timezone'=> 'local',
// 'viewRender'=> new JsExpression($view),
//'language'=>'id',
// 'locale'=>'id',
// 'isRTL'=> true,
//'ignoreTimezone'=> false,
//'timezone'=>'currentTimezone',
'selectHelper' => true,
'editable' => true,
'selectable' => true,
'select' => new JsExpression($JSSelect), // don't set if used "modalSelect"
'eventClick' => new JsExpression($JSEventClick),
'rerenderEvents'=> new JsExpression($JsBeforeRender),
'eventAfterRender'=> new JsExpression($Jseventcolor),
//'eventAfterAllRender'=> new JsExpression($afterAllRender),
'droppable' => true,
//'eventDrop' => new JsExpression($JSDropEvent),
//'now' => \Yii::$app->ambilKonvesi->convert($model->start,'datetime'),//'2016-05-07 06:00:00',
'firstDay' =>'0',
'theme'=> true,
'aspectRatio' => 1.8,
//'scrollTime' => '00:00', // undo default 6am scrollTime
//'defaultView' => 'month',//'timelineDay',//agendaDay',
'defaultView' => 'timelineDay',//agendaDay',
'views' => [
'timelineOneDays' => [
'type' => 'timeline',
'duration' => [
'days' => 1,
],
],
],
'lazyFetching'=>true,
//'eventOverlap'=> true,
//'resources'=> \yii\helpers\Url::to(['pilotproject/render-data-resources', 'id' => 1]),
//'eventSources'=>new JsExpression($JsBefore),
//'events'=> \yii\helpers\Url::to(['pilotproject/render-data-events']),
//'renderResources'=>new JsExpression($JsBefore),
//'resources'=>new JsExpression($JsBefore),
//'eventSources'=>new JsExpression($JsBefore),
'resourceAreaWidth'=>'30%',
'resourceLabelText' => 'Discriptions',
//'resourceEditable'=>true,
//'resourceGroupField'=> 'srcparent',
//'resourceGroupField'=> \yii\helpers\Url::to(['pilotproject/group-data-resources']),
'resourceColumns'=>[
[
//'group'=> true,
'labelText'=>'Rooms',
'field'=> 'title',
'width'=>'150px',
'align'=>'left',
],
[
'labelText'=> 'Department',
'field'=> 'dep_id',
'width'=>'150px',
'align'=>'center',
],
[
'labelText'=> 'CreateBy',
'field'=> 'createby',
'width'=>'100px',
'align'=>'center',
]
],
],
]);
/*modal*/
Modal::begin([
'id' => 'modal-rooms',
'header' => '<div style="float:left;margin-right:10px" class="fa fa-2x fa fa-user"></div><div><h5 class="modal-title"><b>Create Rooms</b></h5></div>',
'size' => 'modal-dm',
'headerOptions'=>[
'style'=> 'border-radius:5px; background-color: rgba(74, 206, 231, 1)',
],
]);
echo "<div id='modalContentRooms'></div>";
Modal::end();
/*modal*/
Modal::begin([
'id' => 'modal-up',
'header' => '<div style="float:left;margin-right:10px" class="fa fa-2x fa fa-user"></div><div><h5 class="modal-title"><b>Pilot Project</b></h5></div>',
'size' => Modal::SIZE_LARGE,
'headerOptions'=>[
'style'=> 'border-radius:5px; background-color: rgba(74, 206, 231, 1)',
],
]);
echo "<div id='modalContentUp'></div>";
Modal::end();
/*modal*/
// Modal::begin([
// 'id' => 'modal-row',
// 'header' => '<div style="float:left;margin-right:10px" class="fa fa-plus"></div><div><h5 class="modal-title"><b>Tambah Row</b></h5></div>',
// 'size' => Modal::SIZE_SMALL,
// 'headerOptions'=>[
// 'style'=> 'border-radius:5px; background-color: rgba(74, 206, 231, 1)',
// ],
// ]);
// echo "<div id='modalContentRow'></div>";
// Modal::end();
?>
<?php
// $this->registerJs("
// /* ADDING EVENTS */
// var currColor = '#3c8dbc'; //Red by default
// //Color chooser button
// var colorChooser = $('#color-chooser-btn');
// $('#color-chooser > li > a').click(function (e) {
// e.preventDefault();
// //Save color
// currColor = $(this).css('color');
// //Add color effect to button
// $('#add-new-event').css({'background-color': currColor, 'eventColor': currColor});
// });
// $('#add-new-event').click(function (e) {
// e.preventDefault();
// //Get value and make sure it is not null
// var val = $('#new-event').val();
// if (val.length == 0) {
// return;
// }
// //Create events
// var event = $('<div />');
// event.css({'background-color': currColor, 'eventColor': currColor, 'color': '#fff'}).addClass('external-event');
// event.html(val);
// $('#external-events').prepend(event);
// //Add draggable funtionality
// ini_events(event);
// //Remove event from text input
// $('#new-event').val('');
// });
// ",$this::POS_END);
$this->registerJs($this->render('save_external_event.js'),$this::POS_END);
/*
* Triger timeout button triger with timeout.
* @author piter novian [ptr.nov@gmail.com]
*/
$this->registerJs("
document.addEventListener('DOMContentLoaded', function(event) {
//$(document).ready(function() {
$('#tab-project-id').click(function(){
setTimeout(function(){
var idx = $('ul li.active').index();
//alert(idx);
if (idx==0){
//alert(idx);
var elem = document.getElementById('calendar_test');
var list = elem.getElementsByTagName('button')[4];
//list.onmouseover = function() {}
//list.className='ui-state-hover';
//list.focus();
setTimeout(function(){
list.click();
},100);
}
},100);
});
//});
})
",$this::POS_READY);
$this->registerJs("
//$('.fc-prev-button, .fc-next-button, .fc-today-button, .fc-timelineOneDays-button').click(function(){
$(document).on('click', '.fc-prev-button, .fc-next-button, .fc-today-button, .fc-timelineOneDays-button', function(){
console.log('test button next');
/**
* Remove Resources and Add Resources fullcalendar
* author piter novian [ptr.nov@gmail.com]
*/
setTimeout(function(){
$.get('http://lukisongroup.com/widget/pilotproject/render-data-resources', function(data, status){
//var obj = new JSONObject(data);
coba = JSON.parse(data);
for (var key in coba) {
$('#calendar_test').fullCalendar('removeResources',coba[key].id);
console.log(coba[key].id);
};
//alert(coba[1].id);
//alert(coba.count);
});
var tglCurrent = $('#calendar_test').fullCalendar('getDate');
var tgl=moment(tglCurrent).format('YYYY-MM-DD');
$.get('http://lukisongroup.com/widget/pilotproject/update-data-resources?start='+tgl, function(datarcvd, status){
rcvd = JSON.parse(datarcvd);
for (var key in rcvd) {
$('#calendar_test').fullCalendar('addResource',
rcvd[key]
, scroll );
console.log(rcvd[1]);
};
});
$('#calendar_test').fullCalendar('refetchEvents');
$('#calendar_test').fullCalendar('refetchResources');
//$('#calendar_test').fullCalendar('refetchEvents');
/* */
},500);
//$('#calendar_test').fullCalendar( 'rerenderEvents' )
/* $.get('http://lukisongroup.com/widget/pilotproject/render-data-events?claster=event&start=2016-10-10&end=2016-10-11', function(dataEvent, status){
dataEventDay= JSON.parse(dataEvent);
$('#calendar_test').fullCalendar('updateEvent', dataEventDay );
console.log(dataEventDay[1]);
}) */
});
function second() {
/* $('#calendar_test').fullCalendar(function(){
$('#calendar_test').fullCalendar('option',{
resourceGroupField:'',
});
}); */
$('#calendar_test').fullCalendar('refetchEvents');
$('#calendar_test').fullCalendar('refetchResources');
}
//
",$this::POS_READY);
?>
<div class="row" style="margin-top:0px,font-family: verdana, arial, sans-serif ;font-size: 8pt">
<div class="col-xs-12 col-sm-12 col-dm-9 col-lg-9">
<div id="tes1" class="row">
<?php echo $wgCalendar;?>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-dm-3 col-lg-3">
<div class="row">
<section class="content">
<div class="box box-solid">
<div class="box-body">
<h5>Draggable Events</h5>
<div id='external-events'>
<!-- <div class='external-event bg-green '>My Event 1</div>
<div class='external-event bg-yellow'>My Event 2</div>
<div class='external-event bg-aqua'>My Event 3</div>
<div class='external-event bg-light-blue'>My Event 4</div>
<div class='external-event bg-red'>My Event 5</div>
<div class='external-event bg-aqua'>My Event 3</div>
<div class='external-event bg-light-blue'>My Event 4</div>
<div class='external-event bg-red'>My Event 5</div> -->
<!-- <p>
<input type='checkbox' id='drop-remove' />
<label for='drop-remove'>remove after drop</label>
</p> -->
</div>
</div>
</div>
<div class="box box-solid">
<div class="box-header with-border">
<h5>Create Event</h5>
</div>
<div class="box-body">
<div class="btn-group" style="width: 100%; margin-bottom: 10px;">
<!--<button type="button" id="color-chooser-btn" class="btn btn-info btn-block dropdown-toggle" data-toggle="dropdown">Color <span class="caret"></span></button>-->
<ul class="fc-color-picker" id="color-chooser">
<li><a class="text-aqua" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-blue" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-light-blue" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-teal" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-yellow" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-orange" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-green" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-lime" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-red" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-purple" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-fuchsia" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-muted" href="#"><i class="fa fa-square"></i></a></li>
<li><a class="text-navy" href="#"><i class="fa fa-square"></i></a></li>
</ul>
</div>
<!-- /btn-group -->
<div class="input-group">
<input id="new-event" type="text" class="form-control" placeholder="Event Title">
<div class="input-group-btn">
<button id="add-new-event" type="button" class="btn btn-primary btn-flat">Add</button>
</div>
<!-- /btn-group -->
</div>
<!-- /input-group -->
</div>
</div>
</section>
</div>
</div>
</div>
| bsd-3-clause |
lewisodriscoll/sasview | src/sas/sasgui/perspectives/calculator/kiessig_calculator_panel.py | 9529 | """
This software was developed by the University of Tennessee as part of the
Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
project funded by the US National Science Foundation.
See the license text in license.txt
copyright 2008, 2009, University of Tennessee
"""
import wx
import sys
from sas.sasgui.guiframe.panel_base import PanelBase
from sas.sascalc.calculator.kiessig_calculator import KiessigThicknessCalculator
from calculator_widgets import OutputTextCtrl
from calculator_widgets import InputTextCtrl
from sas.sasgui.perspectives.calculator import calculator_widgets as widget
from sas.sasgui.guiframe.documentation_window import DocumentationWindow
_BOX_WIDTH = 77
#Slit length panel size
if sys.platform.count("win32") > 0:
PANEL_TOP = 0
PANEL_WIDTH = 500
PANEL_HEIGHT = 230
FONT_VARIANT = 0
else:
PANEL_TOP = 60
PANEL_WIDTH = 560
PANEL_HEIGHT = 230
FONT_VARIANT = 1
class KiessigThicknessCalculatorPanel(wx.Panel, PanelBase):
"""
Provides the Kiessig thickness calculator GUI.
"""
## Internal nickname for the window, used by the AUI manager
window_name = "Kiessig Thickness Calculator"
## Name to appear on the window title bar
window_caption = "Kiessig Thickness Calculator"
## Flag to tell the AUI manager to put this panel in the center pane
CENTER_PANE = True
def __init__(self, parent, *args, **kwds):
wx.Panel.__init__(self, parent, *args, **kwds)
PanelBase.__init__(self)
#Font size
self.SetWindowVariant(variant=FONT_VARIANT)
# Object that receive status event
self.parent = parent
self.kiessig = KiessigThicknessCalculator()
#layout attribute
self.hint_sizer = None
self._do_layout()
def _define_structure(self):
"""
Define the main sizers building to build this application.
"""
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.box_source = wx.StaticBox(self, -1,
str("Kiessig Thickness Calculator"))
self.boxsizer_source = wx.StaticBoxSizer(self.box_source,
wx.VERTICAL)
self.dq_name_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.thickness_size_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.hint_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
def _layout_dq_name(self):
"""
Fill the sizer containing dq name
"""
# get the default dq
dq_value = str(self.kiessig.get_deltaq())
dq_unit_txt = wx.StaticText(self, -1, '[1/A]')
dq_name_txt = wx.StaticText(self, -1,
'Kiessig Fringe Width (Delta Q): ')
self.dq_name_tcl = InputTextCtrl(self, -1,
size=(_BOX_WIDTH,-1))
dq_hint = "Type the Kiessig Fringe Width (Delta Q)"
self.dq_name_tcl.SetValue(dq_value)
self.dq_name_tcl.SetToolTipString(dq_hint)
#control that triggers importing data
id = wx.NewId()
self.compute_button = wx.Button(self, id, "Compute")
hint_on_compute = "Compute the diameter/thickness in the real space."
self.compute_button.SetToolTipString(hint_on_compute)
self.Bind(wx.EVT_BUTTON, self.on_compute, id=id)
self.dq_name_sizer.AddMany([(dq_name_txt, 0, wx.LEFT, 15),
(self.dq_name_tcl, 0, wx.LEFT, 15),
(dq_unit_txt, 0, wx.LEFT, 10),
(self.compute_button, 0, wx.LEFT, 30)])
def _layout_thickness_size(self):
"""
Fill the sizer containing thickness information
"""
thick_unit = '['+self.kiessig.get_thickness_unit() +']'
thickness_size_txt = wx.StaticText(self, -1,
'Thickness (or Diameter): ')
self.thickness_size_tcl = OutputTextCtrl(self, -1,
size=(_BOX_WIDTH,-1))
thickness_size_hint = " Estimated Size in Real Space"
self.thickness_size_tcl.SetToolTipString(thickness_size_hint)
thickness_size_unit_txt = wx.StaticText(self, -1, thick_unit)
self.thickness_size_sizer.AddMany([(thickness_size_txt, 0, wx.LEFT, 15),
(self.thickness_size_tcl, 0, wx.LEFT, 15),
(thickness_size_unit_txt, 0, wx.LEFT, 10)])
def _layout_hint(self):
"""
Fill the sizer containing hint
"""
hint_msg = "This tool is to approximately estimate "
hint_msg += "the thickness of a layer"
hint_msg += " or the diameter of particles\n "
hint_msg += "from the Kiessig fringe width in SAS/NR data."
hint_msg += ""
self.hint_txt = wx.StaticText(self, -1, hint_msg)
self.hint_sizer.AddMany([(self.hint_txt, 0, wx.LEFT, 15)])
def _layout_button(self):
"""
Do the layout for the button widgets
"""
id = wx.NewId()
self.bt_help = wx.Button(self, id, 'HELP')
self.bt_help.Bind(wx.EVT_BUTTON, self.on_help)
self.bt_help.SetToolTipString("Help using the Kiessig fringe calculator.")
self.bt_close = wx.Button(self, wx.ID_CANCEL, 'Close')
self.bt_close.Bind(wx.EVT_BUTTON, self.on_close)
self.bt_close.SetToolTipString("Close this window.")
self.button_sizer.AddMany([(self.bt_help, 0, wx.LEFT, 260),
(self.bt_close, 0, wx.LEFT, 20)])
def _do_layout(self):
"""
Draw window content
"""
self._define_structure()
self._layout_dq_name()
self._layout_thickness_size()
self._layout_hint()
self._layout_button()
self.boxsizer_source.AddMany([(self.dq_name_sizer, 0,
wx.EXPAND|wx.TOP|wx.BOTTOM, 5),
(self.thickness_size_sizer, 0,
wx.EXPAND|wx.TOP|wx.BOTTOM, 5),
(self.hint_sizer, 0,
wx.EXPAND|wx.TOP|wx.BOTTOM, 5)])
self.main_sizer.AddMany([(self.boxsizer_source, 0, wx.ALL, 10),
(self.button_sizer, 0,
wx.EXPAND|wx.TOP|wx.BOTTOM, 5)])
self.SetSizer(self.main_sizer)
self.SetAutoLayout(True)
def on_help(self, event):
"""
Bring up the Kiessig fringe calculator Documentation whenever
the HELP button is clicked.
Calls DocumentationWindow with the path of the location within the
documentation tree (after /doc/ ....". Note that when using old
versions of Wx (before 2.9) and thus not the release version of
installers, the help comes up at the top level of the file as
webbrowser does not pass anything past the # to the browser when it is
running "file:///...."
:param evt: Triggers on clicking the help button
"""
_TreeLocation = "user/sasgui/perspectives/calculator/"
_TreeLocation += "kiessig_calculator_help.html"
_doc_viewer = DocumentationWindow(self, -1, _TreeLocation, "",
"Density/Volume Calculator Help")
def on_close(self, event):
"""
close the window containing this panel
"""
self.parent.Close()
if event is not None:
event.Skip()
def on_compute(self, event):
"""
Execute the computation of thickness
"""
# skip for another event
if event is not None:
event.Skip()
dq = self.dq_name_tcl.GetValue()
self.kiessig.set_deltaq(dq)
# calculate the thickness
output = self.kiessig.compute_thickness()
thickness = self.format_number(output)
# set tcl
self.thickness_size_tcl.SetValue(str(thickness))
def format_number(self, value=None):
"""
Return a float in a standardized, human-readable formatted string
"""
try:
value = float(value)
except:
output = None
return output
output = "%-7.4g" % value
return output.lstrip().rstrip()
def _onparamEnter(self, event = None):
"""
On Text_enter_callback, perform compute
"""
self.on_compute(event)
class KiessigWindow(widget.CHILD_FRAME):
def __init__(self, parent=None, manager=None,
title="Kiessig Thickness Calculator",
size=(PANEL_WIDTH,PANEL_HEIGHT), *args, **kwds):
kwds['title'] = title
kwds['size'] = size
widget.CHILD_FRAME.__init__(self, parent, *args, **kwds)
self.parent = parent
self.manager = manager
self.panel = KiessigThicknessCalculatorPanel(parent=self)
self.Bind(wx.EVT_CLOSE, self.on_close)
self.SetPosition((wx.LEFT, PANEL_TOP))
self.Show(True)
def on_close(self, event):
"""
Close event
"""
if self.manager is not None:
self.manager.kiessig_frame = None
self.Destroy()
if __name__ == "__main__":
app = wx.PySimpleApp()
widget.CHILD_FRAME = wx.Frame
frame = KiessigWindow()
frame.Show(True)
app.MainLoop()
| bsd-3-clause |
grapto/Orchard.CloudBust | src/Orchard.Web/Global.asax.cs | 2075 | using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Orchard.Environment;
using Orchard.WarmupStarter;
namespace Orchard.Web {
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : HttpApplication {
private static Starter<IOrchardHost> _starter;
public MvcApplication() {
}
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
}
protected void Application_Start() {
RegisterRoutes(RouteTable.Routes);
_starter = new Starter<IOrchardHost>(HostInitialization, HostBeginRequest, HostEndRequest);
_starter.OnApplicationStart(this);
}
protected void Application_BeginRequest() {
_starter.OnBeginRequest(this);
}
protected void Application_EndRequest() {
_starter.OnEndRequest(this);
}
private static void HostBeginRequest(HttpApplication application, IOrchardHost host) {
application.Context.Items["originalHttpContext"] = application.Context;
host.BeginRequest();
}
private static void HostEndRequest(HttpApplication application, IOrchardHost host) {
host.EndRequest();
}
private static IOrchardHost HostInitialization(HttpApplication application) {
var host = OrchardStarter.CreateHost(MvcSingletons);
host.Initialize();
// initialize shells to speed up the first dynamic query
host.BeginRequest();
host.EndRequest();
return host;
}
static void MvcSingletons(ContainerBuilder builder) {
builder.Register(ctx => RouteTable.Routes).SingleInstance();
builder.Register(ctx => ModelBinders.Binders).SingleInstance();
builder.Register(ctx => ViewEngines.Engines).SingleInstance();
}
}
}
| bsd-3-clause |
nwjs/chromium.src | chrome/browser/google/google_brand_code_map_chromeos.cc | 29284 | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/google/google_brand_code_map_chromeos.h"
#include "base/containers/flat_map.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
namespace google_brand {
namespace chromeos {
std::string GetRlzBrandCode(
const std::string& static_brand_code,
absl::optional<policy::MarketSegment> market_segment) {
struct BrandCodeValueEntry {
const char* unenrolled_brand_code;
const char* education_enrolled_brand_code;
const char* enterprise_enrolled_brand_code;
};
static const base::NoDestructor<
base::flat_map<std::string, BrandCodeValueEntry>>
kBrandCodeMap({{"ACAC", {"CFZM", "BEUH", "GUTN"}},
{"ACAG", {"KSOU", "MUHR", "YYJR"}},
{"ACAH", {"KEFG", "RYNH", "HHAZ"}},
{"ACAI", {"BKWQ", "CMVE", "VNFQ"}},
{"ACAJ", {"KVPC", "UHAI", "CPNG"}},
{"ACAK", {"PQNT", "MDWH", "AJKH"}},
{"ACAM", {"HBCZ", "ZGSZ", "MFUO"}},
{"ACAO", {"MWDF", "BNNY", "SYIY"}},
{"ACAP", {"LKNW", "SVFL", "FGKR"}},
{"ACAQ", {"JXWA", "PZLO", "AKLZ"}},
{"ACAR", {"EAQE", "UHHJ", "ZYFW"}},
{"ACAS", {"JEHD", "XUID", "FNGA"}},
{"ACAT", {"RJNJ", "CKCB", "VHGI"}},
{"ACAU", {"DXIN", "LPNB", "FIXM"}},
{"ACAV", {"TTSD", "XTQQ", "TIQC"}},
{"ACAX", {"CFKW", "QKXN", "VXIS"}},
{"ACAY", {"HKDC", "RYKK", "KSIY"}},
{"ACAZ", {"VHDQ", "AOTU", "WAMY"}},
{"ACBA", {"TVZD", "HLQR", "DOWV"}},
{"ACBB", {"ABIB", "LFJO", "ZQSG"}},
{"ACBC", {"UFPX", "WVQM", "MLYC"}},
{"ACBD", {"BRFU", "HBXU", "FAQM"}},
{"ACBE", {"JQFF", "GOJK", "ALHM"}},
{"ACBF", {"SSNP", "VHIH", "QMFD"}},
{"ADGK", {"PKUQ", "AEMI", "CUUL"}},
{"ADID", {"XDMY", "QHTP", "PBND"}},
{"AGVY", {"RNNC", "KYLA", "NJOS"}},
{"AJIM", {"XQAQ", "WFLV", "AMBR"}},
{"ALRH", {"XDKE", "TDIH", "VLER"}},
{"ANAE", {"IWTJ", "CISE", "SLJZ"}},
{"ANLW", {"MTZL", "LFDW", "IHRZ"}},
{"AOKF", {"ZKSY", "KRPA", "QAZL"}},
{"AOPA", {"TTBL", "HHHA", "SADO"}},
{"AOPB", {"WFJJ", "ZQCN", "OMBM"}},
{"AOPC", {"CAKV", "AASR", "BXLX"}},
{"AOPD", {"PFAH", "NIUP", "MQIF"}},
{"AOPE", {"ZMYO", "BBQM", "UOUV"}},
{"APXY", {"JUFT", "VCUF", "TMSS"}},
{"AQCO", {"TNLZ", "FHPA", "XFUO"}},
{"ARBI", {"GFHA", "FBQD", "WRQR"}},
{"ASCT", {"CTRF", "LBBD", "YBND"}},
{"ASUA", {"IEIT", "JAIV", "MURN"}},
{"ASUB", {"QBBW", "RUGL", "UVVX"}},
{"ASUD", {"QLMM", "CRUA", "JSID"}},
{"ASUE", {"XLEN", "KECH", "HBGX"}},
{"ASUF", {"IVGE", "VNTM", "XELD"}},
{"ASUG", {"TSGW", "DZUL", "HFLO"}},
{"ASUH", {"DDNS", "OMSX", "VVWZ"}},
{"ASUJ", {"HJUL", "XWWL", "WSCY"}},
{"ASUK", {"RGUX", "OXBQ", "LDTL"}},
{"ASUL", {"ZJXP", "HGDC", "OFPC"}},
{"ASUN", {"ERAF", "HZQI", "JBDP"}},
{"ASUO", {"RCMY", "NLPS", "JOKT"}},
{"AYMH", {"BBMB", "VBWP", "BVTP"}},
{"BAQN", {"YJJJ", "LDCA", "QSJF"}},
{"BAUA", {"UWIF", "EOEW", "RPDR"}},
{"BCOL", {"YJDV", "GSIC", "BAUL"}},
{"BDIW", {"UDUG", "TRYQ", "PWFV"}},
{"BDXJ", {"EWPX", "PXLS", "LPDD"}},
{"BKLL", {"DJXO", "KLUN", "DJNO"}},
{"BLXA", {"VLID", "JNUQ", "IKRB"}},
{"BMAD", {"HGZG", "AOPW", "RIVV"}},
{"BMNE", {"HLSA", "WXJQ", "TULR"}},
{"BWYB", {"YMAG", "QICL", "XNBX"}},
{"CBUY", {"POUW", "GHJY", "USXU"}},
{"CDYS", {"CJRA", "BIRA", "NFVP"}},
{"CFGF", {"SKZQ", "CFPE", "KTXQ"}},
{"CFUL", {"GIFL", "EDYW", "GOJE"}},
{"CLQY", {"BBGR", "ULEA", "YDVH"}},
{"CLSF", {"OWOB", "RLJX", "OZWK"}},
{"CNOR", {"TEUF", "QHOY", "NQZD"}},
{"CPPT", {"CQFF", "PCCZ", "HZEW"}},
{"CQFV", {"OJUW", "FCMY", "VCYR"}},
{"CQPQ", {"GATZ", "QAVU", "WRXC"}},
{"CSLV", {"BZSH", "ZDXA", "HGGZ"}},
{"CTIE", {"EURD", "HZJV", "WBJJ"}},
{"CYQR", {"XGJJ", "DRMC", "RUQD"}},
{"CYSQ", {"NHHD", "TAVM", "FHSA"}},
{"DBED", {"JUMI", "UTSY", "RXGS"}},
{"DBHI", {"MMGG", "MMQD", "XQDJ"}},
{"DEAA", {"HXUG", "BJUN", "IYTV"}},
{"DEAB", {"ARPQ", "MFRJ", "JWTH"}},
{"DEAC", {"DSMM", "IXET", "KQDV"}},
{"DEAD", {"QJXG", "AGGP", "GYQT"}},
{"DEAE", {"NZAS", "IHEL", "JSYE"}},
{"DEAF", {"TATK", "RWXF", "DQDT"}},
{"DEAG", {"JFEX", "CVLN", "UFWN"}},
{"DEAH", {"HRBU", "DJKF", "CMPZ"}},
{"DHAS", {"KEDN", "LUZR", "MHFN"}},
{"DISZ", {"PPAR", "VCPW", "NJKK"}},
{"DJBB", {"ZLXN", "WQCE", "ASCQ"}},
{"DKJM", {"VRGL", "PZYF", "VBTW"}},
{"DRYI", {"LWTQ", "OLEY", "NWUA"}},
{"DSCL", {"OSET", "BPKO", "KRIN"}},
{"DUKI", {"FRGD", "SACE", "AAMW"}},
{"DVUG", {"HJHV", "KPAH", "DCQS"}},
{"DWCY", {"ZJQH", "JLCB", "QOAI"}},
{"DXVL", {"EBBY", "NMQL", "GTHA"}},
{"DXZT", {"WNSK", "WNDA", "DZWQ"}},
{"DYHT", {"YPAH", "NUKA", "EULJ"}},
{"EDFZ", {"VUMJ", "OMDW", "LCDF"}},
{"EDHM", {"NLAE", "JYDL", "BTWJ"}},
{"EGSC", {"DWAW", "FZRC", "PKWJ"}},
{"EKWL", {"PGWE", "JEHJ", "WQYW"}},
{"ELQA", {"GTJZ", "DTIH", "IXVN"}},
{"EOJH", {"GTAZ", "APYI", "UHAZ"}},
{"EUHF", {"RZPG", "FQYM", "IIBT"}},
{"EWFK", {"XAMW", "XCJY", "NWVP"}},
{"EXCQ", {"LAOZ", "QTVX", "ZCLW"}},
{"EXEM", {"RIPQ", "SYMM", "GONB"}},
{"FBTP", {"XLDO", "TLOM", "FYMS"}},
{"FCPG", {"WITB", "FOXJ", "YJQZ"}},
{"FCVS", {"HOBX", "YMDN", "GKTP"}},
{"FHYR", {"YKUD", "XTKX", "QFMD"}},
{"FIGU", {"VMWP", "SBFY", "IYUS"}},
{"FNVY", {"DLEJ", "DCNV", "XALG"}},
{"FOBB", {"TRYO", "HAKV", "WKDK"}},
{"FQPJ", {"ZTQG", "ZNEO", "LYMZ"}},
{"FQZI", {"WPBA", "YZDA", "FXCI"}},
{"FRGW", {"ZPJY", "MYPP", "KQFE"}},
{"FSFR", {"ZDAR", "BERM", "COKX"}},
{"FSGY", {"PJQC", "RHZW", "POVI"}},
{"FWVK", {"MUTD", "GWKK", "SQSC"}},
{"FXEL", {"FVLL", "QOGS", "SVKH"}},
{"FYSO", {"HFDH", "WNPK", "ZTIK"}},
{"GBWE", {"DKLE", "OUDI", "VWJC"}},
{"GBXM", {"ONLL", "YBJS", "SOVT"}},
{"GFMQ", {"DRLH", "HVWY", "OYYM"}},
{"GFZE", {"HWCY", "NMLY", "QJJN"}},
{"GJZV", {"BUSA", "GIOS", "UYOM"}},
{"GLAR", {"RLLB", "UPQT", "OITD"}},
{"GMOO", {"GMRP", "QONY", "LOJX"}},
{"GNBB", {"HDRM", "BNED", "RUYH"}},
{"GNDV", {"UCEU", "GXKO", "HWDL"}},
{"GOKU", {"PRAG", "PQVF", "PIDI"}},
{"GVLR", {"HCKU", "VUNU", "FIRF"}},
{"GWDK", {"MQJZ", "WTMH", "ZOYJ"}},
{"GXSC", {"MQSO", "FZZK", "QOBC"}},
{"GXYK", {"MLCI", "HWQK", "ERBL"}},
{"HBOM", {"BCAW", "OXRC", "UGKI"}},
{"HDPY", {"JCUZ", "TMKK", "XMVQ"}},
{"HFAN", {"ZQNI", "RPSS", "VFHT"}},
{"HFKU", {"ILOF", "UXKA", "JQLI"}},
{"HFRG", {"YGYA", "IWET", "PSFN"}},
{"HGNV", {"NAFX", "USJN", "IQQJ"}},
{"HHRN", {"IGZW", "ICRP", "QQKJ"}},
{"HIER", {"ZXKC", "BJFL", "PUBL"}},
{"HKGT", {"EBMG", "KDZJ", "MELG"}},
{"HKUO", {"PPET", "QFEZ", "JSKD"}},
{"HOMH", {"BXHI", "WXYD", "VRZY"}},
{"HOWM", {"MJNG", "XPYN", "IRWY"}},
{"HPZO", {"SICM", "XEGH", "TDJJ"}},
{"HPZP", {"NQDY", "QIMT", "QKAK"}},
{"HPZQ", {"XGER", "OLTF", "DVQA"}},
{"HPZR", {"ZAQH", "WPSK", "TCHA"}},
{"HPZS", {"QRFK", "SQGI", "VESI"}},
{"HPZT", {"IUCU", "WDAV", "LOLH"}},
{"HPZV", {"WAFN", "PQVW", "MJVM"}},
{"HPZW", {"TLLY", "WNPD", "XIFO"}},
{"HPZX", {"DNXN", "VHRG", "XTRZ"}},
{"HPZY", {"RAWP", "CNRC", "TPIA"}},
{"HPZZ", {"FJGP", "GMLT", "SZQX"}},
{"HQLQ", {"PGTQ", "NSOB", "GIPH"}},
{"HRIZ", {"BJMA", "SKSL", "XBUU"}},
{"HTPV", {"LAEC", "NGRO", "BGEX"}},
{"HUIJ", {"EVJI", "RNMR", "JQZR"}},
{"HUUA", {"WTWZ", "DONX", "VRYO"}},
{"HVPU", {"HUTT", "JXOO", "HHMM"}},
{"HXIQ", {"QTNX", "AQCS", "VZXB"}},
{"HXZN", {"XTOL", "YHGP", "HMAG"}},
{"HYMD", {"LPEG", "UDVW", "KUBO"}},
{"HYPG", {"FSVQ", "PSWK", "RXGC"}},
{"HYZI", {"YBVF", "EUST", "WJVV"}},
{"IGRW", {"FORO", "KHEK", "BREP"}},
{"IHZG", {"MLLN", "EZTK", "GJEJ"}},
{"INUT", {"BRSN", "OJOO", "DWSP"}},
{"IULQ", {"ICMQ", "ZABS", "XMOU"}},
{"IXMM", {"DIJU", "LAUW", "XHLQ"}},
{"JBPA", {"VUZL", "XYPI", "XOWE"}},
{"JFZB", {"PFDC", "XJDX", "CPXX"}},
{"JGVE", {"DBVB", "YATF", "XFBR"}},
{"JICX", {"GUZK", "TIZA", "HTUW"}},
{"JLGJ", {"HAZJ", "KSWW", "QCYN"}},
{"JLOF", {"IWFR", "CJHY", "DOPK"}},
{"JLRH", {"SAMJ", "GLJZ", "SKTN"}},
{"JOTV", {"QBNM", "NMWE", "IDTV"}},
{"JPUQ", {"OVKI", "AHZL", "YMJY"}},
{"JPZQ", {"CCBQ", "ABTW", "KFNE"}},
{"JQAO", {"OJYT", "ZDWK", "RQXZ"}},
{"JQUD", {"CUTW", "DLJE", "DOON"}},
{"JRVR", {"WGPS", "YETD", "KBWB"}},
{"JTFE", {"DNJK", "FJMW", "QBLT"}},
{"JVAN", {"FQPY", "WNTW", "XWXD"}},
{"JWGY", {"GMIM", "ZNPK", "RGAL"}},
{"JXIS", {"ZYZD", "TEIT", "ILLN"}},
{"JYXK", {"USZT", "XXPU", "LJHH"}},
{"KABJ", {"ISGW", "KOHG", "BPGB"}},
{"KBOV", {"PGBC", "IKKC", "AHSL"}},
{"KDDA", {"DRSL", "IFNA", "BMDE"}},
{"KIMZ", {"FBTQ", "OKNU", "JZIT"}},
{"KLKW", {"PIDD", "JIKU", "QTVN"}},
{"KOKS", {"XCGR", "ZFVG", "PPCB"}},
{"KRTE", {"ILKK", "GNTB", "XFRA"}},
{"KXUH", {"RIFT", "DZUO", "ZSEI"}},
{"LASN", {"ILWC", "BQYG", "RROZ"}},
{"LEAA", {"DHUB", "OBDS", "YMSJ"}},
{"LEAB", {"LRHX", "EFFC", "SZFH"}},
{"LEAC", {"DMEA", "EXWD", "PBTU"}},
{"LEAD", {"QXLJ", "GDOH", "RJNB"}},
{"LEAE", {"QFVM", "GACH", "BMXB"}},
{"LEAF", {"KGXB", "OUVB", "GTLI"}},
{"LEAG", {"XTLW", "WLQO", "QVKP"}},
{"LEAH", {"QIDR", "XBTQ", "QYUO"}},
{"LEAI", {"KCSV", "PRBF", "FVDO"}},
{"LEAJ", {"OBPJ", "NJJS", "WOFS"}},
{"LEAK", {"CGWM", "ZLOS", "JGTD"}},
{"LEAL", {"EYPX", "SOCH", "PFPW"}},
{"LEAM", {"ZGEL", "KZQA", "PSAL"}},
{"LEAN", {"MEYH", "PXTT", "LFVK"}},
{"LEAO", {"MKOE", "YJSI", "QQMN"}},
{"LEAP", {"AEZG", "JOYE", "JHWK"}},
{"LGAA", {"YOGJ", "UGWO", "DAMU"}},
{"LGAB", {"EQRP", "DLUM", "GMAI"}},
{"LIYT", {"CMCZ", "YUAJ", "MFPX"}},
{"LKSP", {"JVAJ", "ZERV", "YAYV"}},
{"LLJI", {"GCIS", "UIQV", "TKJS"}},
{"LOEA", {"YYMF", "ZFDK", "KYJQ"}},
{"LOEB", {"HPPW", "LGZO", "NZIZ"}},
{"LOEC", {"FHUN", "VOTY", "IGUT"}},
{"LOED", {"WULK", "SEKY", "BWRY"}},
{"LOEE", {"GXPA", "MPFZ", "BAOI"}},
{"LOEF", {"DYDQ", "DBBP", "WNKL"}},
{"LOEG", {"WQVR", "VIMS", "XWTK"}},
{"LOEH", {"BLSW", "SRQW", "QJGU"}},
{"LOEI", {"WBJB", "HYVM", "QLRE"}},
{"LOEJ", {"JMPY", "RMIK", "CIPV"}},
{"LOEK", {"CFNY", "YTYX", "MFIU"}},
{"LOEL", {"KPTO", "AEKK", "PBSG"}},
{"LOEM", {"XQSP", "HYHH", "GQQF"}},
{"LOEN", {"FWRN", "XYNF", "TRTB"}},
{"LOEO", {"BNBG", "VSFX", "DMVB"}},
{"LOEP", {"KTKR", "JRUJ", "RYBH"}},
{"LOEQ", {"ZIEG", "IHSZ", "JXFB"}},
{"LOER", {"SOXE", "DIJG", "OHUN"}},
{"LOES", {"PAIY", "JXQE", "ZHPW"}},
{"LOET", {"CKLF", "TDYH", "HOES"}},
{"LOEU", {"LFQU", "ACJS", "DHDJ"}},
{"LOEV", {"YEZD", "CLSN", "JCDI"}},
{"LOEW", {"BYME", "GVQB", "ALXC"}},
{"LOEX", {"DTSE", "FFUO", "GOWI"}},
{"LOEY", {"UJLK", "PIZK", "ASMT"}},
{"LOEZ", {"LDCF", "MYHV", "OZLH"}},
{"LOFA", {"ZHIB", "KAWM", "RSJW"}},
{"LOFB", {"YIHY", "QXQD", "GDXE"}},
{"LOFC", {"IDAK", "FKMQ", "MHSL"}},
{"LOFD", {"PVSV", "WAEK", "JASG"}},
{"LOFE", {"BLWI", "ZXBI", "DMET"}},
{"LOFF", {"XVWG", "LLIC", "AAIM"}},
{"LOFG", {"SMQP", "RFJQ", "HDWV"}},
{"LOFH", {"LBUJ", "DGLT", "EHHF"}},
{"LOFI", {"DJQQ", "QKSW", "HWAJ"}},
{"LOFJ", {"WJXN", "IDHY", "GKCO"}},
{"LOFK", {"VGKG", "SQCD", "SLUY"}},
{"LOFL", {"UYXZ", "AZKR", "RDLY"}},
{"LOFM", {"CVLJ", "UCLO", "PADI"}},
{"LOFO", {"DMJS", "PYYK", "SKQO"}},
{"LOFP", {"DGNA", "ZXHN", "ARBG"}},
{"LOFQ", {"QGKD", "PRZN", "IPEQ"}},
{"LOFR", {"ZOWO", "ZSTS", "JXBM"}},
{"LOFS", {"QEKW", "TTKC", "MQUP"}},
{"LOFT", {"YXFQ", "QFJS", "BNPB"}},
{"LOFU", {"KSMM", "TJWT", "VBMW"}},
{"LOFV", {"NDDC", "BTQU", "HUZE"}},
{"LOFW", {"VLDG", "IPIN", "JAVJ"}},
{"LOFX", {"UWQQ", "IGRC", "GRUT"}},
{"LOFY", {"SCIO", "HJKR", "TBOP"}},
{"LOFZ", {"VSSO", "WSDE", "BHWL"}},
{"LOGB", {"BWRU", "YLCD", "RWLB"}},
{"LOGC", {"YUDR", "THXM", "NBVM"}},
{"LOGD", {"JFPI", "RDCY", "DGJD"}},
{"LOGE", {"ITOL", "GZEC", "INSH"}},
{"LOGF", {"OWNI", "ECYV", "JEFV"}},
{"LOGH", {"RTVE", "EJJV", "DNTX"}},
{"LOGI", {"OEYI", "IKUX", "TCEI"}},
{"LPEW", {"XBJZ", "HTBP", "JQXK"}},
{"LULQ", {"DEHI", "QYXC", "KAGT"}},
{"LYFT", {"LMQF", "CYMI", "ZGEF"}},
{"LYLN", {"XXWY", "JEUV", "RSOC"}},
{"LYVN", {"USOR", "ASKR", "LPGD"}},
{"MAII", {"EOHR", "XZOT", "VJJS"}},
{"MBLE", {"KOCV", "ZLFP", "HOVE"}},
{"MCDN", {"BAOV", "GLVV", "XHGO"}},
{"MCOO", {"IPNW", "CRSK", "QTAX"}},
{"MDPZ", {"AHBA", "ENTF", "IIMC"}},
{"MEXL", {"JFMC", "LBVP", "DERH"}},
{"MNFK", {"BFMJ", "APMV", "LPJQ"}},
{"MNQW", {"LCRH", "YVGU", "SJID"}},
{"MNZG", {"PPTP", "OFXE", "ROJJ"}},
{"MOIP", {"HCCZ", "PXCU", "MROE"}},
{"MQUZ", {"MFAZ", "GBNW", "MRMS"}},
{"MRFF", {"VHZM", "CBXS", "WHGR"}},
{"MXEQ", {"EKJV", "UWUR", "CPES"}},
{"MXUY", {"IRZH", "ADQR", "PCST"}},
{"MYQR", {"VMHK", "QHCZ", "HMFN"}},
{"MZVS", {"VUZM", "RIDT", "URTS"}},
{"NAMM", {"BFSS", "BKVK", "EBDV"}},
{"NBQS", {"KMJF", "MFWA", "UWRX"}},
{"NGVJ", {"GVZG", "GJWP", "CFNU"}},
{"NISD", {"MISA", "YDPG", "NCLQ"}},
{"NMOG", {"UYQU", "ZWTV", "TQFQ"}},
{"NOMD", {"GZLV", "UNZR", "FVOP"}},
{"NPEC", {"BMGD", "YETH", "XAWJ"}},
{"NSXI", {"VYQS", "HGFQ", "SLFL"}},
{"NZRH", {"NOUG", "UDYG", "ZGAU"}},
{"ODVK", {"VIOP", "MIHJ", "VXFY"}},
{"OFPE", {"YFOO", "UIGY", "PFGZ"}},
{"OFPO", {"TSWQ", "EBUR", "JASZ"}},
{"OIFF", {"MLXE", "KFNX", "CRAQ"}},
{"OIXD", {"UNMJ", "EGQA", "GIAQ"}},
{"OKWC", {"RGFB", "UPFP", "HUVK"}},
{"OPNA", {"JDSG", "BCNO", "THKI"}},
{"OYZI", {"WDBC", "NKZT", "QJZD"}},
{"PAZD", {"VARX", "KZSU", "WPLH"}},
{"PEVA", {"RBMX", "IBPY", "ALNV"}},
{"PGQF", {"USPJ", "SFKO", "KNBH"}},
{"PHYB", {"EGXD", "KHYC", "QUPU"}},
{"PIGM", {"FEBY", "YTML", "VFLZ"}},
{"PLKQ", {"EXXM", "LBZT", "SPDN"}},
{"PRYU", {"QFZV", "TZXL", "EPRT"}},
{"PULG", {"OXHS", "IBTI", "EKUW"}},
{"PVHI", {"FUBQ", "URIF", "UATZ"}},
{"PWFL", {"WGJQ", "KMBF", "UKJV"}},
{"PXDO", {"ZXCF", "TQWC", "HOAL"}},
{"QACT", {"YQSO", "OFRB", "HGQL"}},
{"QAPN", {"EMNZ", "SJTH", "HJKU"}},
{"QBJC", {"WAQG", "MSEN", "FQYE"}},
{"QBTA", {"UDQV", "UIZV", "SGMN"}},
{"QCDF", {"HOUC", "PKTP", "APSD"}},
{"QGJP", {"SUJW", "VGYV", "DOGG"}},
{"QJHH", {"TIHM", "SOII", "SXVL"}},
{"QKTA", {"USGV", "UPMS", "ZVTZ"}},
{"QLDV", {"BJRT", "ZICU", "URBL"}},
{"QLWW", {"LNZB", "JTVW", "XVCX"}},
{"QNDA", {"VFMY", "KTBL", "UOJY"}},
{"QQFU", {"ZUKV", "QBAU", "SIID"}},
{"QSHQ", {"JNSW", "UILC", "UHMT"}},
{"QSIM", {"ZCML", "LEPJ", "QQEM"}},
{"QTMI", {"YMOW", "FZIR", "YKGT"}},
{"QVKE", {"FIQU", "CVOM", "LPVD"}},
{"QYGU", {"FYBR", "QLFJ", "OLRV"}},
{"QZPR", {"SLSU", "LFCQ", "TKBG"}},
{"QZUX", {"HNBM", "BUJY", "FFDE"}},
{"RAKQ", {"LDHH", "NAML", "LKFR"}},
{"RGDH", {"YWKM", "ZBAR", "RMQQ"}},
{"RGNF", {"SDGJ", "KEWA", "GITE"}},
{"RHDN", {"MGVK", "EQPB", "UAHY"}},
{"RIKG", {"VRBT", "LEPX", "VWIV"}},
{"RKRB", {"OPOY", "QMZZ", "FAGR"}},
{"RLGE", {"NTKV", "LOTA", "MJVG"}},
{"RNPH", {"TSIF", "ESCP", "GISR"}},
{"RVKU", {"EVWH", "THXH", "GROS"}},
{"RVRM", {"MZJU", "IGXP", "DSJP"}},
{"RXGN", {"WHNA", "DWVK", "FRWP"}},
{"RYMB", {"ZITN", "TMGX", "HVCV"}},
{"SBBR", {"IMRL", "LZCR", "WJQV"}},
{"SBGV", {"ZNIN", "ZVZV", "BPJY"}},
{"SFGV", {"TSMJ", "SVHE", "WNOP"}},
{"SGGB", {"HSKN", "BECX", "NFTY"}},
{"SHAN", {"OERN", "XNHK", "GVYX"}},
{"SKIW", {"CLPF", "OTYY", "ZJVP"}},
{"SMAC", {"FDEX", "ZFXY", "DJMW"}},
{"SMAD", {"AADC", "URZK", "UBVE"}},
{"SMAE", {"SUUV", "QXWL", "LYKX"}},
{"SMAF", {"HKPA", "NFCE", "UBOP"}},
{"SMAG", {"DPGH", "PQFA", "ROEP"}},
{"SMAH", {"EXLB", "YYYY", "LLLA"}},
{"SMAI", {"PPDO", "ISMM", "BKNT"}},
{"SMAJ", {"PVCB", "UCIK", "XVBK"}},
{"SMAK", {"WOMZ", "OHAX", "JSTF"}},
{"SMAL", {"OWLX", "YXSA", "TXJR"}},
{"SOCA", {"AJGR", "IYZW", "NPDX"}},
{"SSLV", {"IUFZ", "NTYF", "TWGJ"}},
{"SSVR", {"NZKV", "NGLW", "LDCH"}},
{"STMU", {"HKNS", "OFBT", "RWDO"}},
{"SUCA", {"JSZT", "IBUF", "HMEZ"}},
{"SVGZ", {"WWDD", "EJWL", "TJFT"}},
{"SWLP", {"GLDC", "WZKJ", "GTXT"}},
{"SYDL", {"CGGV", "VDEY", "UZDR"}},
{"TAAB", {"ZBMY", "NYDT", "CXYZ"}},
{"TAAC", {"YBVP", "RXXN", "HMDY"}},
{"TBKT", {"IBUN", "QLQQ", "CRBQ"}},
{"TFIY", {"RVUF", "DHKE", "GFPK"}},
{"THNQ", {"XMVV", "RUHW", "WWLP"}},
{"TJKH", {"ZHMG", "RBXM", "VIVU"}},
{"TKER", {"KOSM", "IUCL", "LIIM"}},
{"TKZT", {"KWCM", "APLN", "STGO"}},
{"TMSE", {"PSOE", "RFGT", "DVAS"}},
{"TMTX", {"CNAW", "BEDK", "HGOT"}},
{"TNFY", {"LGZD", "QNOV", "XCQG"}},
{"TPHN", {"DGRC", "EDPM", "FLCE"}},
{"TQAU", {"PUVO", "MASK", "LJBB"}},
{"TSNX", {"NLLF", "DJAG", "FBBO"}},
{"TVRZ", {"XWBR", "VSOG", "WGJH"}},
{"TXMN", {"WTVY", "GJTZ", "KMRI"}},
{"TYOO", {"EGWA", "BJJJ", "GOKE"}},
{"TZIV", {"XWTU", "JFLV", "JLEU"}},
{"UBKE", {"CPTX", "EGAC", "MRXT"}},
{"UGAY", {"YDHM", "HVCY", "ILHO"}},
{"UMAU", {"FKAK", "JCTZ", "GDUU"}},
{"UPPG", {"HYSS", "KHZT", "QQZJ"}},
{"UQDN", {"LWWF", "SCDS", "IKKY"}},
{"UQUC", {"YLQO", "IDZV", "PXQW"}},
{"URZD", {"QDAL", "YLWB", "XCCP"}},
{"UTTX", {"OZET", "BYVE", "PLSI"}},
{"UUCL", {"HELE", "KEDZ", "ZAAI"}},
{"VEUT", {"JDFA", "ALIR", "DDJM"}},
{"VGYW", {"AAXS", "SHZF", "HYJU"}},
{"VHUH", {"JYDF", "SFJY", "JMBU"}},
{"VICR", {"VNCX", "OLSV", "YCZO"}},
{"VJVS", {"BVOQ", "KREV", "QRKT"}},
{"VJXU", {"ANLP", "KACE", "KWVH"}},
{"VRWC", {"OGMF", "GYJX", "NOBB"}},
{"VVUC", {"WQCU", "YUMW", "YHYC"}},
{"VYNC", {"MBDE", "ZHLY", "EESD"}},
{"VYRC", {"VKSO", "NKTO", "ZPZX"}},
{"VZMB", {"YCKT", "WSPC", "SHYP"}},
{"WBZQ", {"LAYK", "LQDM", "QBFV"}},
{"WCLL", {"DALK", "WPRA", "TPTP"}},
{"WFIQ", {"KKHX", "UTHS", "HDSP"}},
{"WFVB", {"UQPS", "NZRZ", "GJNX"}},
{"WJOZ", {"BASQ", "BRTL", "CQAV"}},
{"WMMD", {"HBFI", "XBKO", "LCEC"}},
{"WMPI", {"POXG", "VCJD", "WEGX"}},
{"WMVU", {"GMMR", "AVVS", "IMDF"}},
{"WNNA", {"ERXU", "TWMI", "ZOER"}},
{"WPBT", {"VUKV", "DLTH", "CQBD"}},
{"WVRW", {"GJGN", "QQFA", "AGVP"}},
{"WWTI", {"GZHX", "JHGD", "ZDGL"}},
{"WXZG", {"IUGR", "JOEE", "PTHY"}},
{"XAJY", {"UWFH", "BVFB", "OLQX"}},
{"XBWL", {"IQEI", "JEGU", "QSKW"}},
{"XFUX", {"UHAM", "NEHU", "SHMG"}},
{"XHVI", {"KVWL", "GQOJ", "JLLW"}},
{"XIYN", {"ZZYC", "OJOW", "NTKR"}},
{"XJKD", {"HGKR", "DNEI", "MBFP"}},
{"XLUK", {"ARRX", "SCBM", "TIWT"}},
{"XOGA", {"BIWO", "JPWZ", "YYDG"}},
{"XOKS", {"DEVR", "YKLR", "QYBF"}},
{"XVTK", {"TMUU", "BTWW", "THQH"}},
{"XVYQ", {"UAVB", "OEMI", "VQVK"}},
{"XWJE", {"KDZI", "IYPJ", "ERIM"}},
{"YAVR", {"DHAY", "KBWN", "BBPJ"}},
{"YEGM", {"SEQF", "OXKW", "OFEF"}},
{"YFVF", {"NPWS", "PUZZ", "TTCZ"}},
{"YGHA", {"BMDT", "AUXW", "GYPE"}},
{"YHYU", {"CDLM", "QDXQ", "HPTE"}},
{"YLRO", {"ZQHU", "SFQD", "YNOL"}},
{"YMJL", {"LBTX", "YPBE", "LHMF"}},
{"YMMU", {"ZVIA", "CFKN", "ERLO"}},
{"YPCE", {"CCCC", "VHQK", "PYBL"}},
{"YPPO", {"TRIY", "TMUA", "AMPD"}},
{"YQWT", {"KEBH", "PAMG", "ACOF"}},
{"YTGY", {"PRXN", "QEZG", "FOSO"}},
{"YVRQ", {"LBMS", "AKKB", "UFNF"}},
{"YXBK", {"VKAU", "HUNQ", "AFRP"}},
{"YXED", {"KDUD", "MTUI", "WLHI"}},
{"YXMK", {"ZUSE", "TZFU", "DVKA"}},
{"ZBCF", {"BDTW", "MIQF", "VUNL"}},
{"ZDKS", {"UBRP", "AWQF", "GOVG"}},
{"ZDYJ", {"JNGY", "SDRU", "YIEW"}},
{"ZFCZ", {"JQUA", "SEEH", "RJVV"}},
{"ZFNX", {"DMVG", "EVBR", "SUXX"}},
{"ZFVI", {"DHXX", "NXUJ", "HVXK"}},
{"ZHKO", {"PEIC", "UYOS", "NVYS"}},
{"ZIWS", {"GSAE", "JJUF", "ZPRA"}},
{"ZJLO", {"HLMS", "OHWG", "HMAL"}},
{"ZKJH", {"OBDQ", "OUAQ", "SPYY"}},
{"ZLBC", {"DJCJ", "HNGZ", "IRYZ"}},
{"ZPIS", {"VXIY", "HUUG", "GHXQ"}},
{"ZSKM", {"JPEZ", "FTUS", "ZFUF"}},
{"ZSLY", {"TQED", "GKPV", "BHWH"}},
{"ZZAB", {"WVIK", "IUXK", "ZCIK"}},
{"ZZAC", {"MBDD", "SMUW", "JEIY"}},
{"ZZAD", {"KSTH", "CBJY", "TSID"}},
{"ZZAF", {"OTWH", "RRNB", "VNXA"}},
{"ZZTB", {"MXQT", "JUUX", "FMFR"}}});
const auto it = kBrandCodeMap->find(static_brand_code);
if (it == kBrandCodeMap->end())
return static_brand_code;
const auto& entry = it->second;
// An empty value indicates the device is not enrolled.
if (!market_segment.has_value())
return entry.unenrolled_brand_code;
switch (market_segment.value()) {
case policy::MarketSegment::EDUCATION:
return entry.education_enrolled_brand_code;
case policy::MarketSegment::ENTERPRISE:
case policy::MarketSegment::UNKNOWN:
// If the device is enrolled but market segment is unknown, it's fine to
// treat it as enterprise enrolled.
return entry.enterprise_enrolled_brand_code;
}
NOTREACHED();
return static_brand_code;
}
} // namespace chromeos
} // namespace google_brand
| bsd-3-clause |
frankwiles/django-admin-views | example_project/example_project/urls.py | 566 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Examples:
# url(r'^$', 'example_project.views.home', name='home'),
# url(r'^example_project/', include('example_project.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
]
| bsd-3-clause |
NCIP/annotation-and-image-markup | AIMToolkit_v3.0.2_rv11/source/dcmtk-3.6.0/dcmnet/libsrc/scu.cc | 45969 | /*
*
* Copyright (C) 2008-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmnet
*
* Author: Michael Onken
*
* Purpose: Base class for Service Class Users (SCUs)
*
* Last Update: $Author: onken $
* Update Date: $Date: 2010-12-21 09:37:36 $
* CVS/RCS Revision: $Revision: 1.16 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dcuid.h" /* for dcmFindUIDName() */
#include "dcmtk/dcmnet/scu.h"
#include "dcmtk/dcmnet/diutil.h" /* for dcmnet logger */
DcmSCU::DcmSCU() :
m_assoc(NULL),
m_net(NULL),
m_params(NULL),
m_assocConfigFilename(),
m_assocConfigProfile(),
m_presContexts(),
m_openDIMSERequest(NULL),
m_maxReceivePDULength(ASC_DEFAULTMAXPDU),
m_blockMode(DIMSE_BLOCKING),
m_ourAETitle("ANY-SCU"),
m_peer(),
m_peerAETitle("ANY-SCP"),
m_peerPort(104),
m_dimseTimeout(0),
m_acseTimeout(30),
m_verbosePCMode(OFFalse)
{
#ifdef HAVE_GUSI_H
GUSISetup(GUSIwithSIOUXSockets);
GUSISetup(GUSIwithInternetSockets);
#endif
#ifdef HAVE_WINSOCK_H
WSAData winSockData;
/* we need at least version 1.1 */
WORD winSockVersionNeeded = MAKEWORD( 1, 1 );
WSAStartup(winSockVersionNeeded, &winSockData); // TODO: check with multiple SCU instances whether this is harmful
#endif
}
DcmSCU::~DcmSCU()
{
// abort association (if any) and destroy dcmnet data structures
if (isConnected())
{
closeAssociation(DCMSCU_ABORT_ASSOCIATION);
} else {
if ((m_assoc != NULL) || (m_net != NULL))
DCMNET_DEBUG("Cleaning up internal association and network structures");
ASC_destroyAssociation(&m_assoc);
ASC_dropNetwork(&m_net);
}
// free memory allocated by this class
delete m_openDIMSERequest;
#ifdef HAVE_WINSOCK_H
WSACleanup(); // TODO: check with multiple SCU instances whether this is harmful
#endif
}
OFCondition DcmSCU::initNetwork()
{
// TODO: do we need to check whether the network is already initialized?
OFString tempStr;
/* initialize network, i.e. create an instance of T_ASC_Network*. */
OFCondition cond = ASC_initializeNetwork(NET_REQUESTOR, 0, m_acseTimeout, &m_net);
if (cond.bad())
{
DimseCondition::dump(tempStr, cond);
DCMNET_ERROR(tempStr);
return cond;
}
/* initialize asscociation parameters, i.e. create an instance of T_ASC_Parameters*. */
cond = ASC_createAssociationParameters(&m_params, m_maxReceivePDULength);
if (cond.bad())
{
DCMNET_ERROR(DimseCondition::dump(tempStr, cond));
return cond;
}
/* sets this application's title and the called application's title in the params */
/* structure. The default values are "ANY-SCU" and "ANY-SCP". */
ASC_setAPTitles(m_params, m_ourAETitle.c_str(), m_peerAETitle.c_str(), NULL);
/* Figure out the presentation addresses and copy the */
/* corresponding values into the association parameters.*/
DIC_NODENAME localHost;
DIC_NODENAME peerHost;
gethostname(localHost, sizeof(localHost) - 1);
/* Since the underlying dcmnet structures reserve only 64 bytes for peer
as well as local host name, we check here for buffer overflow.
*/
if ((m_peer.length() + 5 /* max 65535 */) + 1 /* for ":" */ > 63)
{
DCMNET_ERROR("Maximum length of peer host name '" << m_peer << "' is longer than maximum of 57 characters");
return EC_IllegalCall; // TODO: need to find better error code
}
if (strlen(localHost) + 1 > 63)
{
DCMNET_ERROR("Maximum length of local host name '" << localHost << " is longer than maximum of 62 characters");
return EC_IllegalCall; // TODO: need to find better error code
}
sprintf(peerHost, "%s:%d", m_peer.c_str(), OFstatic_cast(int, m_peerPort));
ASC_setPresentationAddresses(m_params, localHost, peerHost);
/* Add presentation contexts */
// First, import from config file, if specified
OFCondition result;
if (m_assocConfigFilename.length() != 0)
{
DcmAssociationConfiguration assocConfig;
result = DcmAssociationConfigurationFile::initialize(assocConfig, m_assocConfigFilename.c_str());
if (result.bad())
{
DCMNET_WARN("Unable to parse association configuration file " << m_assocConfigFilename
<< " (ignored): " << result.text());
return result;
}
else
{
/* perform name mangling for config file key */
OFString profileName;
const unsigned char *c = OFreinterpret_cast(const unsigned char *, m_assocConfigProfile.c_str());
while (*c)
{
if (! isspace(*c)) profileName += OFstatic_cast(char, toupper(*c));
++c;
}
result = assocConfig.setAssociationParameters(profileName.c_str(), *m_params);
if (result.bad())
{
DCMNET_WARN("Unable to apply association configuration file" << m_assocConfigFilename
<<" (ignored): " << result.text());
return result;
}
}
}
// Adapt presentation context ID to existing presentation contexts
// It's important that presentation context ids are numerated 1,3,5,7...!
Uint32 nextFreePresID = 257;
Uint32 numContexts = ASC_countPresentationContexts(m_params);
if (numContexts <= 127)
{
// Need Uint16 to avoid overflow in currPresID (unsigned char)
nextFreePresID = 2 * numContexts + 1; /* add 1 to point to the next free ID*/
}
// Print warning if number of overall presenation contexts exceeds 128
if ((numContexts + m_presContexts.size()) > 128)
{
DCMNET_WARN("Number of presentation contexts exceeds 128 (" << numContexts + m_presContexts.size()
<< "). Some contexts will not be negotiated");
}
else
{
DCMNET_TRACE("Configured " << numContexts << " presentation contexts from config file");
if (m_presContexts.size() > 0)
DCMNET_TRACE("Adding another " << m_presContexts.size() << " presentation contexts configured for SCU");
}
// Add presentation contexts not originating from config file
OFListIterator(DcmSCUPresContext) contIt = m_presContexts.begin();
OFListConstIterator(DcmSCUPresContext) endOfContList = m_presContexts.end();
while ((contIt != endOfContList) && (nextFreePresID <= 255))
{
const Uint16 numTransferSyntaxes = (*contIt).transferSyntaxes.size();
const char** transferSyntaxes = new const char*[numTransferSyntaxes];
// Iterate over transfer syntaxes within one presentation context
OFListIterator(OFString) syntaxIt = (*contIt).transferSyntaxes.begin();
OFListIterator(OFString) endOfSyntaxList = (*contIt).transferSyntaxes.end();
Uint16 sNum = 0;
// copy all transfersyntaxes to array
while (syntaxIt != endOfSyntaxList)
{
transferSyntaxes[sNum] = (*syntaxIt).c_str();
++syntaxIt;
++sNum;
}
// add the presentation context
cond = ASC_addPresentationContext(m_params, OFstatic_cast(Uint8, nextFreePresID),
(*contIt).abstractSyntaxName.c_str(), transferSyntaxes, numTransferSyntaxes);
// if adding was successfull, prepare pres. context ID for next addition
delete[] transferSyntaxes;
transferSyntaxes = NULL;
if (cond.bad())
return cond;
contIt++;
// goto next free nr, only odd presentation context numbers permitted
nextFreePresID += 2;
}
numContexts = ASC_countPresentationContexts(m_params);
if (numContexts == 0)
{
DCMNET_ERROR("Cannot initialize network: No presentation contexts defined");
return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
}
DCMNET_DEBUG("Configured a total of " << numContexts << " presentation contexts for SCU");
return cond;
}
OFCondition DcmSCU::negotiateAssociation()
{
/* dump presentation contexts if required */
OFString tempStr;
if (m_verbosePCMode)
DCMNET_INFO("Request Parameters:" << OFendl << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_RQ));
else
DCMNET_DEBUG("Request Parameters:" << OFendl << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_RQ));
/* create association, i.e. try to establish a network connection to another */
/* DICOM application. This call creates an instance of T_ASC_Association*. */
DCMNET_INFO("Requesting Association");
OFCondition cond = ASC_requestAssociation(m_net, m_params, &m_assoc);
if (cond.bad())
{
if (cond == DUL_ASSOCIATIONREJECTED)
{
T_ASC_RejectParameters rej;
ASC_getRejectParameters(m_params, &rej);
DCMNET_DEBUG("Association Rejected:" << OFendl << ASC_printRejectParameters(tempStr, &rej));
return cond;
}
else
{
DCMNET_DEBUG("Association Request Failed: " << DimseCondition::dump(tempStr, cond));
return cond;
}
}
/* dump the presentation contexts which have been accepted/refused */
if (m_verbosePCMode)
DCMNET_INFO("Association Parameters Negotiated:" << OFendl << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_AC));
else
DCMNET_DEBUG("Association Parameters Negotiated:" << OFendl << ASC_dumpParameters(tempStr, m_params, ASC_ASSOC_AC));
/* count the presentation contexts which have been accepted by the SCP */
/* If there are none, finish the execution */
if (ASC_countAcceptedPresentationContexts(m_params) == 0)
{
DCMNET_ERROR("No Acceptable Presentation Contexts");
return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
}
/* dump general information concerning the establishment of the network connection if required */
DCMNET_INFO("Association Accepted (Max Send PDV: " << OFstatic_cast(unsigned long, m_assoc->sendPDVLength) << ")");
return EC_Normal;
}
OFCondition DcmSCU::addPresentationContext(const OFString &abstractSyntax,
const OFList<OFString> &xferSyntaxes)
{
DcmSCUPresContext presContext;
presContext.abstractSyntaxName = abstractSyntax;
OFListConstIterator(OFString) it = xferSyntaxes.begin();
OFListConstIterator(OFString) endOfList = xferSyntaxes.end();
while (it != endOfList)
{
presContext.transferSyntaxes.push_back(*it);
it++;
}
m_presContexts.push_back(presContext);
return EC_Normal;
}
OFCondition DcmSCU::useSecureConnection(DcmTransportLayer *tlayer)
{
OFCondition cond = ASC_setTransportLayer(m_net, tlayer, OFFalse /* do not take over ownership */);
if (cond.good())
cond = ASC_setTransportLayerType(m_params, OFTrue /* use TLS */);
return cond;
}
// Reads association configuration from config file
OFCondition readAssocConfigFromFile(const OFString &filename,
const OFString & /* profile */)
{
DcmAssociationConfiguration assocConfig;
OFCondition result = DcmAssociationConfigurationFile::initialize(assocConfig, filename.c_str());
return result;
}
// Returns usable presentation context ID for given abstract syntax and UID
// transfer syntax UID. 0 if none matches.
T_ASC_PresentationContextID DcmSCU::findPresentationContextID(const OFString &abstractSyntax,
const OFString &transferSyntax)
{
if (m_assoc == NULL)
return 0;
DUL_PRESENTATIONCONTEXT *pc;
LST_HEAD **l;
OFBool found = OFFalse;
if (abstractSyntax.empty()) return 0;
/* first of all we look for a presentation context
* matching both abstract and transfer syntax
*/
l = &m_assoc->params->DULparams.acceptedPresentationContext;
pc = (DUL_PRESENTATIONCONTEXT*) LST_Head(l);
(void)LST_Position(l, (LST_NODE*)pc);
while (pc && !found)
{
found = (strcmp(pc->abstractSyntax, abstractSyntax.c_str()) == 0);
found &= (pc->result == ASC_P_ACCEPTANCE);
if (!transferSyntax.empty()) // ignore transfer syntax if not specified
found &= (strcmp(pc->acceptedTransferSyntax, transferSyntax.c_str()) == 0);
if (!found) pc = (DUL_PRESENTATIONCONTEXT*) LST_Next(l);
}
if (found) return pc->presentationContextID;
return 0; /* not found */
}
void DcmSCU::findPresentationContext(const T_ASC_PresentationContextID presID,
OFString &abstractSyntax,
OFString &transferSyntax)
{
transferSyntax.clear();
abstractSyntax.clear();
if (m_assoc == NULL)
return;
DUL_PRESENTATIONCONTEXT *pc;
LST_HEAD **l;
/* first of all we look for a presentation context
* matching both abstract and transfer syntax
*/
l = &m_assoc->params->DULparams.acceptedPresentationContext;
pc = (DUL_PRESENTATIONCONTEXT*) LST_Head(l);
(void)LST_Position(l, (LST_NODE*)pc);
while (pc)
{
if ((presID == pc->presentationContextID) && (pc->result == ASC_P_ACCEPTANCE))
{
// found a match
transferSyntax = pc->acceptedTransferSyntax;
abstractSyntax = pc->abstractSyntax;
return;
}
pc = (DUL_PRESENTATIONCONTEXT*) LST_Next(l);
}
return; /* not found */
}
Uint16 DcmSCU::nextMessageID()
{
if (m_assoc == NULL)
return 0;
else
return m_assoc->nextMsgID++;
}
void DcmSCU::closeAssociation(const DcmCloseAssociationType closeType)
{
OFCondition cond;
OFString tempStr;
/* tear down association, i.e. terminate network connection to SCP */
switch (closeType)
{
case DCMSCU_RELEASE_ASSOCIATION:
/* release association */
DCMNET_INFO("Releasing Association");
cond = ASC_releaseAssociation(m_assoc);
if (cond.bad())
{
DCMNET_ERROR("Association Release Failed: " << DimseCondition::dump(tempStr, cond));
return; // TODO: do we really need this?
}
break;
case DCMSCU_ABORT_ASSOCIATION:
/* abort association */
DCMNET_INFO("Aborting Association");
cond = ASC_abortAssociation(m_assoc);
if (cond.bad())
{
DCMNET_ERROR("Association Abort Failed: " << DimseCondition::dump(tempStr, cond));
}
break;
case DCMSCU_PEER_REQUESTED_RELEASE:
/* peer requested release */
DCMNET_ERROR("Protocol Error: Peer requested release (Aborting)");
DCMNET_INFO("Aborting Association");
cond = ASC_abortAssociation(m_assoc);
if (cond.bad())
{
DCMNET_ERROR("Association Abort Failed: " << DimseCondition::dump(tempStr, cond));
}
break;
case DCMSCU_PEER_ABORTED_ASSOCIATION:
/* peer aborted association */
DCMNET_INFO("Peer Aborted Association");
break;
}
/* destroy the association, i.e. free memory of T_ASC_Association* structure. This */
/* call is the counterpart of ASC_requestAssociation(...) which was called above. */
cond = ASC_destroyAssociation(&m_assoc);
if (cond.bad())
{
DCMNET_ERROR("Unable to clean up internal association structures: " << DimseCondition::dump(tempStr, cond));
}
/* drop the network, i.e. free memory of T_ASC_Network* structure. This call */
/* is the counterpart of ASC_initializeNetwork(...) which was called above. */
cond = ASC_dropNetwork(&m_net);
if (cond.bad())
{
DCMNET_ERROR("Unable to clean up internal network structures: " << DimseCondition::dump(tempStr, cond));
}
}
// Sends C-ECHO request to another DICOM application
OFCondition DcmSCU::sendECHORequest(const T_ASC_PresentationContextID presID)
{
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
OFCondition cond;
T_ASC_PresentationContextID pcid = presID;
/* If necessary, find appropriate presentation context */
if (pcid == 0)
pcid = findPresentationContextID(UID_VerificationSOPClass, UID_LittleEndianExplicitTransferSyntax);
if (pcid == 0)
pcid = findPresentationContextID(UID_VerificationSOPClass, UID_BigEndianExplicitTransferSyntax);
if (pcid == 0)
pcid = findPresentationContextID(UID_VerificationSOPClass, UID_LittleEndianImplicitTransferSyntax);
if (pcid == 0)
{
DCMNET_ERROR("No presentation context found for sending C-ECHO with SOP Class / Transfer Syntax: "
<< dcmFindNameOfUID(UID_VerificationSOPClass, "") << "/"
<< DcmXfer(UID_LittleEndianImplicitTransferSyntax).getXferName());
return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
}
/* Now, assemble dimse message */
Uint16 status;
cond = DIMSE_echoUser(m_assoc, nextMessageID(), m_blockMode, m_dimseTimeout, &status, NULL);
if (cond.bad())
{
OFString tempStr;
DCMNET_ERROR("Failed sending C-ECHO request or receiving response: " << DimseCondition::dump(tempStr, cond));
return cond;
}
else
{
if (status == STATUS_Success)
DCMNET_DEBUG("Successfully sent C-ECHO request");
else
{
DCMNET_ERROR("C-ECHO failed with status code: 0x"
<< STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4) << status);
return makeOFCondition(OFM_dcmnet, 22, OF_error, "SCP returned non-success status in C-ECHO response");
}
}
return EC_Normal;
}
// Sends C-STORE request to another DICOM application
OFCondition DcmSCU::sendSTORERequest(const T_ASC_PresentationContextID presID,
const OFString &dicomFile,
DcmDataset *dset,
DcmDataset *& /* rspCommandSet */, // TODO
DcmDataset *& /* rspStatusDetail */, // TODO
Uint16 &rspStatusCode)
{
// Do some basic validity checks
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
OFCondition cond;
OFString tempStr;
T_ASC_PresentationContextID pcid = presID;
DcmDataset* statusDetail = NULL;
T_DIMSE_Message msg;
T_DIMSE_C_StoreRQ* req = &(msg.msg.CStoreRQ);
// Set type of message
msg.CommandField = DIMSE_C_STORE_RQ;
/* Set message ID */
req->MessageID = nextMessageID();
/* Load file if necessary */
OFString sopClass, sopInstance;
E_TransferSyntax transferSyntax = EXS_Unknown; // Initialized in getDatasetInfo()
DcmFileFormat *dcmff = NULL;
if (!dicomFile.empty())
{
dcmff = new DcmFileFormat();
if (dcmff == NULL) return EC_MemoryExhausted;
cond = dcmff->loadFile(dicomFile.c_str());
if (cond.bad())
return cond;
dset = dcmff->getDataset();
}
/* Fill message according to dataset to be sent */
cond = getDatasetInfo(dset, sopClass, sopInstance, transferSyntax);
if ((dset == NULL) || sopClass.empty() || sopInstance.empty() || (transferSyntax == EXS_Unknown))
{
DCMNET_ERROR("Cannot send DICOM file, missing information:");
DCMNET_ERROR(" SOP Class UID: " << sopClass);
DCMNET_ERROR(" SOP Instance UID: " << sopInstance);
DCMNET_ERROR(" Transfersyntax: " << DcmXfer(transferSyntax).getXferName());
delete dcmff;
dcmff = NULL;
return EC_IllegalParameter;
}
OFStandard::strlcpy(req->AffectedSOPClassUID, sopClass.c_str(), sizeof(req->AffectedSOPClassUID));
OFStandard::strlcpy(req->AffectedSOPInstanceUID, sopInstance.c_str(), sizeof(req->AffectedSOPInstanceUID));
req->DataSetType = DIMSE_DATASET_PRESENT;
/* If necessary, find appropriate presentation context */
if (pcid == 0)
pcid = findPresentationContextID(sopClass, DcmXfer(transferSyntax).getXferID());
if (pcid == 0)
{
OFString sopname = dcmFindNameOfUID(sopClass.c_str(), sopClass.c_str());
OFString tsname = DcmXfer(transferSyntax).getXferName();
DCMNET_ERROR("No presentation context found for sending C-STORE with SOP Class / Transfer Syntax: "
<< sopname << "/"
<< (tsname.empty() ? DcmXfer(transferSyntax).getXferName() : tsname));
return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
}
/* Send request */
DCMNET_INFO("Send C-STORE Request");
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, NULL, pcid));
cond = sendDIMSEMessage(pcid, &msg, dset, NULL /* callback */, NULL /* callbackContext */);
delete dcmff;
dcmff = NULL;
if (cond.bad())
{
DCMNET_ERROR("Failed sending C-STORE request: " << DimseCondition::dump(tempStr, cond));
return cond;
}
/* Receive response */
T_DIMSE_Message rsp;
cond = receiveDIMSECommand(&pcid, &rsp, &statusDetail, NULL /* not interested in the command set */);
if (cond.bad())
{
DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
return cond;
}
if (rsp.CommandField == DIMSE_C_STORE_RSP)
{
DCMNET_INFO("Received C-STORE Response");
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
} else {
DCMNET_ERROR("Expected C-STORE response but received DIMSE command 0x"
<< STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
<< OFstatic_cast(unsigned int, rsp.CommandField));
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
return DIMSE_BADCOMMANDTYPE;
}
T_DIMSE_C_StoreRSP storeRsp = rsp.msg.CStoreRSP;
rspStatusCode = storeRsp.DimseStatus;
if (statusDetail != NULL)
{
DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
delete statusDetail;
}
return cond;
}
// Sends a C-FIND Request on given presentation context
OFCondition DcmSCU::sendFINDRequest(const T_ASC_PresentationContextID presID,
DcmDataset *queryKeys,
FINDResponses *responses)
{
// Do some basic validity checks
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
if (queryKeys == NULL)
return ASC_NULLKEY;
/* Prepare DIMSE data structures for issuing request */
OFCondition cond;
OFString tempStr;
T_ASC_PresentationContextID pcid = presID;
T_DIMSE_Message msg;
DcmDataset* statusDetail = NULL;
T_DIMSE_C_FindRQ* req = &(msg.msg.CFindRQ);
// Set type of message
msg.CommandField = DIMSE_C_FIND_RQ;
// Set message ID
req->MessageID = nextMessageID();
// Announce dataset
req->DataSetType = DIMSE_DATASET_PRESENT;
// Determine SOP Class from presentation context
OFString abstractSyntax, transferSyntax;
findPresentationContext(pcid, abstractSyntax, transferSyntax);
if (abstractSyntax.empty() || transferSyntax.empty())
return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
OFStandard::strlcpy(req->AffectedSOPClassUID, abstractSyntax.c_str(), sizeof(req->AffectedSOPClassUID));
DCMNET_INFO("Send C-FIND Request");
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, msg, DIMSE_OUTGOING, NULL, pcid));
cond = sendDIMSEMessage(pcid, &msg, queryKeys, NULL /* callback */, NULL /* callbackContext */);
if (cond.bad())
{
DCMNET_ERROR("Failed sending C-FIND request: " << DimseCondition::dump(tempStr, cond));
return cond;
}
/* Receive and handle response */
OFBool waitForNextResponse = OFTrue;
while (waitForNextResponse)
{
T_DIMSE_Message rsp;
statusDetail = NULL;
// Receive command set
cond = receiveDIMSECommand(&pcid, &rsp, &statusDetail, NULL /* not interested in the command set */);
if (cond.bad())
{
DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
return cond;
}
if (rsp.CommandField == DIMSE_C_FIND_RSP)
{
DCMNET_INFO("Received C-FIND Response");
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
} else {
DCMNET_ERROR("Expected C-FIND response but received DIMSE command 0x"
<< STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
<< OFstatic_cast(unsigned int, rsp.CommandField));
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, rsp, DIMSE_INCOMING, NULL, pcid));
return DIMSE_BADCOMMANDTYPE;
}
// Prepare response package for response handler
FINDResponse *findrsp = new FINDResponse();
findrsp->m_affectedSOPClassUID = rsp.msg.CFindRSP.AffectedSOPClassUID;
findrsp->m_messageIDRespondedTo = rsp.msg.CFindRSP.MessageIDBeingRespondedTo;
findrsp->m_status = rsp.msg.CFindRSP.DimseStatus;
DCMNET_DEBUG("Response has status " << findrsp->m_status);
// Receive dataset if there is one (status PENDING)
DcmDataset *rspDataset = NULL;
if (DICOM_PENDING_STATUS(findrsp->m_status))
{
// Check if dataset is announced correctly
if (rsp.msg.CFindRSP.DataSetType == DIMSE_DATASET_NULL)
{
DCMNET_ERROR("Received C-FIND response with PENDING status but no dataset announced, aborting");
delete findrsp;
return DIMSE_BADMESSAGE;
}
// Receive dataset
cond = receiveDIMSEDataset(&pcid, &rspDataset, NULL /* callback */, NULL /* callbackContext */);
if (cond.bad())
{
DCMNET_ERROR("Unable to receive C-FIND dataset on presentation context "
<< OFstatic_cast(unsigned int, pcid) << ": " << DimseCondition::dump(tempStr, cond));
delete findrsp;
return DIMSE_BADDATA;
}
DCMNET_DEBUG("Received dataset on presentation context " << OFstatic_cast(unsigned int, pcid));
findrsp->m_dataset = rspDataset;
}
// Handle C-FIND response (has to handle all possible status flags)
cond = handleFINDResponse(pcid, findrsp, waitForNextResponse);
if (cond.bad())
{
DCMNET_WARN("Unable to handle C-FIND response correctly: " << cond.text() << " (ignored)");
delete findrsp;
cond = EC_Normal;
// don't return here but trust the "waitForNextResponse" variable
}
// if response could be handled successfully, add it to response list
else
{
if (responses != NULL) // only add if desired by caller
responses->add(findrsp);
}
}
/* All responses received or break signal occured */
return EC_Normal;
}
// Standard handler for C-FIND message responses
OFCondition DcmSCU::handleFINDResponse(Uint16 /* presContextID */,
FINDResponse *response,
OFBool &waitForNextResponse)
{
DCMNET_DEBUG("Handling C-FIND Response");
switch (response->m_status) {
case STATUS_Pending:
case STATUS_FIND_Pending_WarningUnsupportedOptionalKeys:
/* in this case the current C-FIND-RSP indicates that */
/* there will be some more results */
waitForNextResponse = OFTrue;
DCMNET_DEBUG("One or more outstanding C-FIND responses");
break;
case STATUS_Success:
/* in this case the current C-FIND-RSP indicates that */
/* there are no more records that match the search mask */
waitForNextResponse = OFFalse;
DCMNET_DEBUG("Received final C-FIND response, no more C-FIND responses expected");
break;
default:
/* in all other cases, don't expect further responses to come */
waitForNextResponse = OFFalse;
DCMNET_DEBUG("Status tells not to wait for further C-FIND responses");
break;
} //switch
return EC_Normal;
}
// Send C-FIND-CANCEL and, therefore, ends current C-FIND session
OFCondition DcmSCU::sendCANCELRequest(Uint16 /* presContextID */)
{
return EC_Normal;
}
// Sends N-ACTION request to another DICOM application
OFCondition DcmSCU::sendACTIONRequest(const T_ASC_PresentationContextID presID,
const OFString &sopInstanceUID,
const Uint16 actionTypeID,
DcmDataset *reqDataset,
Uint16 &rspStatusCode)
{
// Do some basic validity checks
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
if (sopInstanceUID.empty() || (reqDataset == NULL))
return DIMSE_NULLKEY;
// Prepare DIMSE data structures for issuing request
OFCondition cond;
OFString tempStr;
T_ASC_PresentationContextID pcid = presID;
T_DIMSE_Message request;
T_DIMSE_N_ActionRQ &actionReq = request.msg.NActionRQ;
DcmDataset *statusDetail = NULL;
request.CommandField = DIMSE_N_ACTION_RQ;
actionReq.MessageID = nextMessageID();
actionReq.DataSetType = DIMSE_DATASET_PRESENT;
actionReq.ActionTypeID = actionTypeID;
// Determine SOP Class from presentation context
OFString abstractSyntax, transferSyntax;
findPresentationContext(pcid, abstractSyntax, transferSyntax);
if (abstractSyntax.empty() || transferSyntax.empty())
return DIMSE_NOVALIDPRESENTATIONCONTEXTID;
OFStandard::strlcpy(actionReq.RequestedSOPClassUID, abstractSyntax.c_str(), sizeof(actionReq.RequestedSOPClassUID));
OFStandard::strlcpy(actionReq.RequestedSOPInstanceUID, sopInstanceUID.c_str(), sizeof(actionReq.RequestedSOPInstanceUID));
// Send request
DCMNET_INFO("Sending N-ACTION Request");
// Output dataset only if trace level is enabled
if (DCM_dcmnetGetLogger().isEnabledFor(OFLogger::TRACE_LOG_LEVEL))
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, reqDataset, pcid));
else
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_OUTGOING, NULL, pcid));
cond = sendDIMSEMessage(pcid, &request, reqDataset, NULL /* callback */, NULL /* callbackContext */);
if (cond.bad())
{
DCMNET_ERROR("Failed sending N-ACTION request: " << DimseCondition::dump(tempStr, cond));
return cond;
}
// Receive response
T_DIMSE_Message response;
cond = receiveDIMSECommand(&pcid, &response, &statusDetail, NULL /* commandSet */);
if (cond.bad())
{
DCMNET_ERROR("Failed receiving DIMSE response: " << DimseCondition::dump(tempStr, cond));
return cond;
}
// Check command set
if (response.CommandField == DIMSE_N_ACTION_RSP)
{
DCMNET_INFO("Received N-ACTION Response");
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
} else {
DCMNET_ERROR("Expected N-ACTION response but received DIMSE command 0x"
<< STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
<< OFstatic_cast(unsigned int, response.CommandField));
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_INCOMING, NULL, pcid));
delete statusDetail;
return DIMSE_BADCOMMANDTYPE;
}
if (statusDetail != NULL)
{
DCMNET_DEBUG("Response has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
delete statusDetail;
}
// Set return value
T_DIMSE_N_ActionRSP &actionRsp = response.msg.NActionRSP;
rspStatusCode = actionRsp.DimseStatus;
// Check whether there is a dataset to be received
if (actionRsp.DataSetType == DIMSE_DATASET_PRESENT)
{
// this should never happen
DcmDataset *tempDataset = NULL;
T_ASC_PresentationContextID tempID;
cond = receiveDIMSEDataset(&tempID, &tempDataset, NULL /* callback */, NULL /* callbackContext */);
if (cond.good())
{
DCMNET_WARN("Received unexpected dataset after N-ACTION response, ignoring");
delete tempDataset;
} else {
DCMNET_ERROR("Failed receiving unexpected dataset after N-ACTION response: "
<< DimseCondition::dump(tempStr, cond));
return DIMSE_BADDATA;
}
}
if (actionRsp.MessageIDBeingRespondedTo != actionReq.MessageID)
{
DCMNET_ERROR("Received response with wrong message ID ("
<< actionRsp.MessageIDBeingRespondedTo << " instead of " << actionReq.MessageID << ")");
return DIMSE_BADMESSAGE;
}
return cond;
}
// Receives N-EVENT-REPORT request
OFCondition DcmSCU::handleEVENTREPORTRequest(DcmDataset *&reqDataset,
Uint16 &eventTypeID,
const int timeout)
{
// Do some basic validity checks
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
OFCondition cond;
OFString tempStr;
T_ASC_PresentationContextID presID;
T_ASC_PresentationContextID presIDdset;
T_DIMSE_Message request;
T_DIMSE_N_EventReportRQ &eventReportReq = request.msg.NEventReportRQ;
DcmDataset *dataset = NULL;
DcmDataset *statusDetail = NULL;
Uint16 statusCode = 0;
if (timeout > 0)
DCMNET_DEBUG("Handle N-EVENT-REPORT request, waiting up to " << timeout << " seconds (only for N-EVENT-REPORT message)");
else if ((m_dimseTimeout > 0) && (m_blockMode == DIMSE_NONBLOCKING))
DCMNET_DEBUG("Handle N-EVENT-REPORT request, waiting up to " << m_dimseTimeout << " seconds (default for all DIMSE messages)");
else
DCMNET_DEBUG("Handle N-EVENT-REPORT request, waiting an unlimited period of time");
// Receive request, use specific timeout (if defined)
cond = receiveDIMSECommand(&presID, &request, &statusDetail, NULL /* commandSet */, timeout);
if (cond.bad())
{
if (cond != DIMSE_NODATAAVAILABLE)
DCMNET_ERROR("Failed receiving DIMSE request: " << DimseCondition::dump(tempStr, cond));
return cond;
}
// Check command set
if (request.CommandField == DIMSE_N_EVENT_REPORT_RQ)
{
DCMNET_INFO("Received N-EVENT-REPORT Request");
} else {
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));
DCMNET_ERROR("Expected N-EVENT-REPORT request but received DIMSE command 0x"
<< STD_NAMESPACE hex << STD_NAMESPACE setfill('0') << STD_NAMESPACE setw(4)
<< OFstatic_cast(unsigned int, request.CommandField));
delete statusDetail;
return DIMSE_BADCOMMANDTYPE;
}
if (statusDetail != NULL)
{
DCMNET_DEBUG("Request has status detail:" << OFendl << DcmObject::PrintHelper(*statusDetail));
delete statusDetail;
}
// Check if dataset is announced correctly
if (eventReportReq.DataSetType == DIMSE_DATASET_NULL)
{
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));
DCMNET_ERROR("Received N-EVENT-REPORT request but no dataset announced, aborting");
return DIMSE_BADMESSAGE;
}
// Receive dataset
cond = receiveDIMSEDataset(&presIDdset, &dataset, NULL /* callback */, NULL /* callbackContext */);
if (cond.bad())
{
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));
DCMNET_ERROR("Unable to receive N-EVENT-REPORT dataset on presentation context "
<< OFstatic_cast(unsigned int, presID));
return DIMSE_BADDATA;
}
// Output dataset only if trace level is enabled
if (DCM_dcmnetGetLogger().isEnabledFor(OFLogger::TRACE_LOG_LEVEL))
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, dataset, presID));
else
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, request, DIMSE_INCOMING, NULL, presID));
// Compare presentation context ID of command and data set
if (presIDdset != presID)
{
DCMNET_ERROR("Presentation Context ID of command (" << OFstatic_cast(unsigned int, presID)
<< ") and data set (" << OFstatic_cast(unsigned int, presIDdset) << ") differs");
delete dataset;
return makeDcmnetCondition(DIMSEC_INVALIDPRESENTATIONCONTEXTID, OF_error,
"DIMSE: Presentation Contexts of Command and Data Set differ");
}
// Check the request dataset and return the DIMSE status code to be used
statusCode = checkEVENTREPORTRequest(eventReportReq, dataset);
// Send back response
T_DIMSE_Message response;
T_DIMSE_N_EventReportRSP &eventReportRsp = response.msg.NEventReportRSP;
response.CommandField = DIMSE_N_EVENT_REPORT_RSP;
eventReportRsp.MessageIDBeingRespondedTo = eventReportReq.MessageID;
eventReportRsp.DimseStatus = statusCode;
eventReportRsp.DataSetType = DIMSE_DATASET_NULL;
eventReportRsp.opts = 0;
eventReportRsp.AffectedSOPClassUID[0] = 0;
eventReportRsp.AffectedSOPInstanceUID[0] = 0;
DCMNET_INFO("Sending N-EVENT-REPORT Response");
DCMNET_DEBUG(DIMSE_dumpMessage(tempStr, response, DIMSE_OUTGOING, NULL, presID));
cond = sendDIMSEMessage(presID, &response, NULL /* dataObject */, NULL /* callback */, NULL /* callbackContext */);
if (cond.bad())
{
DCMNET_ERROR("Failed sending N-EVENT-REPORT response: " << DimseCondition::dump(tempStr, cond));
delete dataset;
return cond;
}
// Set return values
reqDataset = dataset;
eventTypeID = eventReportReq.EventTypeID;
return cond;
}
Uint16 DcmSCU::checkEVENTREPORTRequest(T_DIMSE_N_EventReportRQ & /*eventReportReq*/,
DcmDataset * /*reqDataset*/)
{
// we default to success
return STATUS_Success;
}
// Sends a DIMSE command and possibly also instance data to the configured peer DICOM application
OFCondition DcmSCU::sendDIMSEMessage(const T_ASC_PresentationContextID presID,
T_DIMSE_Message *msg,
DcmDataset *dataObject,
DIMSE_ProgressCallback callback,
void *callbackContext,
DcmDataset **commandSet)
{
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
if (msg == NULL)
return DIMSE_NULLKEY;
OFCondition cond;
/* call the corresponding DIMSE function to sent the message */
cond = DIMSE_sendMessageUsingMemoryData(m_assoc, presID, msg, NULL /*statusDetail*/, dataObject,
callback, callbackContext, commandSet);
#if 0
// currently disabled because it is not (yet) needed
if (cond.good())
{
/* create a copy of the current DIMSE command message */
delete m_openDIMSERequest;
m_openDIMSERequest = new T_DIMSE_Message;
memcpy((char*)m_openDIMSERequest, msg, sizeof(*m_openDIMSERequest));
}
#endif
return cond;
}
// Receive DIMSE command (excluding dataset!) over the currently open association
OFCondition DcmSCU::receiveDIMSECommand(T_ASC_PresentationContextID *presID,
T_DIMSE_Message *msg,
DcmDataset **statusDetail,
DcmDataset **commandSet,
const Uint32 timeout)
{
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
OFCondition cond;
if (timeout > 0)
{
/* call the corresponding DIMSE function to receive the command (use specified timeout)*/
cond = DIMSE_receiveCommand(m_assoc, DIMSE_NONBLOCKING, timeout, presID,
msg, statusDetail, commandSet);
} else {
/* call the corresponding DIMSE function to receive the command (use default timeout) */
cond = DIMSE_receiveCommand(m_assoc, m_blockMode, m_dimseTimeout, presID,
msg, statusDetail, commandSet);
}
return cond;
}
// Receives one dataset (of instance data) via network from another DICOM application
OFCondition DcmSCU::receiveDIMSEDataset(T_ASC_PresentationContextID *presID,
DcmDataset **dataObject,
DIMSE_ProgressCallback callback,
void *callbackContext)
{
if (m_assoc == NULL)
return DIMSE_ILLEGALASSOCIATION;
OFCondition cond;
/* call the corresponding DIMSE function to receive the dataset */
cond = DIMSE_receiveDataSetInMemory(m_assoc, m_blockMode, m_dimseTimeout, presID,
dataObject, callback, callbackContext);
return cond;
}
void DcmSCU::setMaxReceivePDULength(const unsigned long maxRecPDU)
{
m_maxReceivePDULength = maxRecPDU;
}
void DcmSCU::setDIMSEBlockingMode(const T_DIMSE_BlockingMode blockingMode)
{
m_blockMode = blockingMode;
}
void DcmSCU::setAETitle(const OFString &myAETtitle)
{
m_ourAETitle = myAETtitle;
}
void DcmSCU::setPeerHostName(const OFString &peerHostName)
{
m_peer = peerHostName;
}
void DcmSCU::setPeerAETitle(const OFString &peerAETitle)
{
m_peerAETitle = peerAETitle;
}
void DcmSCU::setPeerPort(const Uint16 peerPort)
{
m_peerPort = peerPort;
}
void DcmSCU::setDIMSETimeout(const Uint32 dimseTimeout)
{
m_dimseTimeout = dimseTimeout;
}
void DcmSCU::setACSETimeout(const Uint32 acseTimeout)
{
m_acseTimeout = acseTimeout;
}
void DcmSCU::setAssocConfigFileAndProfile(const OFString &filename,
const OFString &profile)
{
m_assocConfigFilename = filename;
m_assocConfigProfile = profile;
}
void DcmSCU::setVerbosePCMode(const OFBool mode)
{
m_verbosePCMode = mode;
}
/* Get methods */
OFBool DcmSCU::isConnected() const
{
return (m_assoc != NULL) && (m_assoc->DULassociation != NULL);
}
Uint32 DcmSCU::getMaxReceivePDULength() const
{
return m_maxReceivePDULength;
}
OFBool DcmSCU::getTLSEnabled() const
{
return OFFalse;
}
T_DIMSE_BlockingMode DcmSCU::getDIMSEBlockingMode() const
{
return m_blockMode;
}
const OFString &DcmSCU::getAETitle() const
{
return m_ourAETitle;
}
const OFString &DcmSCU::getPeerHostName() const
{
return m_peer;
}
const OFString &DcmSCU::getPeerAETitle() const
{
return m_peerAETitle;
}
Uint16 DcmSCU::getPeerPort() const
{
return m_peerPort;
}
Uint32 DcmSCU::getDIMSETimeout() const
{
return m_dimseTimeout;
}
Uint32 DcmSCU::getACSETimeout() const
{
return m_acseTimeout;
}
OFBool DcmSCU::getVerbosePCMode() const
{
return m_verbosePCMode;
}
OFCondition DcmSCU::getDatasetInfo(DcmDataset *dataset,
OFString &sopClassUID,
OFString &sopInstanceUID,
E_TransferSyntax &transferSyntax)
{
if (dataset == NULL)
return EC_IllegalParameter;
dataset->findAndGetOFString(DCM_SOPClassUID, sopClassUID);
dataset->findAndGetOFString(DCM_SOPInstanceUID, sopInstanceUID);
transferSyntax = dataset->getOriginalXfer();
return EC_Normal;
}
/* ************************************************************************ */
/* C-FIND Response classes */
/* ************************************************************************ */
FINDResponses::FINDResponses()
{
// Nothing to do :-)
}
FINDResponses::~FINDResponses()
{
Uint32 numelems = m_responses.size();
FINDResponse *rsp = NULL;
for (Uint32 i=0; i < numelems; i++)
{
rsp = m_responses.front();
if (rsp != NULL)
{
delete rsp; rsp = NULL;
}
m_responses.pop_front();
}
}
Uint32 FINDResponses::numResults() const
{
return m_responses.size();
}
void FINDResponses::add(FINDResponse *rsp)
{
if (rsp != NULL)
m_responses.push_back(rsp);
}
OFListIterator(FINDResponse *) FINDResponses::begin()
{
return m_responses.begin();
}
OFListIterator(FINDResponse *) FINDResponses::end()
{
return m_responses.end();
}
/* ************************** FINDResponse class ****************************/
// Standard constructor
FINDResponse::FINDResponse() :
m_messageIDRespondedTo(0),
m_affectedSOPClassUID(),
m_dataset(NULL),
m_status(0)
{
}
// Destructor, cleans up internal memory (datasets if present)
FINDResponse::~FINDResponse()
{
if (m_dataset != NULL)
{
delete m_dataset;
m_dataset = NULL;
}
}
/*
** CVS Log
** $Log: scu.cc,v $
** Revision 1.16 2010-12-21 09:37:36 onken
** Fixed wrong response assignment in DcmSCU's C-STORE code. Thanks to
** forum user "takeos" for the hint and fix.
**
** Revision 1.15 2010-10-20 07:41:36 uli
** Made sure isalpha() & friends are only called with valid arguments.
**
** Revision 1.14 2010-10-14 13:14:29 joergr
** Updated copyright header. Added reference to COPYRIGHT file.
**
** Revision 1.13 2010-10-01 12:25:29 uli
** Fixed most compiler warnings in remaining modules.
**
** Revision 1.12 2010-08-10 11:59:32 uli
** Fixed some cases where dcmFindNameOfUID() returning NULL could cause crashes.
**
** Revision 1.11 2010-06-24 09:26:57 joergr
** Added check on whether the presentation context ID of command and data set are
** identical. Made sure that received dataset is deleted when an error occurs.
** Used more appropriate error conditions / return codes. Further code cleanup.
**
** Revision 1.10 2010-06-22 15:48:53 joergr
** Introduced new enumeration type to be used for closeAssociation().
** Further code cleanup. Renamed some methods, variables, types and so on.
**
** Revision 1.9 2010-06-18 14:58:01 joergr
** Changed some error conditions / return codes to more appropriate values.
** Further revised logging output. Use DimseCondition::dump() where appropriate.
**
** Revision 1.8 2010-06-17 17:13:06 joergr
** Added preliminary support for N-EVENT-REPORT to DcmSCU. Some further code
** cleanups and enhancements. Renamed some methods. Revised documentation.
**
** Revision 1.7 2010-06-09 16:33:34 joergr
** Added preliminary support for N-ACTION to DcmSCU. Some further code cleanups
** and enhancements.
**
** Revision 1.6 2010-06-08 17:54:14 onken
** Added C-FIND functionality to DcmSCU. Some code cleanups. Fixed
** memory leak sometimes occuring during association configuration.
**
** Revision 1.5 2010-06-02 16:01:49 joergr
** Slightly modified some log messages and levels for reasons of consistency.
** Use type cast macros (e.g. OFstatic_cast) where appropriate.
**
** Revision 1.4 2010-04-29 16:13:25 onken
** Made SCU class independent from dcmtls, i.e. outsourced TLS API. Added
** direct API support for sending C-STORE requests. Further API changes and
** some bugs fixed.
**
** Revision 1.3 2009-12-21 15:33:58 onken
** Added documentation and refactored / enhanced some code.
**
** Revision 1.2 2009-12-17 09:12:27 onken
** Fixed other scu and scp base class compile issues.
**
** Revision 1.1 2009-12-16 17:05:35 onken
** Added base classes for SCU and SCP implementation.
**
** Revision 1.5 2009-12-02 14:26:05 uli
** Stop including dcdebug.h which was removed.
**
** Revision 1.4 2009-11-18 12:37:28 uli
** Fix compiler errors due to removal of DUL_Debug() and DIMSE_Debug().
**
** Revision 1.3 2009-01-08 18:25:34 joergr
** Replaced further OFListIterator() by OFListConstIterator() in order to
** compile when STL list classes are used.
**
** Revision 1.2 2009-01-08 13:33:31 joergr
** Replaced OFListIterator() by OFListConstIterator() in order to compile when
** STL list classes are used.
**
** Revision 1.1 2008-09-29 13:51:55 onken
** Initial checkin of module dcmppscu implementing an MPPS commandline client.
**
*/
| bsd-3-clause |
AurionProject/Aurion | Product/Production/Gateway/PatientDiscovery_10/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/_10/gateway/ws/EntityPatientDiscoveryUnsecured.java | 4925 | /*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* 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 United States Government 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 THE UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.patientdiscovery._10.gateway.ws;
import gov.hhs.fha.nhinc.aspect.OutboundMessageEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.entitypatientdiscovery.EntityPatientDiscoveryPortType;
import gov.hhs.fha.nhinc.messaging.server.BaseService;
import gov.hhs.fha.nhinc.patientdiscovery._10.entity.EntityPatientDiscoveryImpl;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.PRPAIN201305UV02ArgTransformer;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.RespondingGatewayPRPAIN201306UV02Builder;
import gov.hhs.fha.nhinc.patientdiscovery.outbound.OutboundPatientDiscovery;
import ihe.iti.xcpd._2009.PatientLocationQueryResponseType;
import ihe.iti.xcpd._2009.RespondingGatewayPatientLocationQueryRequestType;
import javax.annotation.Resource;
import javax.xml.ws.BindingType;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;
import org.hl7.v3.RespondingGatewayPRPAIN201305UV02RequestType;
import org.hl7.v3.RespondingGatewayPRPAIN201306UV02ResponseType;
@Addressing(enabled = true)
@BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
public class EntityPatientDiscoveryUnsecured extends BaseService implements EntityPatientDiscoveryPortType {
private OutboundPatientDiscovery outboundPatientDiscovery;
private WebServiceContext context;
public EntityPatientDiscoveryUnsecured() {
super();
}
@OutboundMessageEvent(beforeBuilder = PRPAIN201305UV02ArgTransformer.class,
afterReturningBuilder = RespondingGatewayPRPAIN201306UV02Builder.class, serviceType = "Patient Discovery",
version = "1.0")
public RespondingGatewayPRPAIN201306UV02ResponseType respondingGatewayPRPAIN201305UV02(
RespondingGatewayPRPAIN201305UV02RequestType request) {
AssertionType assertion = getAssertion(context, request.getAssertion());
return new EntityPatientDiscoveryImpl(outboundPatientDiscovery).respondingGatewayPRPAIN201305UV02(request,
assertion);
}
public void setOutboundPatientDiscovery(OutboundPatientDiscovery outboundPatientDiscovery) {
this.outboundPatientDiscovery = outboundPatientDiscovery;
}
@Resource
public void setContext(WebServiceContext context) {
this.context = context;
}
/**
* Gets the outbound patient discovery.
*
* @return the outbound patient discovery
*/
public OutboundPatientDiscovery getOutboundPatientDiscovery() {
return this.outboundPatientDiscovery;
}
@OutboundMessageEvent(beforeBuilder = PRPAIN201305UV02ArgTransformer.class,
afterReturningBuilder = RespondingGatewayPRPAIN201306UV02Builder.class, serviceType = "Patient Discovery",
version = "1.0")
public PatientLocationQueryResponseType respondingGatewayPatientLocationQuery(
RespondingGatewayPatientLocationQueryRequestType request) {
//AssertionType assertion = getAssertion(context, null);
AssertionType assertion = request.getAssertion();
return new EntityPatientDiscoveryImpl(outboundPatientDiscovery).respondingGatewayPatientLocationQuery(request,
assertion);
}
}
| bsd-3-clause |
yephper/django | django/utils/html.py | 14802 | """HTML utilities suitable for global use."""
from __future__ import unicode_literals
import re
from django.utils import six
from django.utils.encoding import force_str, force_text
from django.utils.functional import keep_lazy, keep_lazy_text
from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS
from django.utils.safestring import SafeData, SafeText, mark_safe
from django.utils.six.moves.urllib.parse import (
parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit,
)
from django.utils.text import normalize_newlines
from .html_parser import HTMLParseError, HTMLParser
# Configuration for urlize() function.
TRAILING_PUNCTUATION_RE = re.compile(
'^' # Beginning of word
'(.*?)' # The URL in word
'([.,:;!]+)' # Allowed non-wrapping, trailing punctuation
'$' # End of word
)
WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('<', '>'), ('"', '"'), ('\'', '\'')]
# List of possible strings used for bullets in bulleted lists.
DOTS = ['·', '*', '\u2022', '•', '•', '•']
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'''([\s<>"']+)''')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE)
simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+')
html_gunk_re = re.compile(
r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|'
'<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
hard_coded_bullets_re = re.compile(
r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join(re.escape(x)
for x in DOTS), re.DOTALL)
trailing_empty_content_re = re.compile(r'(?:<p>(?: |\s|<br \/>)*?</p>\s*)+\Z')
@keep_lazy(six.text_type, SafeText)
def escape(text):
"""
Returns the given text with ampersands, quotes and angle brackets encoded
for use in HTML.
This function always escapes its input, even if it's already escaped and
marked as such. This may result in double-escaping. If this is a concern,
use conditional_escape() instead.
"""
return mark_safe(force_text(text).replace('&', '&').replace('<', '<')
.replace('>', '>').replace('"', '"').replace("'", '''))
_js_escapes = {
ord('\\'): '\\u005C',
ord('\''): '\\u0027',
ord('"'): '\\u0022',
ord('>'): '\\u003E',
ord('<'): '\\u003C',
ord('&'): '\\u0026',
ord('='): '\\u003D',
ord('-'): '\\u002D',
ord(';'): '\\u003B',
ord('\u2028'): '\\u2028',
ord('\u2029'): '\\u2029'
}
# Escape every ASCII character with a value less than 32.
_js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32))
@keep_lazy(six.text_type, SafeText)
def escapejs(value):
"""Hex encodes characters for use in JavaScript strings."""
return mark_safe(force_text(value).translate(_js_escapes))
def conditional_escape(text):
"""
Similar to escape(), except that it doesn't operate on pre-escaped strings.
This function relies on the __html__ convention used both by Django's
SafeData class and by third-party libraries like markupsafe.
"""
if hasattr(text, '__html__'):
return text.__html__()
else:
return escape(text)
def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(conditional_escape, args)
kwargs_safe = {k: conditional_escape(v) for (k, v) in six.iteritems(kwargs)}
return mark_safe(format_string.format(*args_safe, **kwargs_safe))
def format_html_join(sep, format_string, args_generator):
"""
A wrapper of format_html, for the common case of a group of arguments that
need to be formatted using the same format string, and then joined using
'sep'. 'sep' is also passed through conditional_escape.
'args_generator' should be an iterator that returns the sequence of 'args'
that will be passed to format_html.
Example:
format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
for u in users))
"""
return mark_safe(conditional_escape(sep).join(
format_html(format_string, *tuple(args))
for args in args_generator))
@keep_lazy_text
def linebreaks(value, autoescape=False):
"""Converts newlines into <p> and <br />s."""
value = normalize_newlines(force_text(value))
paras = re.split('\n{2,}', value)
if autoescape:
paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
else:
paras = ['<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
return '\n\n'.join(paras)
class MLStripper(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def handle_entityref(self, name):
self.fed.append('&%s;' % name)
def handle_charref(self, name):
self.fed.append('&#%s;' % name)
def get_data(self):
return ''.join(self.fed)
def _strip_once(value):
"""
Internal tag stripping utility used by strip_tags.
"""
s = MLStripper()
try:
s.feed(value)
except HTMLParseError:
return value
try:
s.close()
except HTMLParseError:
return s.get_data() + s.rawdata
else:
return s.get_data()
@keep_lazy_text
def strip_tags(value):
"""Returns the given HTML with all tags stripped."""
# Note: in typical case this loop executes _strip_once once. Loop condition
# is redundant, but helps to reduce number of executions of _strip_once.
value = force_text(value)
while '<' in value and '>' in value:
new_value = _strip_once(value)
if len(new_value) >= len(value):
# _strip_once was not able to detect more tags or length increased
# due to http://bugs.python.org/issue20288
# (affects Python 2 < 2.7.7 and Python 3 < 3.3.5)
break
value = new_value
return value
@keep_lazy_text
def strip_spaces_between_tags(value):
"""Returns the given HTML with spaces between tags removed."""
return re.sub(r'>\s+<', '><', force_text(value))
def smart_urlquote(url):
"Quotes a URL if it isn't already quoted."
def unquote_quote(segment):
segment = unquote(force_str(segment))
# Tilde is part of RFC3986 Unreserved Characters
# http://tools.ietf.org/html/rfc3986#section-2.3
# See also http://bugs.python.org/issue16285
segment = quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + str('~'))
return force_text(segment)
# Handle IDN before quoting.
try:
scheme, netloc, path, query, fragment = urlsplit(url)
except ValueError:
# invalid IPv6 URL (normally square brackets in hostname part).
return unquote_quote(url)
try:
netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
except UnicodeError: # invalid domain part
return unquote_quote(url)
if query:
# Separately unquoting key/value, so as to not mix querystring separators
# included in query values. See #22267.
query_parts = [(unquote(force_str(q[0])), unquote(force_str(q[1])))
for q in parse_qsl(query, keep_blank_values=True)]
# urlencode will take care of quoting
query = urlencode(query_parts)
path = unquote_quote(path)
fragment = unquote_quote(fragment)
return urlunsplit((scheme, netloc, path, query, fragment))
@keep_lazy_text
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
"""
Converts any URLs in text into clickable links.
Works on http://, https://, www. links, and also on links ending in one of
the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
Links can have trailing punctuation (periods, commas, close-parens) and
leading punctuation (opening parens) and it'll still do the right thing.
If trim_url_limit is not None, the URLs in the link text longer than this
limit will be truncated to trim_url_limit-3 characters and appended with
an ellipsis.
If nofollow is True, the links will get a rel="nofollow" attribute.
If autoescape is True, the link text and URLs will be autoescaped.
"""
safe_input = isinstance(text, SafeData)
def trim_url(x, limit=trim_url_limit):
if limit is None or len(x) <= limit:
return x
return '%s...' % x[:max(0, limit - 3)]
def unescape(text, trail):
"""
If input URL is HTML-escaped, unescape it so as we can safely feed it to
smart_urlquote. For example:
http://example.com?x=1&y=<2> => http://example.com?x=1&y=<2>
"""
unescaped = (text + trail).replace(
'&', '&').replace('<', '<').replace(
'>', '>').replace('"', '"').replace(''', "'")
if trail and unescaped.endswith(trail):
# Remove trail for unescaped if it was not consumed by unescape
unescaped = unescaped[:-len(trail)]
elif trail == ';':
# Trail was consumed by unescape (as end-of-entity marker), move it to text
text += trail
trail = ''
return text, unescaped, trail
def trim_punctuation(lead, middle, trail):
"""
Trim trailing and wrapping punctuation from `middle`. Return the items
of the new state.
"""
# Continue trimming until middle remains unchanged.
trimmed_something = True
while trimmed_something:
trimmed_something = False
# Trim trailing punctuation.
match = TRAILING_PUNCTUATION_RE.match(middle)
if match:
middle = match.group(1)
trail = match.group(2) + trail
trimmed_something = True
# Trim wrapping punctuation.
for opening, closing in WRAPPING_PUNCTUATION:
if middle.startswith(opening):
middle = middle[len(opening):]
lead += opening
trimmed_something = True
# Keep parentheses at the end only if they're balanced.
if (middle.endswith(closing) and
middle.count(closing) == middle.count(opening) + 1):
middle = middle[:-len(closing)]
trail = closing + trail
trimmed_something = True
return lead, middle, trail
words = word_split_re.split(force_text(text))
for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word:
# lead: Current punctuation trimmed from the beginning of the word.
# middle: Current state of the word.
# trail: Current punctuation trimmed from the end of the word.
lead, middle, trail = '', word, ''
# Deal with punctuation.
lead, middle, trail = trim_punctuation(lead, middle, trail)
# Make URL we want to point to.
url = None
nofollow_attr = ' rel="nofollow"' if nofollow else ''
if simple_url_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote(middle_unescaped)
elif simple_url_2_re.match(middle):
middle, middle_unescaped, trail = unescape(middle, trail)
url = smart_urlquote('http://%s' % middle_unescaped)
elif ':' not in middle and simple_email_re.match(middle):
local, domain = middle.rsplit('@', 1)
try:
domain = domain.encode('idna').decode('ascii')
except UnicodeError:
continue
url = 'mailto:%s@%s' % (local, domain)
nofollow_attr = ''
# Make link.
if url:
trimmed = trim_url(middle)
if autoescape and not safe_input:
lead, trail = escape(lead), escape(trail)
trimmed = escape(trimmed)
middle = '<a href="%s"%s>%s</a>' % (escape(url), nofollow_attr, trimmed)
words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
else:
if safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
elif safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
return ''.join(words)
def avoid_wrapping(value):
"""
Avoid text wrapping in the middle of a phrase by adding non-breaking
spaces where there previously were normal spaces.
"""
return value.replace(" ", "\xa0")
def html_safe(klass):
"""
A decorator that defines the __html__ method. This helps non-Django
templates to detect classes whose __str__ methods return SafeText.
"""
if '__html__' in klass.__dict__:
raise ValueError(
"can't apply @html_safe to %s because it defines "
"__html__()." % klass.__name__
)
if six.PY2:
if '__unicode__' not in klass.__dict__:
raise ValueError(
"can't apply @html_safe to %s because it doesn't "
"define __unicode__()." % klass.__name__
)
klass_unicode = klass.__unicode__
klass.__unicode__ = lambda self: mark_safe(klass_unicode(self))
klass.__html__ = lambda self: unicode(self) # NOQA: unicode undefined on PY3
else:
if '__str__' not in klass.__dict__:
raise ValueError(
"can't apply @html_safe to %s because it doesn't "
"define __str__()." % klass.__name__
)
klass_str = klass.__str__
klass.__str__ = lambda self: mark_safe(klass_str(self))
klass.__html__ = lambda self: str(self)
return klass
| bsd-3-clause |
fyu/drn | lib/modules/batchnormsync.py | 2268 | from queue import Queue
import torch
from torch.nn import Module
from torch.nn.parameter import Parameter
from functions.batchnormp import BatchNormPFunction
class BatchNormSync(Module):
sync = True
checking_mode = False
def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True,
device_ids=None):
super(BatchNormSync, self).__init__()
self.num_features = num_features
self.affine = affine
self.eps = eps
self.momentum = momentum
if self.affine:
self.weight = Parameter(torch.Tensor(num_features))
self.bias = Parameter(torch.Tensor(num_features))
else:
self.register_parameter('weight', None)
self.register_parameter('bias', None)
self.register_buffer('running_mean', torch.zeros(num_features))
self.register_buffer('running_var', torch.ones(num_features))
self.mean = torch.zeros(num_features)
self.std = torch.ones(num_features)
self.reset_parameters()
self.cum_queue = Queue()
self.broadcast_queue = Queue()
if device_ids is None:
self.device_ids = list(range(torch.cuda.device_count()))
else:
self.device_ids = device_ids
def reset_parameters(self):
self.running_mean.zero_()
self.running_var.fill_(1)
self.mean.zero_()
self.std.fill_(1)
if self.affine:
if BatchNormSync.checking_mode:
self.weight.data.fill_(1)
else:
self.weight.data.uniform_()
self.bias.data.zero_()
def forward(self, input):
training = int(self.training)
assert input.size(1) == self.num_features
bn_func = BatchNormPFunction(
self.running_mean, self.running_var, # self.mean, self.std,
training, self.cum_queue, self.broadcast_queue, self.device_ids,
BatchNormSync.sync, self.eps, self.momentum, self.affine)
return bn_func(input, self.weight, self.bias)
def __repr__(self):
return ('{name}({num_features}, eps={eps}, momentum={momentum},'
' affine={affine})'
.format(name=self.__class__.__name__, **self.__dict__)) | bsd-3-clause |
bigjun/mrpt | apps/mrpt-performance/perf-scan_matching.cpp | 9034 | /* +---------------------------------------------------------------------------+
| The Mobile Robot Programming Toolkit (MRPT) |
| |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |
| Copyright (c) 2005-2013, MAPIR group, University of Malaga |
| Copyright (c) 2012-2013, University of Almeria |
| 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 copyright holders 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 THE COPYRIGHT HOLDERS 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. |
+---------------------------------------------------------------------------+ */
#include <mrpt/slam.h>
#include <mrpt/gui.h>
#include <mrpt/random.h>
#include <mrpt/scanmatching.h>
#include "common.h"
using namespace mrpt::vision;
using namespace mrpt::utils;
using namespace mrpt::poses;
using namespace mrpt::gui;
using namespace mrpt::system;
using namespace mrpt::scanmatching;
using namespace mrpt::slam;
using namespace std;
typedef std::vector< std::vector< double > > TPoints;
// ------------------------------------------------------
// Generate both sets of points
// ------------------------------------------------------
void generate_points( TPoints &pA, TPoints &pB )
{
const double Dx = 0.5;
const double Dy = 1.5;
const double Dz = 0.75;
const double yaw = DEG2RAD(10);
const double pitch = DEG2RAD(20);
const double roll = DEG2RAD(5);
pA.resize( 5 ); // A set of points at "A" reference system
pB.resize( 5 ); // A set of points at "B" reference system
pA[0].resize(3); pA[0][0] = 0.0; pA[0][1] = 0.5; pA[0][2] = 0.4;
pA[1].resize(3); pA[1][0] = 1.0; pA[1][1] = 1.5; pA[1][2] = -0.1;
pA[2].resize(3); pA[2][0] = 1.2; pA[2][1] = 1.1; pA[2][2] = 0.9;
pA[3].resize(3); pA[3][0] = 0.7; pA[3][1] = 0.3; pA[3][2] = 3.4;
pA[4].resize(3); pA[4][0] = 1.9; pA[4][1] = 2.5; pA[4][2] = -1.7;
CPose3DQuat qPose( CPose3D( Dx, Dy, Dz, yaw, pitch, roll ) );
for( unsigned int i = 0; i < 5; ++i )
{
pB[i].resize( 3 );
qPose.inverseComposePoint( pA[i][0], pA[i][1], pA[i][2], pB[i][0], pB[i][1], pB[i][2] );
}
} // end generate_points
// ------------------------------------------------------
// Generate a list of matched points
// ------------------------------------------------------
void generate_list_of_points( const TPoints &pA, const TPoints &pB, TMatchingPairList &list )
{
TMatchingPair pair;
for( unsigned int i = 0; i < 5; ++i )
{
pair.this_idx = pair.other_idx = i;
pair.this_x = pA[i][0];
pair.this_y = pA[i][1];
pair.this_z = pA[i][2];
pair.other_x = pB[i][0];
pair.other_y = pB[i][1];
pair.other_z = pB[i][2];
list.push_back( pair );
}
} // end generate_list_of_points
// ------------------------------------------------------
// Genreate a vector of matched points
// ------------------------------------------------------
void generate_vector_of_points( const TPoints &pA, const TPoints &pB, vector_double &inV )
{
// The input vector: inV = [pA1x, pA1y, pA1z, pB1x, pB1y, pB1z, ... ]
inV.resize( 30 );
for( unsigned int i = 0; i < 5; ++i )
{
inV[6*i+0] = pA[i][0]; inV[6*i+1] = pA[i][1]; inV[6*i+2] = pA[i][2];
inV[6*i+3] = pB[i][0]; inV[6*i+4] = pB[i][1]; inV[6*i+5] = pB[i][2];
}
} // end generate_vector_of_points
// ------------------------------------------------------
// Benchmark: using CPose3D
// ------------------------------------------------------
double scan_matching_test_1( int a1, int a2 )
{
TPoints pA, pB;
generate_points( pA, pB );
TMatchingPairList list;
generate_list_of_points( pA, pB, list );
CPose3D out;
double scale;
const size_t N = a1;
CTicTac tictac;
tictac.Tic();
for (size_t i=0;i<N;i++)
leastSquareErrorRigidTransformation6D( list, out, scale );
const double T = tictac.Tac()/N;
return T;
}
// ------------------------------------------------------
// Benchmark: using CPose3DQuat
// ------------------------------------------------------
double scan_matching_test_2( int a1, int a2 )
{
TPoints pA, pB;
generate_points( pA, pB );
TMatchingPairList list;
generate_list_of_points( pA, pB, list );
CPose3DQuat out;
double scale;
const size_t N = a1;
CTicTac tictac;
tictac.Tic();
for (size_t i=0;i<N;i++)
leastSquareErrorRigidTransformation6D( list, out, scale );
const double T = tictac.Tac()/N;
return T;
}
// ------------------------------------------------------
// Benchmark: using vectors
// ------------------------------------------------------
double scan_matching_test_3( int a1, int a2 )
{
TPoints pA, pB;
generate_points( pA, pB );
vector_double inV;
generate_vector_of_points( pA, pB, inV );
vector_double qu;
const size_t N = a1;
CTicTac tictac;
tictac.Tic();
for (size_t i=0;i<N;i++)
HornMethod( inV, qu );
const double T = tictac.Tac()/N;
return T;
}
// ------------------------------------------------------
// Benchmark: leastSquareErrorRigidTransformation
// ------------------------------------------------------
double scan_matching_test_4( int nCorrs, int nRepets )
{
TPoints pA, pB;
generate_points( pA, pB );
vector_double inV;
generate_vector_of_points( pA, pB, inV );
vector_double qu;
TMatchingPairList in_correspondences;
CPose2D out_pose;
in_correspondences.resize(nCorrs);
for (int i=0;i<nCorrs;i++)
{
TMatchingPair & m= in_correspondences[i];
m.this_idx = i;
m.other_idx = i;
m.this_x = mrpt::random::randomGenerator.drawUniform(-10,10);
m.this_y = mrpt::random::randomGenerator.drawUniform(-10,10);
m.this_z = mrpt::random::randomGenerator.drawUniform(-10,10);
m.other_x = mrpt::random::randomGenerator.drawUniform(-10,10);
m.other_y = mrpt::random::randomGenerator.drawUniform(-10,10);
m.other_z = mrpt::random::randomGenerator.drawUniform(-10,10);
}
const size_t N = nRepets;
CTicTac tictac;
tictac.Tic();
for (size_t i=0;i<N;i++)
{
mrpt::scanmatching::leastSquareErrorRigidTransformation(in_correspondences,out_pose);
}
const double T = tictac.Tac()/N;
return T;
}
// ------------------------------------------------------
// register_tests_scan_matching
// ------------------------------------------------------
void register_tests_scan_matching()
{
lstTests.push_back( TestData("scan_matching: 6D LS Rigid Trans. [CPose3D]", scan_matching_test_1 , 1e4 ) );
lstTests.push_back( TestData("scan_matching: 6D LS Rigid Trans. [CPose3DQuat]", scan_matching_test_2 , 1e4) );
lstTests.push_back( TestData("scan_matching: 6D LS Rigid Trans. [vector of points]", scan_matching_test_3 , 1e4) );
lstTests.push_back( TestData("scan_matching: leastSquares 2D [x10 corrs]", scan_matching_test_4, 10, 1e6 ) );
lstTests.push_back( TestData("scan_matching: leastSquares 2D [x100 corrs]", scan_matching_test_4, 100, 1e6 ) );
lstTests.push_back( TestData("scan_matching: leastSquares 2D [x1000 corrs]", scan_matching_test_4, 1000, 1e5 ) );
}
| bsd-3-clause |
KevinFasusi/supplychainpy | supplychainpy/_helpers/_cpu_info.py | 481 | import multiprocessing as mp
class CoreCount:
""" Manage cpu core count for setting multiprocessing tasks.
"""
def __init__(self):
self._core_count = self._get_core_count()
@property
def core_count(self) ->int:
"""Returns system core count.
"""
return self._core_count
@staticmethod
def _get_core_count()->int:
return int(mp.cpu_count())
if __name__ =="__main__":
c = CoreCount()
print(c.core_count) | bsd-3-clause |
silkyar/570_Big_Little | build/ARM/debug/NoncoherentBus.cc | 178 | /*
* DO NOT EDIT THIS FILE! Automatically generated
*/
#include "base/debug.hh"
namespace Debug {
SimpleFlag NoncoherentBus("NoncoherentBus", "None");
} // namespace Debug
| bsd-3-clause |
ric2b/Vivaldi-browser | chromium/components/component_updater/installer_policies/autofill_states_component_installer.cc | 4399 | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/component_updater/installer_policies/autofill_states_component_installer.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/ranges/algorithm.h"
#include "base/task/post_task.h"
#include "components/autofill/core/browser/geo/country_data.h"
#include "components/autofill/core/common/autofill_prefs.h"
#include "components/component_updater/component_updater_service.h"
#include "components/prefs/pref_registry_simple.h"
namespace {
// The SHA256 of the SubjectPublicKeyInfo used to sign the extension.
// The extension id is: eeigpngbgcognadeebkilcpcaedhellh
const std::array<uint8_t, 32> kAutofillStatesPublicKeySHA256 = {
0x44, 0x86, 0xfd, 0x61, 0x62, 0xe6, 0xd0, 0x34, 0x41, 0xa8, 0xb2,
0xf2, 0x04, 0x37, 0x4b, 0xb7, 0x0b, 0xae, 0x93, 0x12, 0x9d, 0x58,
0x15, 0xb5, 0xdd, 0x89, 0xf2, 0x98, 0x73, 0xd3, 0x08, 0x97};
// Returns the filenames corresponding to the states data.
std::vector<base::FilePath> AutofillStateFileNames() {
std::vector<base::FilePath> filenames;
for (const auto& country_code :
autofill::CountryDataMap::GetInstance()->country_codes()) {
filenames.push_back(base::FilePath().AppendASCII(country_code));
}
return filenames;
}
} // namespace
namespace component_updater {
// static
void AutofillStatesComponentInstallerPolicy::RegisterPrefs(
PrefRegistrySimple* registry) {
registry->RegisterStringPref(autofill::prefs::kAutofillStatesDataDir, "");
}
AutofillStatesComponentInstallerPolicy::AutofillStatesComponentInstallerPolicy(
PrefService* pref_service)
: pref_service_(pref_service) {}
AutofillStatesComponentInstallerPolicy::
~AutofillStatesComponentInstallerPolicy() = default;
bool AutofillStatesComponentInstallerPolicy::
SupportsGroupPolicyEnabledComponentUpdates() const {
return false;
}
bool AutofillStatesComponentInstallerPolicy::RequiresNetworkEncryption() const {
return false;
}
update_client::CrxInstaller::Result
AutofillStatesComponentInstallerPolicy::OnCustomInstall(
const base::DictionaryValue& manifest,
const base::FilePath& install_dir) {
return update_client::CrxInstaller::Result(update_client::InstallError::NONE);
}
void AutofillStatesComponentInstallerPolicy::OnCustomUninstall() {}
void AutofillStatesComponentInstallerPolicy::ComponentReady(
const base::Version& version,
const base::FilePath& install_dir,
std::unique_ptr<base::DictionaryValue> manifest) {
DVLOG(1) << "Component ready, version " << version.GetString() << " in "
<< install_dir.value();
DCHECK(pref_service_);
pref_service_->SetFilePath(autofill::prefs::kAutofillStatesDataDir,
install_dir);
}
// Called during startup and installation before ComponentReady().
bool AutofillStatesComponentInstallerPolicy::VerifyInstallation(
const base::DictionaryValue& manifest,
const base::FilePath& install_dir) const {
// Verify that state files are present.
return base::ranges::count(
AutofillStateFileNames(), true, [&](const auto& filename) {
return base::PathExists(install_dir.Append(filename));
}) > 0;
}
base::FilePath AutofillStatesComponentInstallerPolicy::GetRelativeInstallDir()
const {
return base::FilePath(FILE_PATH_LITERAL("AutofillStates"));
}
void AutofillStatesComponentInstallerPolicy::GetHash(
std::vector<uint8_t>* hash) const {
hash->assign(kAutofillStatesPublicKeySHA256.begin(),
kAutofillStatesPublicKeySHA256.end());
}
std::string AutofillStatesComponentInstallerPolicy::GetName() const {
return "Autofill States Data";
}
update_client::InstallerAttributes
AutofillStatesComponentInstallerPolicy::GetInstallerAttributes() const {
return update_client::InstallerAttributes();
}
void RegisterAutofillStatesComponent(ComponentUpdateService* cus,
PrefService* prefs) {
DVLOG(1) << "Registering Autofill States data component.";
auto installer = base::MakeRefCounted<ComponentInstaller>(
std::make_unique<AutofillStatesComponentInstallerPolicy>(prefs));
installer->Register(cus, base::OnceClosure());
}
} // namespace component_updater
| bsd-3-clause |
pdepend/pdepend | src/test/php/PDepend/Source/Parser/ASTAllocationExpressionParsingTest.php | 10629 | <?php
/**
* This file is part of PDepend.
*
* PHP Version 5
*
* Copyright (c) 2008-2017 Manuel Pichler <mapi@pdepend.org>.
* 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 Manuel Pichler nor the names of his
* 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 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.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.2
*/
namespace PDepend\Source\Parser;
use PDepend\Source\AST\ASTAllocationExpression;
use PDepend\Source\AST\ASTClassReference;
use PDepend\Source\AST\ASTFunctionPostfix;
use PDepend\Source\AST\ASTMemberPrimaryPrefix;
use PDepend\Source\AST\ASTParentReference;
use PDepend\Source\AST\ASTSelfReference;
use PDepend\Source\AST\ASTStaticReference;
use PDepend\Source\AST\ASTVariable;
use PDepend\Source\AST\ASTVariableVariable;
/**
* Test case for the {@link \PDepend\Source\Language\PHP\AbstractPHPParser} class.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.2
*
* @covers \PDepend\Source\Language\PHP\AbstractPHPParser
* @group unittest
*/
class ASTAllocationExpressionParsingTest extends AbstractParserTest
{
/**
* testAllocationExpressionForSelfProperty
*
* @return void
* @since 1.0.1
*/
public function testAllocationExpressionForSelfProperty()
{
$allocation = $this->getFirstAllocationInClass();
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTMemberPrimaryPrefix', $allocation->getChild(0));
}
/**
* testAllocationExpressionForParentProperty
*
* @return void
* @since 1.0.1
*/
public function testAllocationExpressionForParentProperty()
{
$allocation = $this->getFirstAllocationInClass();
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTMemberPrimaryPrefix', $allocation->getChild(0));
}
/**
* testAllocationExpressionForStaticProperty
*
* @return void
* @since 1.0.1
*/
public function testAllocationExpressionForStaticProperty()
{
$allocation = $this->getFirstAllocationInClass();
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTMemberPrimaryPrefix', $allocation->getChild(0));
}
/**
* testAllocationExpressionForThisProperty
*
* @return void
* @since 1.0.1
*/
public function testAllocationExpressionForThisProperty()
{
$allocation = $this->getFirstAllocationInClass();
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTFunctionPostfix', $allocation->getChild(0));
}
/**
* testAllocationExpressionForObjectProperty
*
* @return void
* @since 1.0.1
*/
public function testAllocationExpressionForObjectProperty()
{
$allocation = $this->getFirstAllocationInClass();
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTMemberPrimaryPrefix', $allocation->getChild(0));
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForSimpleIdentifier()
{
$function = $this->getFirstFunctionForTestCase();
$allocation = $function->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$reference = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTClassReference', $reference);
$this->assertEquals('Foo', $reference->getType()->getName());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForSelfKeyword()
{
$method = $this->getFirstClassMethodForTestCase();
$allocation = $method->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$self = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTSelfReference', $self);
$this->assertEquals(__FUNCTION__, $self->getType()->getName());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForParentKeyword()
{
$method = $this->getFirstClassMethodForTestCase();
$allocation = $method->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$parent = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTParentReference', $parent);
$this->assertEquals(__FUNCTION__ . 'Parent', $parent->getType()->getName());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForLocalNamespaceIdentifier()
{
$function = $this->getFirstFunctionForTestCase();
$allocation = $function->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$reference = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTClassReference', $reference);
$this->assertEquals('Bar', $reference->getType()->getName());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForAbsoluteNamespaceIdentifier()
{
$function = $this->getFirstFunctionForTestCase();
$allocation = $function->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$reference = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTClassReference', $reference);
$this->assertEquals('Bar', $reference->getType()->getName());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForAbsoluteNamespacedNamespaceIdentifier()
{
$function = $this->getFirstFunctionForTestCase();
$allocation = $function->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$reference = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTClassReference', $reference);
$this->assertEquals('Foo', $reference->getType()->getName());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForVariableIdentifier()
{
$function = $this->getFirstFunctionForTestCase();
$allocation = $function->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$variable = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTVariable', $variable);
$this->assertEquals('$foo', $variable->getImage());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForVariableVariableIdentifier()
{
$function = $this->getFirstFunctionForTestCase();
$allocation = $function->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$vvariable = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTVariableVariable', $vvariable);
$this->assertEquals('$', $vvariable->getImage());
$variable = $vvariable->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTVariable', $variable);
$this->assertEquals('$foo', $variable->getImage());
}
/**
* Tests that the allocation object graph contains the expected objects
*
* @return void
*/
public function testAllocationExpressionGraphForStaticReference()
{
$method = $this->getFirstClassMethodForTestCase();
$allocation = $method->getFirstChildOfType('PDepend\\Source\\AST\\ASTAllocationExpression');
$reference = $allocation->getChild(0);
$this->assertInstanceOf('PDepend\\Source\\AST\\ASTStaticReference', $reference);
$this->assertEquals(__FUNCTION__, $reference->getType()->getName());
}
/**
* Tests that invalid allocation expression results in the expected
* exception.
*
* @return void
*/
public function testInvalidAllocationExpressionResultsInExpectedException()
{
$this->setExpectedException(
'\\PDepend\\Source\\Parser\\UnexpectedTokenException',
'Unexpected token: ;, line: 4, col: 9, file: '
);
$this->parseCodeResourceForTest();
}
/**
* Returns the first allocation expression found in the test file associated
* with the calling test method.
*
* @return ASTAllocationExpression
* @since 1.0.1
*/
private function getFirstAllocationInClass()
{
return $this->getFirstNodeOfTypeInClass(
$this->getCallingTestMethod(),
'PDepend\\Source\\AST\\ASTAllocationExpression'
);
}
}
| bsd-3-clause |
verma/PDAL | boost/boost/mpl/vector/aux_/preprocessed/plain/vector40.hpp | 67821 |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/vector/vector40.hpp" header
// -- DO NOT modify by hand!
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace mpl {
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30
>
struct vector31
{
typedef aux::vector_tag<31> tag;
typedef vector31 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef void_ item31;
typedef T30 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,31 > end;
};
template<>
struct push_front_impl< aux::vector_tag<30> >
{
template< typename Vector, typename T > struct apply
{
typedef vector31<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<31> >
{
template< typename Vector > struct apply
{
typedef vector30<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<30> >
{
template< typename Vector, typename T > struct apply
{
typedef vector31<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<31> >
{
template< typename Vector > struct apply
{
typedef vector30<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
> type;
};
};
template< typename V >
struct v_at< V,31 >
{
typedef typename V::item31 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31
>
struct vector32
{
typedef aux::vector_tag<32> tag;
typedef vector32 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef void_ item32;
typedef T31 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,32 > end;
};
template<>
struct push_front_impl< aux::vector_tag<31> >
{
template< typename Vector, typename T > struct apply
{
typedef vector32<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<32> >
{
template< typename Vector > struct apply
{
typedef vector31<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<31> >
{
template< typename Vector, typename T > struct apply
{
typedef vector32<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<32> >
{
template< typename Vector > struct apply
{
typedef vector31<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30
> type;
};
};
template< typename V >
struct v_at< V,32 >
{
typedef typename V::item32 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32
>
struct vector33
{
typedef aux::vector_tag<33> tag;
typedef vector33 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef void_ item33;
typedef T32 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,33 > end;
};
template<>
struct push_front_impl< aux::vector_tag<32> >
{
template< typename Vector, typename T > struct apply
{
typedef vector33<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<33> >
{
template< typename Vector > struct apply
{
typedef vector32<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<32> >
{
template< typename Vector, typename T > struct apply
{
typedef vector33<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<33> >
{
template< typename Vector > struct apply
{
typedef vector32<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
> type;
};
};
template< typename V >
struct v_at< V,33 >
{
typedef typename V::item33 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32, typename T33
>
struct vector34
{
typedef aux::vector_tag<34> tag;
typedef vector34 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef T33 item33;
typedef void_ item34;
typedef T33 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,34 > end;
};
template<>
struct push_front_impl< aux::vector_tag<33> >
{
template< typename Vector, typename T > struct apply
{
typedef vector34<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<34> >
{
template< typename Vector > struct apply
{
typedef vector33<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
, typename Vector::item33
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<33> >
{
template< typename Vector, typename T > struct apply
{
typedef vector34<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<34> >
{
template< typename Vector > struct apply
{
typedef vector33<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32
> type;
};
};
template< typename V >
struct v_at< V,34 >
{
typedef typename V::item34 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32, typename T33, typename T34
>
struct vector35
{
typedef aux::vector_tag<35> tag;
typedef vector35 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef T33 item33;
typedef T34 item34;
typedef void_ item35;
typedef T34 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,35 > end;
};
template<>
struct push_front_impl< aux::vector_tag<34> >
{
template< typename Vector, typename T > struct apply
{
typedef vector35<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<35> >
{
template< typename Vector > struct apply
{
typedef vector34<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
, typename Vector::item33, typename Vector::item34
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<34> >
{
template< typename Vector, typename T > struct apply
{
typedef vector35<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<35> >
{
template< typename Vector > struct apply
{
typedef vector34<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
> type;
};
};
template< typename V >
struct v_at< V,35 >
{
typedef typename V::item35 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32, typename T33, typename T34
, typename T35
>
struct vector36
{
typedef aux::vector_tag<36> tag;
typedef vector36 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef T33 item33;
typedef T34 item34;
typedef T35 item35;
typedef void_ item36;
typedef T35 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,36 > end;
};
template<>
struct push_front_impl< aux::vector_tag<35> >
{
template< typename Vector, typename T > struct apply
{
typedef vector36<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<36> >
{
template< typename Vector > struct apply
{
typedef vector35<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
, typename Vector::item33, typename Vector::item34
, typename Vector::item35
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<35> >
{
template< typename Vector, typename T > struct apply
{
typedef vector36<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<36> >
{
template< typename Vector > struct apply
{
typedef vector35<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34
> type;
};
};
template< typename V >
struct v_at< V,36 >
{
typedef typename V::item36 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32, typename T33, typename T34
, typename T35, typename T36
>
struct vector37
{
typedef aux::vector_tag<37> tag;
typedef vector37 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef T33 item33;
typedef T34 item34;
typedef T35 item35;
typedef T36 item36;
typedef void_ item37;
typedef T36 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,37 > end;
};
template<>
struct push_front_impl< aux::vector_tag<36> >
{
template< typename Vector, typename T > struct apply
{
typedef vector37<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<37> >
{
template< typename Vector > struct apply
{
typedef vector36<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
, typename Vector::item33, typename Vector::item34
, typename Vector::item35, typename Vector::item36
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<36> >
{
template< typename Vector, typename T > struct apply
{
typedef vector37<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<37> >
{
template< typename Vector > struct apply
{
typedef vector36<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
> type;
};
};
template< typename V >
struct v_at< V,37 >
{
typedef typename V::item37 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32, typename T33, typename T34
, typename T35, typename T36, typename T37
>
struct vector38
{
typedef aux::vector_tag<38> tag;
typedef vector38 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef T33 item33;
typedef T34 item34;
typedef T35 item35;
typedef T36 item36;
typedef T37 item37;
typedef void_ item38;
typedef T37 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,38 > end;
};
template<>
struct push_front_impl< aux::vector_tag<37> >
{
template< typename Vector, typename T > struct apply
{
typedef vector38<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<38> >
{
template< typename Vector > struct apply
{
typedef vector37<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
, typename Vector::item33, typename Vector::item34
, typename Vector::item35, typename Vector::item36
, typename Vector::item37
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<37> >
{
template< typename Vector, typename T > struct apply
{
typedef vector38<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<38> >
{
template< typename Vector > struct apply
{
typedef vector37<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36
> type;
};
};
template< typename V >
struct v_at< V,38 >
{
typedef typename V::item38 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32, typename T33, typename T34
, typename T35, typename T36, typename T37, typename T38
>
struct vector39
{
typedef aux::vector_tag<39> tag;
typedef vector39 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef T33 item33;
typedef T34 item34;
typedef T35 item35;
typedef T36 item36;
typedef T37 item37;
typedef T38 item38;
typedef void_ item39;
typedef T38 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,39 > end;
};
template<>
struct push_front_impl< aux::vector_tag<38> >
{
template< typename Vector, typename T > struct apply
{
typedef vector39<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36, typename Vector::item37
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<39> >
{
template< typename Vector > struct apply
{
typedef vector38<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
, typename Vector::item33, typename Vector::item34
, typename Vector::item35, typename Vector::item36
, typename Vector::item37, typename Vector::item38
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<38> >
{
template< typename Vector, typename T > struct apply
{
typedef vector39<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36, typename Vector::item37
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<39> >
{
template< typename Vector > struct apply
{
typedef vector38<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36, typename Vector::item37
> type;
};
};
template< typename V >
struct v_at< V,39 >
{
typedef typename V::item39 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
, typename T20, typename T21, typename T22, typename T23, typename T24
, typename T25, typename T26, typename T27, typename T28, typename T29
, typename T30, typename T31, typename T32, typename T33, typename T34
, typename T35, typename T36, typename T37, typename T38, typename T39
>
struct vector40
{
typedef aux::vector_tag<40> tag;
typedef vector40 type;
typedef T0 item0;
typedef T1 item1;
typedef T2 item2;
typedef T3 item3;
typedef T4 item4;
typedef T5 item5;
typedef T6 item6;
typedef T7 item7;
typedef T8 item8;
typedef T9 item9;
typedef T10 item10;
typedef T11 item11;
typedef T12 item12;
typedef T13 item13;
typedef T14 item14;
typedef T15 item15;
typedef T16 item16;
typedef T17 item17;
typedef T18 item18;
typedef T19 item19;
typedef T20 item20;
typedef T21 item21;
typedef T22 item22;
typedef T23 item23;
typedef T24 item24;
typedef T25 item25;
typedef T26 item26;
typedef T27 item27;
typedef T28 item28;
typedef T29 item29;
typedef T30 item30;
typedef T31 item31;
typedef T32 item32;
typedef T33 item33;
typedef T34 item34;
typedef T35 item35;
typedef T36 item36;
typedef T37 item37;
typedef T38 item38;
typedef T39 item39;
typedef void_ item40;
typedef T39 back;
typedef v_iter< type,0 > begin;
typedef v_iter< type,40 > end;
};
template<>
struct push_front_impl< aux::vector_tag<39> >
{
template< typename Vector, typename T > struct apply
{
typedef vector40<
T
,
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36, typename Vector::item37
, typename Vector::item38
> type;
};
};
template<>
struct pop_front_impl< aux::vector_tag<40> >
{
template< typename Vector > struct apply
{
typedef vector39<
typename Vector::item1, typename Vector::item2
, typename Vector::item3, typename Vector::item4
, typename Vector::item5, typename Vector::item6
, typename Vector::item7, typename Vector::item8
, typename Vector::item9, typename Vector::item10
, typename Vector::item11, typename Vector::item12
, typename Vector::item13, typename Vector::item14
, typename Vector::item15, typename Vector::item16
, typename Vector::item17, typename Vector::item18
, typename Vector::item19, typename Vector::item20
, typename Vector::item21, typename Vector::item22
, typename Vector::item23, typename Vector::item24
, typename Vector::item25, typename Vector::item26
, typename Vector::item27, typename Vector::item28
, typename Vector::item29, typename Vector::item30
, typename Vector::item31, typename Vector::item32
, typename Vector::item33, typename Vector::item34
, typename Vector::item35, typename Vector::item36
, typename Vector::item37, typename Vector::item38
, typename Vector::item39
> type;
};
};
template<>
struct push_back_impl< aux::vector_tag<39> >
{
template< typename Vector, typename T > struct apply
{
typedef vector40<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36, typename Vector::item37
, typename Vector::item38
,
T
> type;
};
};
template<>
struct pop_back_impl< aux::vector_tag<40> >
{
template< typename Vector > struct apply
{
typedef vector39<
typename Vector::item0, typename Vector::item1
, typename Vector::item2, typename Vector::item3
, typename Vector::item4, typename Vector::item5
, typename Vector::item6, typename Vector::item7
, typename Vector::item8, typename Vector::item9
, typename Vector::item10, typename Vector::item11
, typename Vector::item12, typename Vector::item13
, typename Vector::item14, typename Vector::item15
, typename Vector::item16, typename Vector::item17
, typename Vector::item18, typename Vector::item19
, typename Vector::item20, typename Vector::item21
, typename Vector::item22, typename Vector::item23
, typename Vector::item24, typename Vector::item25
, typename Vector::item26, typename Vector::item27
, typename Vector::item28, typename Vector::item29
, typename Vector::item30, typename Vector::item31
, typename Vector::item32, typename Vector::item33
, typename Vector::item34, typename Vector::item35
, typename Vector::item36, typename Vector::item37
, typename Vector::item38
> type;
};
};
template< typename V >
struct v_at< V,40 >
{
typedef typename V::item40 type;
};
}}
| bsd-3-clause |
genome-vendor/apollo | src/java/jalview/gui/ProgressFrame.java | 1346 | package jalview.gui;
import jalview.analysis.*;
import jalview.io.*;
import java.awt.*;
import java.awt.event.*;
public class ProgressFrame extends Frame {
Object parent;
ProgressPanel pp;
TextArea ta;
TextAreaPrintStream taps;
ProgressWindowListener pal;
public ProgressFrame(String title,Object parent,Thread th) {
super(title);
this.parent = parent;
pp = new ProgressPanel(this,th);
setLayout(new GridLayout(2,1));
ta = new TextArea(50,20);
taps = new TextAreaPrintStream(System.out,ta);
resize(400,500);
add(pp);
add(ta);
pal = new ProgressWindowListener();
addWindowListener(pal);
}
public TextArea getTextArea() {
return ta;
}
public void setCommandThread(Thread t) {
pp.setThread(t);
}
public Thread createProgressThread() {
return new Thread(pp);
}
class ProgressWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
if (pp.ct instanceof CommandThread) {
pp.status.setText("Destroying process");
((CommandThread)pp.ct).getProcess().destroy();
}
if (parent != null || !AlignFrame.exitOnClose()) {
ProgressFrame.this.hide();
ProgressFrame.this.dispose();
} else if (parent == null) {
System.exit(0);
}
}
}
}
| bsd-3-clause |
zucchi/ZucchiUploader | src/ZucchiUploader/View/Helper/Uploader.php | 3287 | <?php
namespace ZucchiUploader\View\Helper;
use Zend\View\Helper\AbstractHtmlElement;
use Zend\Form\Element\Button;
use ZucchiUploader\Options\UploaderOptions;
class Uploader extends AbstractHtmlElement
{
protected $options;
/**
* @param $url
* @param array $attribs
* @param array $options
* @param array $events
* @return string
*/
public function __invoke($url, $attribs = array(), $options = array())
{
$view = $this->getView();
$config= $this->getOptions();
if (!empty($options)) {
$config->setFromArray($options);
}
$config->setUrl($url);
$view->inlineScript()->appendFile($config->getPath() . 'plupload.js');
$runtimes = explode(',', $config->getRuntimes());
foreach ($runtimes as $runtime) {
$view->inlineScript()->appendFile($config->getPath() . 'plupload.' . $runtime . '.js');
}
$settings = json_encode(
$config,
JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
$view->inlineScript()
->appendScript(
"var uploader = new plupload.Uploader(" . $settings .");" . PHP_EOL .
"uploader.init();" . PHP_EOL .
"uploader.bind('FilesAdded', function(up, files) { uploader.start(); });" . PHP_EOL .
"uploader.bind('Error', function(up, err){
var file = err.file, message;
if (file) {
message = err.message;
if (err.details) {message += ' (' + err.details + ')';}
if (err.code == plupload.FILE_SIZE_ERROR) {alert(_('Error: File too large: ') + file.name);}
if (err.code == plupload.FILE_EXTENSION_ERROR) {alert(_('Error: Invalid file extension: ') + file.name);}
}
});" . PHP_EOL .
"uploader.bind('FileUploaded', function(up, file, info){
var data = JSON.parse(info.response);
if (!data.success) {
var msgs = '';
for (var i in data.messages) {
msgs += data.messages[i] + \"\\n\";
}
alert(msgs);
}
});"
);
$html = '<div id="' . $config->getContainer() . '">';
$button = new Button($config->getBrowse_button());
$button->setLabel('Upload');
$button->setAttribute('id', $config->getBrowse_button());
$button->setAttributes($attribs);
$html .= $view->formButton($button);
$html .= '</div>';
return $html;
}
/**
*
* @param UploaderOptions $options
* @return \ZucchiUploader\View\Helper\Uploader
*/
public function setOptions(UploaderOptions $options)
{
$this->options = $options;
return $this;
}
/**
*
* @return UploaderOptions
*/
public function getOptions()
{
return $this->options;
}
} | bsd-3-clause |
alexander-alvarez/django_polymorphic | example/pexp/management/commands/polybench.py | 2881 | # -*- coding: utf-8 -*-
"""
This module is a scratchpad for general development, testing & debugging
"""
import django
from django.core.management.base import NoArgsCommand
from django.db import connection
from pprint import pprint
import sys
from pexp.models import *
num_objects = 1000
def reset_queries():
if django.VERSION < (1, 9):
connection.queries = []
else:
connection.queries_log.clear()
def show_queries():
print
print 'QUERIES:', len(connection.queries)
pprint(connection.queries)
print
reset_queries()
import time
###################################################################################
# benchmark wrappers
def print_timing(func, message='', iterations=1):
def wrapper(*arg):
results = []
reset_queries()
for i in xrange(iterations):
t1 = time.time()
x = func(*arg)
t2 = time.time()
results.append((t2 - t1) * 1000.0)
res_sum = 0
for r in results:
res_sum += r
median = res_sum / len(results)
print '%s%-19s: %.0f ms, %i queries' % (
message, func.func_name,
median,
len(connection.queries) / len(results)
)
sys.stdout.flush()
return wrapper
def run_vanilla_any_poly(func, iterations=1):
f = print_timing(func, ' ', iterations)
f(nModelC)
f = print_timing(func, 'poly ', iterations)
f(ModelC)
###################################################################################
# benchmarks
def bench_create(model):
for i in xrange(num_objects):
model.objects.create(field1='abc' + str(i), field2='abcd' + str(i), field3='abcde' + str(i))
# print 'count:',model.objects.count()
def bench_load1(model):
for o in model.objects.all():
pass
def bench_load1_short(model):
for i in xrange(num_objects / 100):
for o in model.objects.all()[:100]:
pass
def bench_load2(model):
for o in model.objects.all():
f1 = o.field1
f2 = o.field2
f3 = o.field3
def bench_load2_short(model):
for i in xrange(num_objects / 100):
for o in model.objects.all()[:100]:
f1 = o.field1
f2 = o.field2
f3 = o.field3
def bench_delete(model):
model.objects.all().delete()
###################################################################################
# Command
class Command(NoArgsCommand):
help = ""
def handle_noargs(self, **options):
func_list = [
(bench_delete, 1),
(bench_create, 1),
(bench_load1, 5),
(bench_load1_short, 5),
(bench_load2, 5),
(bench_load2_short, 5)
]
for f, iterations in func_list:
run_vanilla_any_poly(f, iterations=iterations)
print
| bsd-3-clause |
psygate/CivModCore | src/main/java/vg/civcraft/mc/civmodcore/inventorygui/LClickable.java | 1246 | package vg.civcraft.mc.civmodcore.inventorygui;
import java.util.function.Consumer;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import vg.civcraft.mc.civmodcore.api.ItemAPI;
/**
* Convience class for lambda support in clickables. Unfortunately java doesn't
* allow usage of abstract classes as functional interfaces, see also
* https://stackoverflow.com/questions/24610207/abstract-class-as-functional-interface
*
*/
public class LClickable extends Clickable {
private Consumer<Player> clickFunction;
public LClickable(Material mat, String name, Consumer<Player> clickFunction) {
this(mat, clickFunction);
ItemAPI.setDisplayName(this.item, name);
}
public LClickable(Material mat, String name, Consumer<Player> clickFunction, String ... lore) {
this(mat, name, clickFunction);
if (lore.length > 0) {
ItemAPI.addLore(this.item, lore);
}
}
public LClickable(Material mat, Consumer<Player> clickFunction) {
this(new ItemStack(mat), clickFunction);
}
public LClickable(ItemStack item, Consumer<Player> clickFunction) {
super(item);
this.clickFunction = clickFunction;
}
@Override
public void clicked(Player p) {
clickFunction.accept(p);
}
}
| bsd-3-clause |
vin120/vcos | backend/modules/voyagemanagement/controllers/ActiveConfigController.php | 11122 | <?php
namespace app\modules\voyagemanagement\controllers;
use Yii;
use yii\helpers\Url;
use yii\web\Controller;
use app\modules\voyagemanagement\components\Helper;
use app\modules\voyagemanagement\models\VCActive;
use app\modules\voyagemanagement\models\VCActiveI18n;
use app\modules\voyagemanagement\models\VCActiveDetail;
use app\modules\voyagemanagement\models\VCActiveDetailI18n;
use yii\db\Query;
class ActiveconfigController extends Controller
{
public function actionActive_config()
{
if(isset($_GET['active_id'])){
$active_id = $_GET['active_id'];
VCActive::deleteAll(['active_id'=>$active_id]);
VCActiveI18n::deleteAll(['active_id'=>$active_id]);
Helper::show_message('Delete successful ', Url::toRoute(['active_config']));
}
if(isset($_POST['ids'])){
$ids = implode(',', $_POST['ids']);
VCActive::deleteAll("active_id in ($ids)");
VCActiveI18n::deleteAll("active_id in ($ids)");
Helper::show_message('Delete successful ', Url::toRoute(['active_config']));
}
$query = new Query();
$actives = $query->select(['v_c_active.*','v_c_active_i18n.name','v_c_active_i18n.i18n'])
->from('v_c_active')
->join('LEFT JOIN','v_c_active_i18n','v_c_active.active_id=v_c_active_i18n.active_id')
->where(['v_c_active_i18n.i18n'=>'en'])
->limit(2)
->all();
$count = VCActive::find()->count();
return $this->render("active_config",['actives'=>$actives,'count'=>$count,'active_page'=>1]);
}
//活动分页
public function actionGet_active_page()
{
$pag = isset($_GET['pag']) ? $_GET['pag']==1 ? 0 :($_GET['pag']-1) * 2 : 0;
$query = new Query();
$result = $query->select(['a.*','b.name'])
->from('v_c_active a')
->join('LEFT JOIN','v_c_active_i18n b','a.active_id=b.active_id')
->where(['b.i18n'=>'en'])
->offset($pag)
->limit(2)
->all();
if($result){
echo json_encode($result);
}else{
echo 0;
}
}
//详细活动分页
public function actionGet_active_config_page()
{
$pag = isset($_GET['pag']) ? $_GET['pag']==1 ? 0 :($_GET['pag']-1) * 2 : 0;
$active_id = isset($_GET['active_id']) ? $_GET['active_id'] : '';
$query = new Query();
$result = $query->select(['a.id','a.day_from','a.day_to','b.detail_title','b.detail_desc'])
->from('v_c_active_detail a')
->join('LEFT JOIN','v_c_active_detail_i18n b','a.id=b.active_detail_id')
->where(['b.i18n'=>'en','a.active_id'=>$active_id])
->offset($pag)
->limit(2)
->all();
if($result){
echo json_encode($result);
}else{
echo 0;
}
}
//Active Config Add
public function actionActive_config_add()
{
if(isset($_POST)){
$name = isset($_POST['name']) ? $_POST['name'] : '';
$active_select = isset($_POST['active_select']) ? $_POST['active_select'] : '';
if($name != '' && $active_select != ''){
$transaction = Yii::$app->db->beginTransaction();
try{
$vcactive = new VCActive();
$vcactive->status = $active_select;
$vcactive->save();
$last_active_id = Yii::$app->db->getLastInsertID();
$vcactivei18n = new VCActiveI18n();
$vcactivei18n->active_id = $last_active_id;
$vcactivei18n->name = $name;
$vcactivei18n->i18n = 'en';
$vcactivei18n->save();
Helper::show_message('Save successful', Url::toRoute(['active_config_edit'])."&active_id=".$last_active_id);
$transaction->commit();
}catch (Exception $e){
$transaction->rollBack();
Helper::show_message('Save failed', Url::toRoute(['active_config_add']));
}
}
}
return $this->render("active_config_add");
}
//Active Config Edit
public function actionActive_config_edit()
{
//获取编辑页面的信息
$active_id = isset($_GET['active_id']) ? $_GET['active_id'] : '';
$query = new Query();
$active = $query->select(['a.active_id','a.status','b.name'])
->from('v_c_active a')
->join('LEFT JOIN','v_c_active_i18n b','a.active_id=b.active_id')
->where(['a.active_id'=>$active_id,'b.i18n'=>'en'])
->one();
$count = VCActiveDetail::find()->where(['active_id'=>$active_id])->count();
//更新编辑页面的信息
if(isset($_POST)){
$name = isset($_POST['name']) ? $_POST['name'] : '';
$active_select = isset($_POST['active_select']) ? $_POST['active_select'] : '';
$active_id_post = isset($_POST['active_id']) ? $_POST['active_id'] : '';
if($name != '' && $active_select != '' && $active_id_post){
$transaction = Yii::$app->db->beginTransaction();
try{
VCActive::updateAll(['status'=>$active_select],['active_id'=>$active_id_post]);
VCActiveI18n::updateAll(['name'=>$name],['active_id'=>$active_id_post,'i18n'=>'en']);
Helper::show_message('Save successful', Url::toRoute(['active_config_edit'])."&active_id=".$active_id_post);
$transaction->commit();
}catch (Exception $e){
$transaction->rollBack();
Helper::show_message('Save failed', Url::toRoute(['active_config_edit'])."&active_id=".$active_id_post);
}
}
}
return $this->render("active_config_edit",['active'=>$active,'count'=>$count,'active_config_page'=>1]);
}
//ajax获取active_config_edit页面的active_detail内容
public function actionGet_active_config_detail_ajax()
{
$active_id = isset($_GET['active_id']) ? $_GET['active_id'] : '';
$query = new Query();
$active_detail = $query->select(['a.id','a.day_from','a.day_to','b.detail_title','b.detail_desc'])
->from('v_c_active_detail a')
->join('LEFT JOIN','v_c_active_detail_i18n b','a.id=b.active_detail_id')
->where(['a.active_id'=>$active_id,'b.i18n'=>'en'])
->limit(2)
->all();
echo json_encode($active_detail);
}
public function actionActive_config_detail_add()
{
$active_id = isset($_GET['active_id']) ? $_GET['active_id'] : '';
$active = VCActive::find()->select(['active_id'])->where(['active_id'=>$active_id])->one();
if($_POST){
$day_from = isset($_POST['day_from']) ? $_POST['day_from'] : '';
$day_to = isset($_POST['day_to']) ? $_POST['day_to'] : '';
$active_id_post = isset($_POST['active_id']) ? $_POST['active_id'] : '';
$detail_title = isset($_POST['detail_title']) ? $_POST['detail_title'] : '';
$detail_desc = isset($_POST['detail_desc']) ? $_POST['detail_desc'] : '';
if($_FILES['photoimg']['error']!=4){
$result=Helper::upload_file('photoimg', Yii::$app->params['img_save_url'].'voyagemanagement/themes/basic/static/upload/'.date('Ym',time()), 'image', 3);
$photo=date('Ym',time()).'/'.$result['filename'];
}
if(!isset($photo)){
$photo="";
}
if($day_from != '' && $detail_title != ''){
//事务
$transaction = Yii::$app->db->beginTransaction();
try{
$vcactivedetail_obj = new VCActiveDetail();
$vcactivedetail_obj->active_id = $active_id_post;
$vcactivedetail_obj->day_from = $day_from;
if($day_to !=''){
$vcactivedetail_obj->day_to = $day_to;
}
$vcactivedetail_obj->detail_img = $photo;
$vcactivedetail_obj->save();
$last_active_detail_id = Yii::$app->db->getLastInsertID();
$vcactivedetaili18n_obj = new VCActiveDetailI18n();
$vcactivedetaili18n_obj->active_detail_id = $last_active_detail_id;
$vcactivedetaili18n_obj->detail_title = $detail_title;
$vcactivedetaili18n_obj->detail_desc = $detail_desc;
$vcactivedetaili18n_obj->i18n = 'en';
$vcactivedetaili18n_obj->save();
$transaction->commit();
Helper::show_message('Save success ', Url::toRoute(['active_config_edit'])."&active_id=".$active_id_post);
}catch(Exception $e){
$transaction->rollBack();
Helper::show_message('Save failed ','#');
}
}else{
Helper::show_message('Save failed ','#');
}
}
return $this->render("active_config_detail_add",['active'=>$active]);
}
public function actionActive_config_detail_edit()
{
$id = isset($_GET['id']) ? $_GET['id'] : '';
$active_id = isset($_GET['active_id']) ? $_GET['active_id'] : '';
$query = new Query();
$active_detail = $query->select(['a.id','a.active_id','a.day_from','a.day_to','a.detail_img','b.detail_title','b.detail_desc'])
->from('v_c_active_detail a')
->join('LEFT JOIN','v_c_active_detail_i18n b','a.id=b.active_detail_id')
->where(['a.id'=>$id,'b.i18n'=>'en','a.active_id'=>$active_id])
->one();
if(isset($_POST)){
$day_from = isset($_POST['day_from']) ? $_POST['day_from'] : '';
$day_to = isset($_POST['day_to']) ? $_POST['day_to'] : '';
$detail_title = isset($_POST['detail_title']) ? $_POST['detail_title'] : '';
$detail_desc = isset($_POST['detail_desc']) ? $_POST['detail_desc'] : '';
$active_id_post = isset($_POST['active_id']) ? $_POST['active_id'] : '';
$active_detail_id = isset($_POST['active_detail_id']) ? $_POST['active_detail_id'] :'';
if(isset($_FILES['photoimg'])){
if($_FILES['photoimg']['error']!=4){
$result=Helper::upload_file('photoimg', Yii::$app->params['img_save_url'].'voyagemanagement/themes/basic/static/upload/'.date('Ym',time()), 'image', 3);
$photo=date('Ym',time()).'/'.$result['filename'];
}
if(!isset($photo)){
$photo=null;
}
}
if($day_from != '' && $detail_title != '' && $active_detail_id !=''){
$transaction = Yii::$app->db->beginTransaction();
try{
$vcactivedetail_obj = VCActiveDetail::findOne($active_detail_id);
$vcactivedetail_obj->day_from = $day_from;
$vcactivedetail_obj->detail_img = $photo;
if($day_to != ''){
$vcactivedetail_obj->day_to = $day_to;
}
$vcactivedetail_obj->save();
$vcactivedetaili18n_obj = VCActiveDetailI18n::find()->where(['active_detail_id'=>$active_detail_id,'i18n'=>'en'])->one();
$vcactivedetaili18n_obj->detail_title = $detail_title;
$vcactivedetaili18n_obj->detail_desc = $detail_desc;
$vcactivedetaili18n_obj->save();
Helper::show_message('Save successful', Url::toRoute(['active_config_edit'])."&active_id=".$active_id_post);
$transaction->commit();
}catch (Exception $e){
$transaction->rollBack();
Helper::show_message('Save failed', Url::toRoute(['active_config_edit'])."&active_id=".$active_id_post);
}
}
}
return $this->render("active_config_detail_edit",['active_detail'=>$active_detail]);
}
//Delete Active Config Detail
public function actionActive_config_detail_delete()
{
//单项删除
if(isset($_GET['id'])){
$id = $_GET['id'];
$active_id = $_GET['active_id'];
VCActiveDetail::deleteAll(['id'=>$id]);
VCActiveDetailI18n::deleteAll(['active_detail_id'=>$id]);
Helper::show_message('Delete successful', Url::toRoute(['active_config_edit'])."&active_id=".$active_id);
}
//选中删除
if(isset($_POST['ids'])){
$ids = implode(',', $_POST['ids']);
$active_id = $_POST['active_id'];
VCActiveDetail::deleteAll("id in ($ids)");
VCActiveDetailI18n::deleteAll("active_detail_id in ($ids)");
VCActive::deleteAll("active_id in ($ids)");
VCActiveI18n::deleteAll("active_id in ($ids)");
Helper::show_message('Delete successful ', Url::toRoute(['active_config_edit'])."&active_id=".$active_id);
}
}
} | bsd-3-clause |
timsnyder/bokeh | bokehjs/src/lib/models/tools/gestures/lasso_select_tool.ts | 3953 | import {SelectTool, SelectToolView} from "./select_tool"
import {CallbackLike1} from "../../callbacks/callback"
import {PolyAnnotation} from "../../annotations/poly_annotation"
import {PolyGeometry} from "core/geometry"
import {GestureEvent, KeyEvent} from "core/ui_events"
import {Keys} from "core/dom"
import {Arrayable} from "core/types"
import * as p from "core/properties"
import {bk_tool_icon_lasso_select} from "styles/icons"
export class LassoSelectToolView extends SelectToolView {
model: LassoSelectTool
protected data: {sx: number[], sy: number[]} | null
initialize(): void {
super.initialize()
this.data = null
}
connect_signals(): void {
super.connect_signals()
this.connect(this.model.properties.active.change, () => this._active_change())
}
_active_change(): void {
if (!this.model.active)
this._clear_overlay()
}
_keyup(ev: KeyEvent): void {
if (ev.keyCode == Keys.Enter)
this._clear_overlay()
}
_pan_start(ev: GestureEvent): void {
const {sx, sy} = ev
this.data = {sx: [sx], sy: [sy]}
}
_pan(ev: GestureEvent): void {
const {sx: _sx, sy: _sy} = ev
const [sx, sy] = this.plot_view.frame.bbox.clip(_sx, _sy)
this.data!.sx.push(sx)
this.data!.sy.push(sy)
const overlay = this.model.overlay
overlay.update({xs: this.data!.sx, ys: this.data!.sy})
if (this.model.select_every_mousemove) {
const append = ev.shiftKey
this._do_select(this.data!.sx, this.data!.sy, false, append)
}
}
_pan_end(ev: GestureEvent): void {
this._clear_overlay()
const append = ev.shiftKey
this._do_select(this.data!.sx, this.data!.sy, true, append)
this.plot_view.push_state('lasso_select', {selection: this.plot_view.get_selection()})
}
_clear_overlay(): void {
this.model.overlay.update({xs: [], ys: []})
}
_do_select(sx: number[], sy: number[], final: boolean, append: boolean): void {
const geometry: PolyGeometry = {type: 'poly', sx, sy}
this._select(geometry, final, append)
}
_emit_callback(geometry: PolyGeometry): void {
const r = this.computed_renderers[0]
const frame = this.plot_view.frame
const xscale = frame.xscales[r.x_range_name]
const yscale = frame.yscales[r.y_range_name]
const x = xscale.v_invert(geometry.sx)
const y = yscale.v_invert(geometry.sy)
const g = {x, y, ...geometry}
if (this.model.callback != null)
this.model.callback.execute(this.model, {geometry: g})
}
}
const DEFAULT_POLY_OVERLAY = () => {
return new PolyAnnotation({
level: "overlay",
xs_units: "screen",
ys_units: "screen",
fill_color: {value: "lightgrey"},
fill_alpha: {value: 0.5},
line_color: {value: "black"},
line_alpha: {value: 1.0},
line_width: {value: 2},
line_dash: {value: [4, 4]},
})
}
export namespace LassoSelectTool {
export type Attrs = p.AttrsOf<Props>
export type Props = SelectTool.Props & {
select_every_mousemove: p.Property<boolean>
callback: p.Property<CallbackLike1<LassoSelectTool, {
geometry: PolyGeometry & {x: Arrayable<number>, y: Arrayable<number>}
}> | null>
overlay: p.Property<PolyAnnotation>
}
}
export interface LassoSelectTool extends LassoSelectTool.Attrs {}
export class LassoSelectTool extends SelectTool {
properties: LassoSelectTool.Props
/*override*/ overlay: PolyAnnotation
constructor(attrs?: Partial<LassoSelectTool.Attrs>) {
super(attrs)
}
static initClass(): void {
this.prototype.default_view = LassoSelectToolView
this.define<LassoSelectTool.Props>({
select_every_mousemove: [ p.Boolean, true ],
callback: [ p.Any ],
overlay: [ p.Instance, DEFAULT_POLY_OVERLAY ],
})
}
tool_name = "Lasso Select"
icon = bk_tool_icon_lasso_select
event_type = "pan" as "pan"
default_order = 12
}
LassoSelectTool.initClass()
| bsd-3-clause |
janisozaur/opentoonz | toonz/sources/translations/russian/tnzcore.ts | 2425 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru" sourcelanguage="en">
<context>
<name>QObject</name>
<message>
<location filename="../../common/tvrender/tpalette.cpp" line="197"/>
<source>colors</source>
<translation>цвета</translation>
</message>
<message>
<location filename="../../common/timage_io/tlevel_io.cpp" line="127"/>
<source>Skipping frame.</source>
<translation>Пропуск кадра.</translation>
</message>
<message>
<location filename="../../common/tsystem/tfilepath.cpp" line="694"/>
<source>Malformed frame name</source>
<translation>Неправильное имя файла</translation>
</message>
<message>
<location filename="../../include/tundo.h" line="46"/>
<source>Unidentified Action</source>
<translation>Нераспознанное действие</translation>
</message>
</context>
<context>
<name>TCenterLineStrokeStyle</name>
<message>
<location filename="../../common/tvrender/tsimplecolorstyles.cpp" line="683"/>
<source>Constant</source>
<translation>Постоянная</translation>
</message>
<message>
<location filename="../../common/tvrender/tsimplecolorstyles.cpp" line="716"/>
<source>Thickness</source>
<translation>Толщина</translation>
</message>
</context>
<context>
<name>TRasterImagePatternStrokeStyle</name>
<message>
<location filename="../../common/tvrender/tsimplecolorstyles.cpp" line="821"/>
<source>Distance</source>
<translation>Расстояние</translation>
</message>
<message>
<location filename="../../common/tvrender/tsimplecolorstyles.cpp" line="823"/>
<source>Rotation</source>
<translation>Вращение</translation>
</message>
</context>
<context>
<name>TVectorImagePatternStrokeStyle</name>
<message>
<location filename="../../common/tvrender/tsimplecolorstyles.cpp" line="1265"/>
<source>Distance</source>
<translation>Расстояние</translation>
</message>
<message>
<location filename="../../common/tvrender/tsimplecolorstyles.cpp" line="1267"/>
<source>Rotation</source>
<translation>Вращение</translation>
</message>
</context>
</TS>
| bsd-3-clause |
kwahsog/clarity | src/main/java/skadistats/clarity/decoder/BitStream.java | 10130 | package skadistats.clarity.decoder;
import com.google.protobuf.ByteString;
import com.google.protobuf.ZeroCopy;
import org.xerial.snappy.Snappy;
import java.io.IOException;
public class BitStream {
private static final int COORD_INTEGER_BITS = 14;
private static final int COORD_FRACTIONAL_BITS = 5;
private static final float COORD_RESOLUTION = (1.0f / (1 << COORD_FRACTIONAL_BITS));
private static final int COORD_INTEGER_BITS_MP = 11;
private static final int COORD_FRACTIONAL_BITS_MP_LOWPRECISION = 3;
private static final int COORD_DENOMINATOR_LOWPRECISION = (1 << COORD_FRACTIONAL_BITS_MP_LOWPRECISION);
private static final float COORD_RESOLUTION_LOWPRECISION = (1.0f / COORD_DENOMINATOR_LOWPRECISION);
private static final int NORMAL_FRACTIONAL_BITS = 11;
private static final float NORMAL_FRACTIONAL_RESOLUTION = (1.0f / ((1 << NORMAL_FRACTIONAL_BITS) - 1));
public static final long[] MASKS = {
0x0L, 0x1L, 0x3L, 0x7L,
0xfL, 0x1fL, 0x3fL, 0x7fL,
0xffL, 0x1ffL, 0x3ffL, 0x7ffL,
0xfffL, 0x1fffL, 0x3fffL, 0x7fffL,
0xffffL, 0x1ffffL, 0x3ffffL, 0x7ffffL,
0xfffffL, 0x1fffffL, 0x3fffffL, 0x7fffffL,
0xffffffL, 0x1ffffffL, 0x3ffffffL, 0x7ffffffL,
0xfffffffL, 0x1fffffffL, 0x3fffffffL, 0x7fffffffL,
0xffffffffL, 0x1ffffffffL, 0x3ffffffffL, 0x7ffffffffL,
0xfffffffffL, 0x1fffffffffL, 0x3fffffffffL, 0x7fffffffffL,
0xffffffffffL, 0x1ffffffffffL, 0x3ffffffffffL, 0x7ffffffffffL,
0xfffffffffffL, 0x1fffffffffffL, 0x3fffffffffffL, 0x7fffffffffffL,
0xffffffffffffL, 0x1ffffffffffffL, 0x3ffffffffffffL, 0x7ffffffffffffL,
0xfffffffffffffL, 0x1fffffffffffffL, 0x3fffffffffffffL, 0x7fffffffffffffL,
0xffffffffffffffL, 0x1ffffffffffffffL, 0x3ffffffffffffffL, 0x7ffffffffffffffL,
0xfffffffffffffffL, 0x1fffffffffffffffL, 0x3fffffffffffffffL, 0x7fffffffffffffffL,
0xffffffffffffffffL
};
final long[] data;
int len;
int pos;
public BitStream(ByteString input) {
len = input.size();
data = new long[(len + 15) >> 3];
pos = 0;
try {
Snappy.arrayCopy(ZeroCopy.extract(input), 0, len, data, 0);
} catch (IOException e) {
throw new RuntimeException(e);
}
len = len * 8; // from now on size in bits
}
public int len() {
return len;
}
public int pos() {
return pos;
}
public int remaining() {
return len - pos;
}
public void skip(int n) {
pos = pos + n;
}
public boolean readBitFlag() {
boolean v = (data[pos >> 6] & (1L << (pos & 63))) != 0L;
pos++;
return v;
}
public long readUBitLong(int n) {
int start = pos >> 6;
int end = (pos + n - 1) >> 6;
int s = pos & 63;
long ret;
if (start == end) {
ret = (data[start] >>> s) & MASKS[n];
} else { // wrap around
ret = ((data[start] >>> s) | (data[end] << (64 - s))) & MASKS[n];
}
pos += n;
return ret;
}
public long readSBitLong(int n) {
long v = readUBitLong(n);
return (v & (1L << (n - 1))) == 0 ? v : v | (MASKS[64 - n] << n);
}
public byte[] readBitsAsByteArray(int n) {
byte[] result = new byte[(n + 7) / 8];
int i = 0;
while (n > 7) {
n -= 8;
result[i] = (byte) readUBitInt(8);
i++;
}
if (n != 0) {
result[i] = (byte) readUBitInt(n);
}
return result;
}
public String readString(int n) {
StringBuilder buf = new StringBuilder();
while (n > 0) {
char c = (char) readUBitInt(8);
if (c == 0) {
break;
}
buf.append(c);
n--;
}
return buf.toString();
}
public long readVarU(int max) {
int m = ((max + 6) / 7) * 7;
int s = 0;
long v = 0L;
long b;
while (true) {
b = readUBitLong(8);
v |= (b & 0x7FL) << s;
s += 7;
if ((b & 0x80L) == 0L || s == m) {
return v;
}
}
}
public long readVarS(int max) {
long v = readVarU(max);
return (v >>> 1) ^ -(v & 1L);
}
public long readVarULong() {
return readVarU(64);
}
public long readVarSLong() {
return readVarS(64);
}
public int readVarUInt() {
return (int) readVarU(32);
}
public int readVarSInt() {
return (int) readVarS(32);
}
public int readUBitInt(int n) {
return (int) readUBitLong(n);
}
public int readSBitInt(int n) {
return (int) readSBitLong(n);
}
public int readUBitVar() {
// Thanks to Robin Dietrich for providing a clean version of this code :-)
// The header looks like this: [XY00001111222233333333333333333333] where everything > 0 is optional.
// The first 2 bits (X and Y) tell us how much (if any) to read other than the 6 initial bits:
// Y set -> read 4
// X set -> read 8
// X + Y set -> read 28
int v = readUBitInt(6);
switch (v & 48) {
case 16:
v = (v & 15) | (readUBitInt(4) << 4);
break;
case 32:
v = (v & 15) | (readUBitInt(8) << 4);
break;
case 48:
v = (v & 15) | (readUBitInt(28) << 4);
break;
}
return v;
}
public int readUBitVarFieldPath() {
if (readBitFlag()) return readUBitInt(2);
if (readBitFlag()) return readUBitInt(4);
if (readBitFlag()) return readUBitInt(10);
if (readBitFlag()) return readUBitInt(17);
return readUBitInt(31);
}
public float readBitCoord() {
boolean i = readBitFlag(); // integer component present?
boolean f = readBitFlag(); // fractional component present?
float v = 0.0f;
if (!(i || f)) return v;
boolean s = readBitFlag();
if (i) v = (float)(readUBitLong(COORD_INTEGER_BITS) + 1);
if (f) v += readUBitLong(COORD_FRACTIONAL_BITS) * COORD_RESOLUTION;
return s ? -v : v;
}
public float readCellCoord(int n, boolean integral, boolean lowPrecision) {
float v = (float)(readUBitLong(n));
if (integral) {
// TODO: something weird is going on here in alice, we might need to adjust the sign?
return v;
}
if (lowPrecision) {
throw new RuntimeException("implement me!");
}
return v + readUBitLong(COORD_FRACTIONAL_BITS) * COORD_RESOLUTION;
}
public float readCoordMp(BitStream stream, boolean integral, boolean lowPrecision) {
int i = 0;
int f = 0;
boolean sign = false;
float value = 0.0f;
boolean inBounds = stream.readBitFlag();
if (integral) {
i = stream.readUBitInt(1);
if (i != 0) {
sign = stream.readBitFlag();
value = stream.readUBitInt(inBounds ? COORD_INTEGER_BITS_MP : COORD_INTEGER_BITS) + 1;
}
} else {
i = stream.readUBitInt(1);
sign = stream.readBitFlag();
if (i != 0) {
i = stream.readUBitInt(inBounds ? COORD_INTEGER_BITS_MP : COORD_INTEGER_BITS) + 1;
}
f = stream.readUBitInt(lowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS);
value = i + ((float) f * (lowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION));
}
return sign ? -value : value;
}
public float readBitAngle(int n) {
return readUBitLong(n) * 360.0f / (1 << n);
}
public float readBitNormal() {
boolean s = readBitFlag();
float v = (float) readUBitLong(NORMAL_FRACTIONAL_BITS) * NORMAL_FRACTIONAL_RESOLUTION;
return s ? -v : v;
}
public float[] read3BitNormal() {
float[] v = new float[3];
boolean x = readBitFlag();
boolean y = readBitFlag();
if (x) v[0] = readBitNormal();
if (y) v[1] = readBitNormal();
boolean s = readBitFlag();
float p = v[0] * v[0] + v[1] * v[1];
if (p < 1.0f) v[2] = (float) Math.sqrt(1.0f - p);
if (s) v[2] = -v[2];
return v;
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append('[');
buf.append(pos);
buf.append('/');
buf.append(len);
buf.append(']');
buf.append(' ');
int prefixLen = buf.length();
int min = Math.max(0, (pos - 32));
int max = Math.min(data.length * 64 - 1, pos + 64);
for (int i = min; i <= max; i++) {
buf.append(peekBit(i));
}
buf.insert(pos - min + prefixLen, '*');
return buf.toString();
}
public String toString(int from, int to) {
StringBuilder buf = new StringBuilder();
for (int i = from; i < to; i++) {
buf.append(peekBit(i));
}
return buf.toString();
}
private int peekBit(int pos) {
int start = pos >> 6;
int s = pos & 63;
long ret = (data[start] >>> s) & MASKS[1];
return (int) ret;
}
}
| bsd-3-clause |
tjouan/producer-core | lib/producer/core/tests/has_dir.rb | 166 | module Producer
module Core
module Tests
class HasDir < Test
def verify
fs.dir? arguments.first
end
end
end
end
end
| bsd-3-clause |
youtube/cobalt | third_party/devtools/front_end/bindings/ResourceScriptMapping.js | 15294 | /*
* Copyright (C) 2012 Google Inc. 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 Google Inc. 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 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.
*/
/**
* @implements {Bindings.DebuggerSourceMapping}
* @unrestricted
*/
export default class ResourceScriptMapping {
/**
* @param {!SDK.DebuggerModel} debuggerModel
* @param {!Workspace.Workspace} workspace
* @param {!Bindings.DebuggerWorkspaceBinding} debuggerWorkspaceBinding
*/
constructor(debuggerModel, workspace, debuggerWorkspaceBinding) {
this._debuggerModel = debuggerModel;
this._workspace = workspace;
this._debuggerWorkspaceBinding = debuggerWorkspaceBinding;
/** @type {!Map.<!Workspace.UISourceCode, !ResourceScriptFile>} */
this._uiSourceCodeToScriptFile = new Map();
/** @type {!Map<string, !Bindings.ContentProviderBasedProject>} */
this._projects = new Map();
/** @type {!Set<!SDK.Script>} */
this._acceptedScripts = new Set();
const runtimeModel = debuggerModel.runtimeModel();
this._eventListeners = [
this._debuggerModel.addEventListener(SDK.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this),
this._debuggerModel.addEventListener(
SDK.DebuggerModel.Events.GlobalObjectCleared, this._globalObjectCleared, this),
runtimeModel.addEventListener(
SDK.RuntimeModel.Events.ExecutionContextDestroyed, this._executionContextDestroyed, this),
];
}
/**
* @param {!SDK.Script} script
* @return {!Bindings.ContentProviderBasedProject}
*/
_project(script) {
const frameId = script[_frameIdSymbol];
const prefix = script.isContentScript() ? 'js:extensions:' : 'js::';
const projectId = prefix + this._debuggerModel.target().id() + ':' + frameId;
let project = this._projects.get(projectId);
if (!project) {
const projectType =
script.isContentScript() ? Workspace.projectTypes.ContentScripts : Workspace.projectTypes.Network;
project = new Bindings.ContentProviderBasedProject(
this._workspace, projectId, projectType, '' /* displayName */, false /* isServiceProject */);
Bindings.NetworkProject.setTargetForProject(project, this._debuggerModel.target());
this._projects.set(projectId, project);
}
return project;
}
/**
* @override
* @param {!SDK.DebuggerModel.Location} rawLocation
* @return {?Workspace.UILocation}
*/
rawLocationToUILocation(rawLocation) {
const script = rawLocation.script();
if (!script) {
return null;
}
const project = this._project(script);
const uiSourceCode = project.uiSourceCodeForURL(script.sourceURL);
if (!uiSourceCode) {
return null;
}
const scriptFile = this._uiSourceCodeToScriptFile.get(uiSourceCode);
if (!scriptFile) {
return null;
}
if ((scriptFile.hasDivergedFromVM() && !scriptFile.isMergingToVM()) || scriptFile.isDivergingFromVM()) {
return null;
}
if (!scriptFile._hasScripts([script])) {
return null;
}
const lineNumber = rawLocation.lineNumber - (script.isInlineScriptWithSourceURL() ? script.lineOffset : 0);
let columnNumber = rawLocation.columnNumber || 0;
if (script.isInlineScriptWithSourceURL() && !lineNumber && columnNumber) {
columnNumber -= script.columnOffset;
}
return uiSourceCode.uiLocation(lineNumber, columnNumber);
}
/**
* @override
* @param {!Workspace.UISourceCode} uiSourceCode
* @param {number} lineNumber
* @param {number} columnNumber
* @return {!Array<!SDK.DebuggerModel.Location>}
*/
uiLocationToRawLocations(uiSourceCode, lineNumber, columnNumber) {
const scriptFile = this._uiSourceCodeToScriptFile.get(uiSourceCode);
if (!scriptFile) {
return [];
}
const script = scriptFile._script;
if (script.isInlineScriptWithSourceURL()) {
return [this._debuggerModel.createRawLocation(
script, lineNumber + script.lineOffset, lineNumber ? columnNumber : columnNumber + script.columnOffset)];
}
return [this._debuggerModel.createRawLocation(script, lineNumber, columnNumber)];
}
/**
* @param {!SDK.Script} script
* @return {boolean}
*/
_acceptsScript(script) {
if (!script.sourceURL || script.isLiveEdit() || (script.isInlineScript() && !script.hasSourceURL)) {
return false;
}
// Filter out embedder injected content scripts.
if (script.isContentScript() && !script.hasSourceURL) {
const parsedURL = new Common.ParsedURL(script.sourceURL);
if (!parsedURL.isValid) {
return false;
}
}
return true;
}
/**
* @param {!Common.Event} event
*/
_parsedScriptSource(event) {
const script = /** @type {!SDK.Script} */ (event.data);
if (!this._acceptsScript(script)) {
return;
}
this._acceptedScripts.add(script);
const originalContentProvider = script.originalContentProvider();
const frameId = Bindings.frameIdForScript(script);
script[_frameIdSymbol] = frameId;
const url = script.sourceURL;
const project = this._project(script);
// Remove previous UISourceCode, if any
const oldUISourceCode = project.uiSourceCodeForURL(url);
if (oldUISourceCode) {
const scriptFile = this._uiSourceCodeToScriptFile.get(oldUISourceCode);
this._removeScript(scriptFile._script);
}
// Create UISourceCode.
const uiSourceCode = project.createUISourceCode(url, originalContentProvider.contentType());
Bindings.NetworkProject.setInitialFrameAttribution(uiSourceCode, frameId);
const metadata = Bindings.metadataForURL(this._debuggerModel.target(), frameId, url);
// Bind UISourceCode to scripts.
const scriptFile = new ResourceScriptFile(this, uiSourceCode, [script]);
this._uiSourceCodeToScriptFile.set(uiSourceCode, scriptFile);
project.addUISourceCodeWithProvider(uiSourceCode, originalContentProvider, metadata, 'text/javascript');
this._debuggerWorkspaceBinding.updateLocations(script);
}
/**
* @param {!Workspace.UISourceCode} uiSourceCode
* @return {?ResourceScriptFile}
*/
scriptFile(uiSourceCode) {
return this._uiSourceCodeToScriptFile.get(uiSourceCode) || null;
}
/**
* @param {!SDK.Script} script
*/
_removeScript(script) {
if (!this._acceptedScripts.has(script)) {
return;
}
this._acceptedScripts.delete(script);
const project = this._project(script);
const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (project.uiSourceCodeForURL(script.sourceURL));
const scriptFile = this._uiSourceCodeToScriptFile.get(uiSourceCode);
scriptFile.dispose();
this._uiSourceCodeToScriptFile.delete(uiSourceCode);
project.removeFile(script.sourceURL);
this._debuggerWorkspaceBinding.updateLocations(script);
}
/**
* @param {!Common.Event} event
*/
_executionContextDestroyed(event) {
const executionContext = /** @type {!SDK.ExecutionContext} */ (event.data);
const scripts = this._debuggerModel.scriptsForExecutionContext(executionContext);
for (const script of scripts) {
this._removeScript(script);
}
}
/**
* @param {!Common.Event} event
*/
_globalObjectCleared(event) {
const scripts = Array.from(this._acceptedScripts);
for (const script of scripts) {
this._removeScript(script);
}
}
resetForTest() {
const scripts = Array.from(this._acceptedScripts);
for (const script of scripts) {
this._removeScript(script);
}
}
dispose() {
Common.EventTarget.removeEventListeners(this._eventListeners);
const scripts = Array.from(this._acceptedScripts);
for (const script of scripts) {
this._removeScript(script);
}
for (const project of this._projects.values()) {
project.removeProject();
}
this._projects.clear();
}
}
/**
* @unrestricted
*/
export class ResourceScriptFile extends Common.Object {
/**
* @param {!ResourceScriptMapping} resourceScriptMapping
* @param {!Workspace.UISourceCode} uiSourceCode
* @param {!Array.<!SDK.Script>} scripts
*/
constructor(resourceScriptMapping, uiSourceCode, scripts) {
super();
console.assert(scripts.length);
this._resourceScriptMapping = resourceScriptMapping;
this._uiSourceCode = uiSourceCode;
if (this._uiSourceCode.contentType().isScript()) {
this._script = scripts[scripts.length - 1];
}
this._uiSourceCode.addEventListener(
Workspace.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
this._uiSourceCode.addEventListener(
Workspace.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this);
}
/**
* @param {!Array.<!SDK.Script>} scripts
* @return {boolean}
*/
_hasScripts(scripts) {
return this._script && this._script === scripts[0];
}
/**
* @return {boolean}
*/
_isDiverged() {
if (this._uiSourceCode.isDirty()) {
return true;
}
if (!this._script) {
return false;
}
if (typeof this._scriptSource === 'undefined') {
return false;
}
const workingCopy = this._uiSourceCode.workingCopy();
if (!workingCopy) {
return false;
}
// Match ignoring sourceURL.
if (!workingCopy.startsWith(this._scriptSource.trimRight())) {
return true;
}
const suffix = this._uiSourceCode.workingCopy().substr(this._scriptSource.length);
return !!suffix.length && !suffix.match(SDK.Script.sourceURLRegex);
}
/**
* @param {!Common.Event} event
*/
_workingCopyChanged(event) {
this._update();
}
/**
* @param {!Common.Event} event
*/
_workingCopyCommitted(event) {
if (this._uiSourceCode.project().canSetFileContent()) {
return;
}
if (!this._script) {
return;
}
const debuggerModel = this._resourceScriptMapping._debuggerModel;
const breakpoints = Bindings.breakpointManager.breakpointLocationsForUISourceCode(this._uiSourceCode)
.map(breakpointLocation => breakpointLocation.breakpoint);
const source = this._uiSourceCode.workingCopy();
debuggerModel.setScriptSource(this._script.scriptId, source, scriptSourceWasSet.bind(this));
/**
* @param {?string} error
* @param {!Protocol.Runtime.ExceptionDetails=} exceptionDetails
* @this {ResourceScriptFile}
*/
async function scriptSourceWasSet(error, exceptionDetails) {
if (!error && !exceptionDetails) {
this._scriptSource = source;
}
this._update();
if (!error && !exceptionDetails) {
// Live edit can cause breakpoints to be in the wrong position, or to be lost altogether.
// If any breakpoints were in the pre-live edit script, they need to be re-added.
breakpoints.map(breakpoint => breakpoint.refreshInDebugger());
return;
}
if (!exceptionDetails) {
Common.console.addMessage(Common.UIString('LiveEdit failed: %s', error), Common.Console.MessageLevel.Warning);
return;
}
const messageText = Common.UIString('LiveEdit compile failed: %s', exceptionDetails.text);
this._uiSourceCode.addLineMessage(
Workspace.UISourceCode.Message.Level.Error, messageText, exceptionDetails.lineNumber,
exceptionDetails.columnNumber);
}
}
_update() {
if (this._isDiverged() && !this._hasDivergedFromVM) {
this._divergeFromVM();
} else if (!this._isDiverged() && this._hasDivergedFromVM) {
this._mergeToVM();
}
}
_divergeFromVM() {
this._isDivergingFromVM = true;
this._resourceScriptMapping._debuggerWorkspaceBinding.updateLocations(this._script);
delete this._isDivergingFromVM;
this._hasDivergedFromVM = true;
this.dispatchEventToListeners(ResourceScriptFile.Events.DidDivergeFromVM, this._uiSourceCode);
}
_mergeToVM() {
delete this._hasDivergedFromVM;
this._isMergingToVM = true;
this._resourceScriptMapping._debuggerWorkspaceBinding.updateLocations(this._script);
delete this._isMergingToVM;
this.dispatchEventToListeners(ResourceScriptFile.Events.DidMergeToVM, this._uiSourceCode);
}
/**
* @return {boolean}
*/
hasDivergedFromVM() {
return this._hasDivergedFromVM;
}
/**
* @return {boolean}
*/
isDivergingFromVM() {
return this._isDivergingFromVM;
}
/**
* @return {boolean}
*/
isMergingToVM() {
return this._isMergingToVM;
}
checkMapping() {
if (!this._script || typeof this._scriptSource !== 'undefined') {
this._mappingCheckedForTest();
return;
}
this._script.requestContent().then(deferredContent => {
this._scriptSource = deferredContent.content;
this._update();
this._mappingCheckedForTest();
});
}
_mappingCheckedForTest() {
}
dispose() {
this._uiSourceCode.removeEventListener(
Workspace.UISourceCode.Events.WorkingCopyChanged, this._workingCopyChanged, this);
this._uiSourceCode.removeEventListener(
Workspace.UISourceCode.Events.WorkingCopyCommitted, this._workingCopyCommitted, this);
}
/**
* @param {string} sourceMapURL
*/
addSourceMapURL(sourceMapURL) {
if (!this._script) {
return;
}
this._script.debuggerModel.setSourceMapURL(this._script, sourceMapURL);
}
/**
* @return {boolean}
*/
hasSourceMapURL() {
return this._script && !!this._script.sourceMapURL;
}
}
const _frameIdSymbol = Symbol('frameid');
/** @enum {symbol} */
ResourceScriptFile.Events = {
DidMergeToVM: Symbol('DidMergeToVM'),
DidDivergeFromVM: Symbol('DidDivergeFromVM'),
};
/* Legacy exported object */
self.Bindings = self.Bindings || {};
/* Legacy exported object */
Bindings = Bindings || {};
/** @constructor */
Bindings.ResourceScriptMapping = ResourceScriptMapping;
/** @constructor */
Bindings.ResourceScriptFile = ResourceScriptFile;
| bsd-3-clause |
treefrogframework/treefrog-framework | src/tinternetmessageheader.cpp | 7443 | /* Copyright (c) 2011-2019, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include "thttputility.h"
#include "tsystemglobal.h"
#include <TInternetMessageHeader>
using namespace Tf;
/*!
\class TInternetMessageHeader
\brief The TInternetMessageHeader class contains internet message headers.
*/
/*!
\fn TInternetMessageHeader::TInternetMessageHeader()
Constructs an empty Internet message header.
*/
/*!
Copy constructor.
*/
TInternetMessageHeader::TInternetMessageHeader(const TInternetMessageHeader &other) :
_headerPairList(other._headerPairList)
{
}
/*!
Constructs an Internet message header by parsing \a str.
*/
TInternetMessageHeader::TInternetMessageHeader(const QByteArray &str)
{
parse(str);
}
/*!
Returns true if the Internet message header has an entry with the given
\a key; otherwise returns false.
*/
bool TInternetMessageHeader::hasRawHeader(const QByteArray &key) const
{
return !rawHeader(key).isNull();
}
/*!
Returns the raw value for the entry with the given \a key. If no entry
has this key, an empty byte array is returned.
*/
QByteArray TInternetMessageHeader::rawHeader(const QByteArray &key) const
{
for (const auto &p : _headerPairList) {
if (qstricmp(p.first.constData(), key.constData()) == 0) {
return p.second;
}
}
return QByteArray();
}
/*!
Returns a list of all raw headers.
*/
QByteArrayList TInternetMessageHeader::rawHeaderList() const
{
QByteArrayList list;
list.reserve(_headerPairList.size());
for (const auto &p : _headerPairList) {
list << p.first;
}
return list;
}
/*!
Sets the raw header \a key to be of value \a value.
If \a key was previously set, it is overridden.
*/
void TInternetMessageHeader::setRawHeader(const QByteArray &key, const QByteArray &value)
{
if (!hasRawHeader(key)) {
_headerPairList << RawHeaderPair(key, value);
return;
}
QByteArray val = value;
for (QMutableListIterator<RawHeaderPair> it(_headerPairList); it.hasNext();) {
RawHeaderPair &p = it.next();
if (qstricmp(p.first.constData(), key.constData()) == 0) {
if (val.isNull()) {
it.remove();
} else {
p.second = val;
val.clear();
}
}
}
}
/*!
Sets the raw header \a key to be of value \a value.
If \a key was previously set, it is added multiply.
*/
void TInternetMessageHeader::addRawHeader(const QByteArray &key, const QByteArray &value)
{
if (key.isEmpty() || value.isNull())
return;
_headerPairList << RawHeaderPair(key, value);
}
/*!
Returns the value of the header field content-type.
*/
QByteArray TInternetMessageHeader::contentType() const
{
return rawHeader(QByteArrayLiteral("Content-Type"));
}
/*!
Sets the value of the header field content-type to \a type.
*/
void TInternetMessageHeader::setContentType(const QByteArray &type)
{
setRawHeader(QByteArrayLiteral("Content-Type"), type);
}
/*!
Returns the value of the header field content-length.
*/
qint64 TInternetMessageHeader::contentLength() const
{
if (_contentLength < 0) {
_contentLength = rawHeader(QByteArrayLiteral("Content-Length")).toLongLong();
}
return _contentLength;
}
/*!
Sets the value of the header field content-length to \a len.
*/
void TInternetMessageHeader::setContentLength(qint64 len)
{
setRawHeader(QByteArrayLiteral("Content-Length"), QByteArray::number(len));
_contentLength = len;
}
/*!
Returns the value of the header field Date.
*/
QByteArray TInternetMessageHeader::date() const
{
return rawHeader(QByteArrayLiteral("Date"));
}
/*!
Sets the value of the header field Date to \a date.
*/
void TInternetMessageHeader::setDate(const QByteArray &date)
{
setRawHeader(QByteArrayLiteral("Date"), date);
}
/*!
Sets the value of the header field Date to the current date/time.
*/
void TInternetMessageHeader::setCurrentDate()
{
setDate(THttpUtility::getUTCTimeString());
}
/*!
Sets the value of the header field Date to \a localTime
as the local time on the computer.
*/
void TInternetMessageHeader::setDate(const QDateTime &dateTime)
{
setRawHeader(QByteArrayLiteral("Date"), THttpUtility::toHttpDateTimeString(dateTime));
}
/*!
Sets the value of the header field Date to \a utc as Coordinated
Universal Time.
*/
// void TInternetMessageHeader::setDateUTC(const QDateTime &utc)
// {
// setRawHeader("Date", THttpUtility::toHttpDateTimeUTCString(utc));
// }
/*!
Returns a byte array representation of the Internet message header.
*/
QByteArray TInternetMessageHeader::toByteArray() const
{
QByteArray res;
res.reserve(_headerPairList.size() * 64);
for (const auto &p : _headerPairList) {
res += p.first;
res += ": ";
res += p.second;
res += CRLF;
}
res += CRLF;
return res;
}
/*!
Parses the \a header. This function is for internal use only.
*/
void TInternetMessageHeader::parse(const QByteArray &header)
{
QByteArray field, value;
int i = 0;
int headerlen;
value.reserve(255);
headerlen = header.indexOf(CRLFCRLF);
if (headerlen < 0)
headerlen = header.length();
while (i < headerlen) {
int j = header.indexOf(':', i); // field-name
if (j < 0)
break;
field = header.mid(i, j - i).trimmed();
// any number of LWS is allowed before and after the value
++j;
value.resize(0);
do {
i = header.indexOf('\n', j);
if (i < 0) {
i = header.length();
}
if (!value.isEmpty())
value += ' ';
value += header.mid(j, i - j).trimmed();
j = ++i;
} while (i < headerlen && (header.at(i) == ' ' || header.at(i) == '\t'));
_headerPairList << qMakePair(field, value);
}
}
/*!
Removes all the entries with the key \a key from the HTTP header.
*/
void TInternetMessageHeader::removeAllRawHeaders(const QByteArray &key)
{
for (QMutableListIterator<RawHeaderPair> it(_headerPairList); it.hasNext();) {
RawHeaderPair &p = it.next();
if (qstricmp(p.first.constData(), key.constData()) == 0) {
it.remove();
}
}
}
/*!
Removes the entries with the key \a key from the HTTP header.
*/
void TInternetMessageHeader::removeRawHeader(const QByteArray &key)
{
for (QMutableListIterator<RawHeaderPair> it(_headerPairList); it.hasNext();) {
RawHeaderPair &p = it.next();
if (qstricmp(p.first.constData(), key.constData()) == 0) {
it.remove();
break;
}
}
}
/*!
Returns true if the Internet message header is empty; otherwise
returns false.
*/
bool TInternetMessageHeader::isEmpty() const
{
return _headerPairList.isEmpty();
}
/*!
Removes all the entries from the Internet message header.
*/
void TInternetMessageHeader::clear()
{
_headerPairList.clear();
_contentLength = -1;
}
/*!
Assigns \a other to this internet message header and returns a reference
to this header.
*/
TInternetMessageHeader &TInternetMessageHeader::operator=(const TInternetMessageHeader &other)
{
_headerPairList = other._headerPairList;
return *this;
}
| bsd-3-clause |
unt-libraries/catalog-api | django/sierra/manage.py | 374 | #!/usr/bin/env python
import os
import sys
import dotenv
from django.core.management import execute_from_command_line
if __name__ == '__main__':
# Use dotenv to load env variables from a .env file
dotenv.load_dotenv(os.path.join(os.path.dirname(__file__), 'sierra',
'settings', '.env'))
execute_from_command_line(sys.argv)
| bsd-3-clause |
MRPT/mrpt | samples/comms_http_client/test.cpp | 1777 | /* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2022, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
/** \example comms_http_client/test.cpp */
//! [example-http-get]
#include <mrpt/comms/net_utils.h>
#include <mrpt/core/exceptions.h>
#include <iostream>
using namespace mrpt;
using namespace mrpt::comms;
using namespace mrpt::comms::net;
std::string url = "http://www.google.es/";
void Test_HTTP_get()
{
std::string content;
mrpt::comms::net::HttpRequestOptions httpOptions;
mrpt::comms::net::HttpRequestOutput httpOut;
std::cout << "Retrieving " << url << "..." << std::endl;
http_errorcode ret = http_get(url, content, httpOptions, httpOut);
if (ret != net::http_errorcode::Ok)
{
std::cout << " Error: " << httpOut.errormsg << std::endl;
return;
}
string typ = httpOut.out_headers.count("Content-Type")
? httpOut.out_headers.at("Content-Type")
: string("???");
std::cout << "Ok: " << content.size() << " bytes of type: " << typ
<< std::endl;
}
//! [example-http-get]
int main(int argc, char** argv)
{
try
{
if (argc > 1) url = string(argv[1]);
Test_HTTP_get();
return 0;
}
catch (const std::exception& e)
{
std::cerr << "MRPT error: " << mrpt::exception_to_str(e) << std::endl;
return -1;
}
}
| bsd-3-clause |