code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<html>
<head><title>Test</title></head>
<body><p>Test</p></body>
</html>
|
dev9com/mvnwatcher
|
src/test/resources/sample-project/src/main/resources/templates/index.html
|
HTML
|
apache-2.0
| 73
|
/**
* Copyright 2014 Emmanuel Benazera beniz@droidnik.fr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CONTINUOUSTRANSITION_H
#define CONTINUOUSTRANSITION_H
#include "BspTree.h"
#include "NormalDiscreteDistribution.h"
#include "discretizationTypes.h"
#include "MDDiscreteDistribution.h"
#include "ContinuousOutcome.h"
#include "PiecewiseConstantValueFunction.h"
#include "PiecewiseLinearValueFunction.h"
#include <iostream>
namespace hmdp_base
{
/**
* \class ContinuousTransition
* \brief continuous transition as a bsp tree. Each sub tree is represented as
* a ContinuousTransition object.
*/
class ContinuousTransition : public BspTree
{
public:
/**
* \brief constructor
* @param sdim the continuous space dimension.
*/
ContinuousTransition (const int &sdim);
/**
* \brief constructor
* @param sdim the continuous space dimension,
* @param d the partitioning dimension,
* @param pos the partitioning position.
*/
ContinuousTransition (const int &sdim, const int &d, const double &pos);
/**
* \brief constructor
* @param dimension the number of transition tiles in the continuous space,
* @param sdim the continuous space dimension.
*/
ContinuousTransition (const int &dimension, const int &sdim);
/**
* \brief constructor
* @param dimension the number of transition tiles in the continuous space,
* @param sdim the continuous space dimension,
* @param d the partitioning dimension,
* @param pos the partitioning position.
*/
ContinuousTransition (const int &dimension, const int &sdim,
const int &d, const double &pos);
public:
/**
* \brief constructor
* @param dimension the number of transition tiles in the continuous space.
* @param sdim the continuous space dimension.
* @param lowPos array of the low coordinates of the corner points of the tiles.
* @param highPos array of the high coordinates of the corner points of the tiles.
* @param low the domain lower bounds.
* @param high the domain upper bounds.
* @param epsilon threshold for the discretization, for each tile, for each dimension.
* @param intervals interval for the discretization, for each tile, for each dimension
* !!NOTE!!: If dt type is DISCRETIZATION_WRT_POINTS, points are stored in place
* of intervals.
* @param dt type of discretization: DISCRETIZATION_WRT_INTERVAL or
* DISCRETIZATION_WRT_THRESHOLD or
* DISCRETIZATION_WRT_POINTS.
* @param means probability distribution mean, for each tile, for each dimension.
* @param sds probability distribution standard deviation, for each tile, for each dimension.
* @param relative relative/absolute transition flag, for each tile, for each dimension.
* @param distrib distribution type: GAUSSIAN or UNIFORM, for each tile, for each dimension.
*/
/* TODO: uniform distribution */
ContinuousTransition (const int &dim, const int &sdim, const discretizationType dt,
double **lowPos, double **highPos,
double *low, double *high,
const double **epsilon, const double **intervals,
const double **means, const double **sds, bool **relative,
const discreteDistributionType **distrib);
/**
* \brief Copy constructor
*/
ContinuousTransition (const ContinuousTransition &ct);
protected:
/**
* \brief copy constructor (from an object of the father's class type)
* @param number of transition tiles in the continuous space.
* @param bt a bsp tree.
*/
ContinuousTransition (const int &dimension, const BspTree &bt);
public:
/**
* \brief Destructor.
*/
virtual ~ContinuousTransition ();
private:
void selfReferenceTiles (ContinuousTransition *ct, ContinuousTransition **ptrref);
protected:
/* virtual functions */
void leafDataIntersectInit (const BspTree &bt, const BspTree &btr,
double *low, double *high);
void transferData (const BspTree &bt);
public:
/* setters */
/**
* \brief leaf distribution setter
* @param jdd a multi-dimension discrete distribution object.
*/
void setLeafDistribution (MDDiscreteDistribution *jdd) { m_jdd = jdd; }
/**
* \brief leaf cached bsp trees for the probability distribution (shifted pieces) (Internal).
* @param cos an array of ContinuousOutcomes pointers, i.e bsp trees.
*/
void setLeafContinuousOutcomes (ContinuousOutcome **cos) { m_shiftedProbabilisticOutcomes = cos; }
void setLeafProjectedContinuousOutcomes (ContinuousOutcome **cos)
{ m_projectedProbabilisticOutcomes = cos; }
/**
* \brief leaf number of continuous outcomes setter.
* @param n number of outcomes (pieces of the discretized leaf probability distribution).
*/
void setNContinuousOutcomes (const int &n) { m_numberContinuousOutcomes = n; }
void setNProjectedContinuousOutcomes (const int &n) { m_numberProjectedContinuousOutcomes = n; }
void setNTile (const int &tile) { m_nTile = tile; }
/* accessors */
/**
* \brief tiling dimension accessor
* @return the number of transition tiles in the continuous space.
*/
int getTilingDimension () const { return m_tilingDimension; }
/**
* \brief leaf distribution accessor
* @return a multi-dimensional discrete distribution object.
*/
MDDiscreteDistribution* getLeafDistribution () const
{ if (isLeaf () && m_jdd) return m_jdd;
else return NULL; }
/**
* \brief transition relative/absolute flag accessor
* @param tdim transition tile number
* @param cdim continuous dimension
* @return true if transition is relative in the tile for the dimension, no if absolute.
*/
bool getRelative (int tdim, int cdim) const { return m_relative[tdim][cdim]; }
ContinuousOutcome** getContinuousOutcomes () const { return m_shiftedProbabilisticOutcomes; }
ContinuousOutcome** getProjectedContinuousOutcomes () const { return m_projectedProbabilisticOutcomes; }
/**
* \brief cache of continuous outcomes accessor.
* @param pos position of a continuous outcome.
* @return a continuous outcome (bsp tree).
*/
ContinuousOutcome* getContinuousOutcome (const int &pos) const
{ return m_shiftedProbabilisticOutcomes[pos]; }
ContinuousOutcome* getProjectedContinuousOutcome (const int &pos) const
{ return m_projectedProbabilisticOutcomes[pos]; }
/**
* \brief number of continuous outcomes accessor.
* @param tile tile index.
* @return number of continuous outcomes for this transition tile.
*/
int getNContinuousOutcomes () const { return m_numberContinuousOutcomes; }
int getNProjectedContinuousOutcomes () const { return m_numberProjectedContinuousOutcomes; }
/**
* \brief tile number accessor.
* @return the tile number (leaf only, -1 otherwise).
*/
int getNTile () const { return m_nTile; }
/**
* \brief quick tile pointer accessor.
* @param tile tile number.
* @return tile pointer for this tile number.
*/
ContinuousTransition* getPtrTile (const int &tile) const
{ return m_ptrToTiles[tile]; }
/**
* \brief accessor to the continuous transition tree converted to a pwc vf.
* This is to speed up 'back up' operations.
* @return a pointer to a pwc vf bsp tree.
*/
PiecewiseConstantValueFunction* getPtrPwcVF () const { return m_ctpwcVF; }
/**
* \brief accessor to the continuous transition tree converted to a pwl vf.
* This is to speed up 'back up' operations.
* @return a pointer to a pwl vf bsp tree.
*/
PiecewiseLinearValueFunction* getPtrPwlVF () const { return m_ctpwlVF; }
ContinuousStateDistribution* getPtrCSD () const { return m_ctCSD; }
void hasZeroConsumption (bool &isNullOutcome);
/* printing */
void print (std::ostream &out, double *low, double *high);
private:
/**
* \brief relative array accessor
* @return array of relative/absolute flags (for all tiles/dimensions).
*/
bool** getRelative () const { return m_relative; }
private:
int m_tilingDimension; /**< number of transition tiles (root node only, 0 otherwise). */
MDDiscreteDistribution *m_jdd; /**< joint discrete probability distribution,
if the tree is a leave */
bool **m_relative; /**< relative/absolute transition flag, per dimension, per tile. */
ContinuousOutcome **m_shiftedProbabilisticOutcomes; /**< cache of shifted outcome of speeding up
the backups (a pointer per discrete point). */
ContinuousOutcome **m_projectedProbabilisticOutcomes; /**< cache of forward projection of
outcomes, for speeding up the front ups
(convolutions). */
int m_numberContinuousOutcomes; /**< number of continuous outcomes, in leaf. */
int m_numberProjectedContinuousOutcomes; /**< number of projected continuous outcomes. */
ContinuousTransition **m_ptrToTiles; /**< root node stores pointers to the leaves that
correspond to the tiles. */
int m_nTile; /**< tile index (in leaf). */
PiecewiseConstantValueFunction *m_ctpwcVF; /**< root caches the ct structure as a value function (for backup). */
PiecewiseLinearValueFunction *m_ctpwlVF;
ContinuousStateDistribution *m_ctCSD; /**< tiles cache for frontup. */
};
} /* end of namespace */
#endif
|
beniz/hmdp
|
src/base/ContinuousTransition.h
|
C
|
apache-2.0
| 9,787
|
// Copyright 2015 Patrick Putnam
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CLOTHO_POPULATION_SPACE_HPP_
#define CLOTHO_POPULATION_SPACE_HPP_
#include <memory>
#include <vector>
#include <map>
#include "clotho/utility/bit_helper.hpp"
namespace clotho {
namespace genetics {
template < class WeightType >
class genetic_weight {
public:
typedef genetic_weight< WeightType > self_type;
typedef WeightType weight_type;
typedef std::vector< weight_type > weight_vector;
typedef typename weight_vector::iterator weight_iterator;
typedef typename weight_vector::const_iterator const_weight_iterator;
genetic_weight( unsigned int N = 1 ) {
m_weights.reserve( N );
}
genetic_weight( const weight_vector & weights ) :
m_weights( weights )
{}
genetic_weight( const self_type & other ) :
m_weights( other.m_weights )
{}
const weight_vector & getWeights() const {
return m_weights;
}
void update( const_weight_iterator first, const_weight_iterator last ) {
if( m_weights.empty() ) {
while( first != last ) {
m_weights.push_back( *first++ );
}
} else {
unsigned int i = 0;
while( i < m_weights.size() && first != last ) {
m_weights[ i++ ] += *first++;
}
}
}
weight_iterator begin_weight() {
return m_weights.begin();
}
weight_iterator end_weight() {
return m_weights.end();
}
const_weight_iterator begin_weight() const {
return m_weights.begin();
}
const_weight_iterator end_weight() const {
return m_weights.end();
}
virtual ~genetic_weight() {}
protected:
weight_vector m_weights;
};
template < class BlockType >
class genetic_sequence {
public:
typedef genetic_sequence< BlockType > self_type;
typedef BlockType block_type;
typedef std::vector< block_type > sequence_vector;
typedef typename sequence_vector::iterator sequence_iterator;
typedef typename sequence_vector::const_iterator const_sequence_iterator;
typedef clotho::utility::BitHelper< block_type > bit_helper_type;
genetic_sequence( unsigned int N = 1 ) {
m_data.reserve( N );
}
genetic_sequence( const sequence_vector & seq ) :
m_data( seq )
{}
genetic_sequence( const self_type & other ) :
m_data( other.m_data )
{}
static unsigned int calculateBlockCount( unsigned int M ) {
return bit_helper_type::padded_block_count( M );
}
const sequence_vector & getSequence() const {
return m_data;
}
void append_sequence( const block_type & b ) {
m_data.push_back( b );
}
void set( unsigned int offset ) {
unsigned int block_offset = rescale_to_offset( offset );
m_data[ block_offset ] |= bit_helper_type::bit_offset( offset );
}
void unset( unsigned int offset ) {
unsigned int block_offset = rescale_to_offset(offset);
m_data[ block_offset ] &= ~( bit_helper_type::bit_offset( offset ) );
}
void remove_fixed( unsigned int bidx, block_type mask ) {
#ifdef DEBUGGING
assert( m_data[ bidx ] & ~(mask) );
#endif // DEBUGGING
if( bidx < m_data.size() )
m_data[ bidx ] &= mask;
}
bool isSet( unsigned int idx ) {
unsigned int b_idx = idx / bit_helper_type::BITS_PER_BLOCK;
block_type mask = ((block_type) 1 << (idx % bit_helper_type::BITS_PER_BLOCK));
return (m_data[ b_idx ] & mask );
}
bool isEmpty() const {
return m_data.empty();
}
unsigned int sequence_block_length() const {
return m_data.size();
}
sequence_iterator begin_sequence() {
return m_data.begin();
}
sequence_iterator end_sequence() {
return m_data.end();
}
const_sequence_iterator begin_sequence() const {
return m_data.begin();
}
const_sequence_iterator end_sequence() const {
return m_data.end();
}
virtual ~genetic_sequence() {}
protected:
inline unsigned int rescale_to_offset( unsigned int offset ) {
unsigned int block_offset = offset / bit_helper_type::BITS_PER_BLOCK;
while( m_data.size() <= block_offset ) {
//m_data.push_back( bit_helper_type::ALL_UNSET );
m_data.push_back( 0 );
}
return block_offset;
}
sequence_vector m_data;
};
template < class BlockType, class WeightType >
class haploid_genome : public genetic_sequence< BlockType >, public genetic_weight< WeightType > {
public:
typedef haploid_genome< BlockType, WeightType > self_type;
typedef genetic_sequence< BlockType > sequence_type;
typedef genetic_weight< WeightType > weight_type;
haploid_genome( unsigned int N, unsigned int M) :
sequence_type( N )
, weight_type( M )
, m_modifiable(true)
{}
haploid_genome( const self_type & other ) :
sequence_type( other.getSequence() )
, weight_type( other.getWeights() )
, m_modifiable( true )
{}
bool isModifiable() const {
return m_modifiable;
}
void finalize() {
m_modifiable = false;
}
virtual ~haploid_genome() {}
protected:
bool m_modifiable;
};
template < class BlockType, class WeightType >
class population_space {
public:
typedef haploid_genome< BlockType, WeightType > base_genome_type;
typedef typename base_genome_type::sequence_type::sequence_vector sequence_vector;
typedef typename sequence_vector::iterator sequence_iterator;
typedef typename sequence_vector::const_iterator const_sequence_iterator;
typedef std::shared_ptr< base_genome_type > genome_type;
typedef std::pair< genome_type, genome_type > individual_type;
typedef std::vector< individual_type > population_type;
typedef typename population_type::iterator individual_iterator;
typedef typename population_type::const_iterator const_individual_iterator;
typedef std::map< genome_type, unsigned int > haploid_genomes;
// typedef std::map< base_genome_type *, unsigned int > haploid_genomes;
typedef typename haploid_genomes::iterator genome_iterator;
typedef typename haploid_genomes::const_iterator const_genome_iterator;
typedef typename base_genome_type::weight_type::weight_type weight_type;
population_space() :
m_max_alleles(0)
, m_max_blocks(0)
, m_max_traits(0)
{}
genome_type create_sequence( ) {
return genome_type( new base_genome_type( m_max_blocks, m_max_traits ) );
}
typename base_genome_type::weight_type::weight_vector create_weight_vector( const weight_type default_value = 0.0 ) {
return typename base_genome_type::weight_type::weight_vector( m_max_traits, default_value);
}
size_t individual_count() const {
return m_pop.size();
}
size_t haploid_genome_count() const {
return 2 * m_pop.size();
}
size_t haploid_genome_pointer_count() const {
return m_genomes.size();
}
individual_type & getIndividual( size_t offset ) {
return m_pop[ offset ];
}
void setIndividual( size_t offset, individual_type & ind ) {
if( offset < m_pop.size() ) {
m_pop[ offset ] = ind;
} else {
do {
m_pop.push_back( ind );
} while( m_pop.size() <= offset );
}
}
void setIndividual( size_t offset, genome_type a, genome_type b ) {
individual_type ind = std::make_pair( a, b );
setIndividual( offset, ind );
}
individual_iterator begin_individual() {
return m_pop.begin();
}
individual_iterator end_individual() {
return m_pop.end();
}
const_individual_iterator begin_individual() const {
return m_pop.begin();
}
const_individual_iterator end_individual() const {
return m_pop.end();
}
genome_iterator begin_genomes() {
return m_genomes.begin();
}
genome_iterator end_genomes() {
return m_genomes.end();
}
const_genome_iterator begin_genomes() const {
return m_genomes.begin();
}
const_genome_iterator end_genomes() const {
return m_genomes.end();
}
void mutate( unsigned int seq_idx, unsigned int all_idx ) {
unsigned int ind_idx = seq_idx / 2;
#ifdef DEBUGGING
BOOST_LOG_TRIVIAL(debug) << "Mutate Individual: " << ind_idx << " [" << seq_idx << " vs " << m_pop.size() << "]";
#endif // DEBUGGING
assert( ind_idx < m_pop.size() );
if( seq_idx % 2 ) {
if( !m_pop[ ind_idx ].second ) {
m_pop[ ind_idx ].second = create_sequence();
} else if( !m_pop[ind_idx].second->isModifiable() ) {
m_pop[ ind_idx ].second = genome_type( new base_genome_type( *(m_pop[ ind_idx ].second) ) );
}
m_pop[ ind_idx ].second->set( all_idx );
} else {
if( !m_pop[ ind_idx ].first ) {
m_pop[ ind_idx ].first = create_sequence();
} else if( !m_pop[ind_idx].first->isModifiable() ) {
m_pop[ ind_idx ].first = genome_type( new base_genome_type( *(m_pop[ ind_idx ].first) ) );
}
m_pop[ ind_idx ].first->set( all_idx );
}
}
void remove_fixed_allele( unsigned int all_idx ) {
genome_iterator first = m_genomes.begin(), last = m_genomes.end();
unsigned int bidx = all_idx / base_genome_type::sequence_type::bit_helper_type::BITS_PER_BLOCK;
typename base_genome_type::sequence_type::block_type mask = ~(base_genome_type::sequence_type::bit_helper_type::bit_offset( all_idx ));
while( first != last ) {
if(first->first) first->first->remove_fixed( bidx, mask );
++first;
}
}
bool freeColumn( unsigned int idx ) {
genome_iterator first = m_genomes.begin(), last = m_genomes.end();
bool res = true;
while( res && first != last ) {
if( !first->first ) {
res = first->first->isSet( idx );
}
++first;
}
return res;
}
void grow( unsigned int I, unsigned int A ) {
clear();
std::cerr << "Reserving: " << I << std::endl;
m_pop.reserve( I );
// fill population with empty individuals
while( m_pop.size() < I ) {
// m_pop.push_back( std::make_pair( genome_type(), genome_type() ) );
m_pop.push_back( std::make_pair( create_sequence(), create_sequence()) );
}
setMaxAlleles( A );
}
/*
void finalize() {
individual_iterator it = m_pop.begin();
while( it != m_pop.end() ) {
if( it->first ) it->first->finalize();
if( it->second ) it->second->finalize();
genome_iterator res = m_genomes.find( it->first.get() );
if( res == m_genomes.end() ) {
m_genomes.insert( std::make_pair( it->first.get(), 1 ) );
} else {
res->second += 1;
}
res = m_genomes.find( it->second.get() );
if( res == m_genomes.end() ) {
m_genomes.insert( std::make_pair( it->second.get(), 1 ) );
} else {
res->second += 1;
}
++it;
}
}
*/
void finalize() {
individual_iterator it = m_pop.begin();
while( it != m_pop.end() ) {
if( it->first ) it->first->finalize();
if( it->second ) it->second->finalize();
genome_iterator res = m_genomes.find( it->first );
if( res == m_genomes.end() ) {
m_genomes.insert( std::make_pair( it->first, 1 ) );
} else {
res->second += 1;
}
res = m_genomes.find( it->second );
if( res == m_genomes.end() ) {
m_genomes.insert( std::make_pair( it->second, 1 ) );
} else {
res->second += 1;
}
++it;
}
}
void setMaxAlleles( unsigned int M ) {
m_max_alleles = M;
m_max_blocks = base_genome_type::calculateBlockCount( M );
}
void setMaxTraits( unsigned int T ) {
m_max_traits = T;
}
unsigned int getMaxAlleles( ) const {
return m_max_alleles;
}
unsigned int getMaxBlocks( ) const {
return m_max_blocks;
}
unsigned int getMaxTraits() const {
return m_max_traits;
}
void clear() {
m_pop.clear();
m_genomes.clear();
}
virtual ~population_space() {}
protected:
population_type m_pop;
haploid_genomes m_genomes;
unsigned int m_max_alleles, m_max_blocks, m_max_traits;
};
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_POPULATION_SPACE_HPP_
|
putnampp/clotho
|
include/clotho/data_spaces/population_space/population_space.hpp
|
C++
|
apache-2.0
| 13,846
|
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.knime.${parentArtifactId}.node;
/*
Copyright 2015 Actian Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import ${package}.dataflow.operators.NewOperator;
import com.pervasive.datarush.knime.core.framework.AbstractDRNodeFactory;
import com.pervasive.datarush.knime.core.framework.DRNodeModel;
import com.pervasive.datarush.knime.coreui.common.CustomDRNodeDialogPane;
public final class NewOperatorNodeModelFactory extends AbstractDRNodeFactory<NewOperator> {
@Override
protected CustomDRNodeDialogPane<NewOperator> createNodeDialogPane() {
CustomDRNodeDialogPane<NewOperator> dialog = new CustomDRNodeDialogPane<NewOperator>(new NewOperator(), new NewOperatorNodeDialogPane());
dialog.setDefaultTabTitle("Properties");
return dialog;
}
@Override
public DRNodeModel<NewOperator> createDRNodeModel() {
return new DRNodeModel<NewOperator>( new NewOperator(), new NewOperatorNodeSettings());
}
@Override
protected boolean hasDialog() {
return true;
}
}
|
ActianCorp/df-newextension-archetype
|
src/main/resources/archetype-resources/__rootArtifactId__-knime-extensions-nodes/src/main/java/knime/__rootArtifactId__/node/NewOperatorNodeModelFactory.java
|
Java
|
apache-2.0
| 1,638
|
/*
* Copyright (c) 2020 Baidu.com, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.baidubce.services.bec.model.vm.instance;
import com.baidubce.services.bec.model.vo.BecResultVo;
import com.baidubce.services.bec.model.vo.VmInstanceBriefVo;
import lombok.Data;
import java.util.List;
/**
* The response for getting the BEC virtual machine list of the node.
*/
@Data
public class GetBecNodeVmInstanceListResponse extends BecResultVo<List<VmInstanceBriefVo>> {
}
|
baidubce/bce-sdk-java
|
src/main/java/com/baidubce/services/bec/model/vm/instance/GetBecNodeVmInstanceListResponse.java
|
Java
|
apache-2.0
| 1,004
|
/*
* Copyright 2014 Kevin Quan (kevin.quan@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kevinquan.android.utils;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.support.annotation.Nullable;
import android.util.Log;
import com.kevinquan.android.utils.DeviceUtils.Permissions;
import java.lang.reflect.Method;
/**
* Collection of utilities that relate to the network
* @author Kevin Quan (kevin.quan@gmail.com)
*
*/
public class NetworkUtils {
private static final String TAG = NetworkUtils.class.getSimpleName();
// Change this flag to true if we want all network access to be off.
public static boolean DEBUG_NETWORK_OFF_FLAG = false;
/**
* Checks whether there is an available network connection (e.g., on which to send data)
* @param context The context to use to check the network connection
* @return True if there is an available network connection
*/
public static boolean hasNetworkConnection(Context context) {
if (context == null) return false;
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return !DEBUG_NETWORK_OFF_FLAG && netInfo != null && netInfo.isConnected();
}
/**
* Checks whether wifi is enabled (i.e., turned on). This does not check whether the device is connected to a wifi network.
* @param context The context to be used to check the wifi status
* @return True if wifi is on.
*/
public static boolean isWifiEnabled(Context context) {
if (context == null) {
return false;
}
WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
return manager != null && manager.isWifiEnabled();
}
/**
* Attempts to check whether wifi hotspot is enabled on the device. There is an API to do this,
* but currently it is internal to Android. To work around this, we use reflection to invoke the method.
*
* If the method cannot be invoked successfully, false will be returned by default.
* @param context The context to use to check the hotspot status
* @return True if the hotspot is enabled and can be checked
*/
public static boolean isWifiHotspotEnabled(Context context) {
if (!DeviceUtils.hasPermission(context, Permissions.WIFI_STATE)) {
Log.w(TAG, "Could not check whether wifi hotspot is enabled as context does not have permission "+Permissions.WIFI_STATE);
return false;
}
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
// This API is not public yet. When it is, we can just use that instead of reflection.
//wifiApEnabled = wifiManager.isWifiApEnabled();
Method apEnabledMethod = null;
try {
apEnabledMethod = wifiManager.getClass().getMethod("isWifiApEnabled");
if (apEnabledMethod != null) {
try {
return (Boolean)apEnabledMethod.invoke(wifiManager);
} catch (Exception e) {
Log.w(TAG, "Could not invoke method to check whether Wifi AP is enabled or not.", e);
}
}
} catch (NoSuchMethodException nsme) {
Log.w(TAG, "Could not check whether hotspot is enabled.", nsme);
}
return false;
}
/**
* Retrieves an intent to open the settings for Wi-Fi
* @param context The context to construct the intent with
* @return The intent or null if no such location exists
*/
@Nullable
public static Intent getWifiSettingsIntent(Context context) {
if (context == null) {
return null;
}
Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
if (DeviceUtils.hasActivityResolverFor(context, intent)) {
return intent;
}
return null;
}
}
|
kquan/android-utils
|
core/src/com/kevinquan/android/utils/NetworkUtils.java
|
Java
|
apache-2.0
| 4,479
|
package com.xubin.starclass;
import android.app.Application;
import com.xubin.starclass.entity.Lesson;
import com.xubin.starclass.entity.Unit;
import com.xubin.starclass.entity.User;
import com.xubin.starclass.https.XUtils;
import com.xubin.starclass.utils.SharedUtil;
import java.util.List;
import cn.jpush.android.api.JPushInterface;
/**
* Created by Xubin on 2015/9/8.
*/
public class MyApp extends Application {
public static User user;
public static Lesson lesson;
public static List<Unit> unitList;
@Override
public void onCreate() {
super.onCreate();
XUtils.init(getApplicationContext());
JPushInterface.setDebugMode(true);
JPushInterface.init(this);
if (SharedUtil.isPush(getApplicationContext())) {
JPushInterface.resumePush(getApplicationContext());
} else {
JPushInterface.stopPush(getApplicationContext());
}
}
public static void release() {
user = null;
lesson = null;
if (null != unitList) {
unitList.clear();
}
unitList = null;
}
}
|
hnxylc8818/StarClass
|
src/main/java/com/xubin/starclass/MyApp.java
|
Java
|
apache-2.0
| 1,120
|
package com.demo.widget.twitter.appwidget.controls;
import java.util.HashMap;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import com.demo.widget.twitter.PhoneBootReceiver;
import com.demo.widget.twitter.R;
import com.demo.widget.twitter.appwidget.config.ConfigActivity;
import com.demo.widget.twitter.database.DatabaseHelper;
import com.demo.widget.twitter.database.DatabaseManager;
import com.demo.widget.twitter.database.FileManager;
import com.demo.widget.twitter.helpers.GeneralUtils;
import com.demo.widget.twitter.helpers.SessionStore;
import com.demo.widget.twitter.helpers.WidgetInfo;
public class WidgetProvider extends AppWidgetProvider {
public static String WIDGET_UPDATE = "com.demo.widget.twitter.TWEET_WIDGET_UPDATE";
public static String WIDGET_ME_LIST_STATII_UPDATE = "com.demo.widget.twitter.ME_LIST_STATII";
public static String WIDGET_LIST_REFRESH = "com.demo.widget.twitter.WIDGET_REFRESH";
public static String WIDGET_LIST_SETTING = "com.demo.widget.twitter.WIDGET_LIST_SETTING";
public static String WIDGET_VISIBILITY = "com.demo.widget.twitter.WIDGET_VISIBILITY";
private static HandlerThread sWorkerThread;
private static Handler sWorkerQueue;
public static final String UPDATE_ACTION = "updateAction",
VISIBILITY_ACTION = "visibility";
public static final int GO_FOR_UPDATE = 0x1, GO_FOR_NOTIFY = 0x2;
private int notifyNature = GO_FOR_UPDATE;
public static String LIST_NAME = "listName";
private static HashMap<Integer, Uri> uriHolder = new HashMap<Integer, Uri>();
public WidgetProvider() {
sWorkerThread = new HandlerThread("WidgetProvider-worker");
sWorkerThread.start();
sWorkerQueue = new Handler(sWorkerThread.getLooper());
}
/*
* Once the phone boots,need to populate the widgets,so for that using
* PhoneBootReceiver isPhoneReboot value make Android update our widgets
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
if (PhoneBootReceiver.isPhoneReboot) {
PhoneBootReceiver.isPhoneReboot = false;
final int N = appWidgetIds.length;
for (int i = 0; i < N; ++i) {
RemoteViews remoteViews = updateWidgetListView(context,
appWidgetIds[i]);
appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);
}
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
/*
* MEthod which receives broadcast for Status Update Refresh Widget Delete
* Widget ListView and Progressbar toggle visibility
*/
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
initDatabase(context);
final String listName = intent.hasExtra(LIST_NAME) ? intent
.getStringExtra(LIST_NAME) : context.getString(R.string.tweets);
Log.i("Update Recieved", "Update Received");
final int appWidgetId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
final Context ctx = context;
if (WIDGET_UPDATE.equals(action)) {
Log.i("Widget Update from", "Alarm manager");
Log.i("appWidgetId", String.valueOf(appWidgetId));
refreshStatiiList(context, appWidgetId);
} else if (WIDGET_ME_LIST_STATII_UPDATE.equals(action)) {
if (intent.hasExtra(WidgetProvider.UPDATE_ACTION))
notifyNature = intent.getIntExtra(UPDATE_ACTION, GO_FOR_UPDATE);
Log.i("Go for me list update", "go for me list update");
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
RemoteViews remoteViews = updateWidgetListView(context,
appWidgetId);
if (!listName.equals(dbManager.getTweetListName(appWidgetId))) {
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
if (notifyNature == GO_FOR_NOTIFY) {
final ComponentName cn = new ComponentName(context,
WidgetProvider.class);
appWidgetManager.notifyAppWidgetViewDataChanged(
appWidgetManager.getAppWidgetIds(cn),
R.id.tweetListView);
Log.i("update nature==", "notify");
} else {
Log.i("update nature==", "update");
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
Log.i("Invalid App Widget Id",
String.valueOf(AppWidgetManager.INVALID_APPWIDGET_ID));
Log.i("App Widget Id", String.valueOf(appWidgetId));
// }
}
} else if (WIDGET_LIST_REFRESH.equals(action)) {
Log.i("Refresh Action", "Go for refresh");
Log.i("appWidgetId", String.valueOf(appWidgetId));
refreshStatiiList(context, appWidgetId);
} else if (WIDGET_LIST_SETTING.equals(action)) {
Log.i("settings go", "go for settings");
Log.i("app widget id", String.valueOf(appWidgetId));
sWorkerQueue.removeMessages(0);
sWorkerQueue.post(new Runnable() {
@Override
public void run() {
Intent settingIntent = new Intent(ctx, ConfigActivity.class);
settingIntent.putExtra(UPDATE_ACTION, GO_FOR_NOTIFY);
settingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle params = new Bundle();
params.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
appWidgetId);
settingIntent.putExtras(params);
ctx.startActivity(settingIntent);
}
});
} else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
Log.i("delete contents of widgetid", String.valueOf(appWidgetId));
sWorkerQueue.removeMessages(0);
sWorkerQueue.post(new Runnable() {
@Override
public void run() {
// delete table from db associated with that widget
Log.i("app widget value deleted", "from database");
dbManager.deleteStoredValueOfWidget(Integer
.toString(appWidgetId));
SessionStore.deleteUpdateInterval(ctx, appWidgetId);
GeneralUtils.cancelAlarmManager(ctx, appWidgetId);
FileManager.INSTANCE.deleteDirectory(appWidgetId);
}
});
} else if (WIDGET_VISIBILITY.equals(action)) {
final boolean showListViewWidget = intent.getBooleanExtra(
WIDGET_VISIBILITY, false);
sWorkerQueue.removeMessages(0);
sWorkerQueue.post(new Runnable() {
@Override
public void run() {
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(ctx);
RemoteViews remoteView = new RemoteViews(ctx
.getPackageName(), R.layout.widget_layout);
if (showListViewWidget) {
remoteView.setViewVisibility(R.id.listViewLayout,
View.VISIBLE);
remoteView.setViewVisibility(R.id.progressBar,
View.GONE);
} else {
remoteView.setViewVisibility(R.id.listViewLayout,
View.GONE);
remoteView.setViewVisibility(R.id.progressBar,
View.VISIBLE);
}
// remoteView.setTextViewText(R.id.headingTextView,
// listName);
appWidgetManager.updateAppWidget(appWidgetId, remoteView);
}
});
}
super.onReceive(context, intent);
}
/**
* @param ctx
* @param appWidgetId
* Method to refresh Widget Status or feeds
*/
private void refreshStatiiList(final Context ctx, final int appWidgetId) {
final WidgetInfo widgetInfo = dbManager.getWidgetInfo(Integer
.toString(appWidgetId));
sWorkerQueue.removeMessages(0);
sWorkerQueue.post(new Runnable() {
@Override
public void run() {
Intent listRefreshIntent = new Intent(ctx, TwitterService.class);
listRefreshIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
appWidgetId);
listRefreshIntent.putExtra(WidgetProvider.UPDATE_ACTION,
WidgetProvider.GO_FOR_NOTIFY);
Log.i("WidgetInfoType", widgetInfo.widgetType);
if (widgetInfo.widgetType.equals(DatabaseHelper.TYPE_TIMELINE)) {
listRefreshIntent
.setAction(TwitterService.ACTION_TIMELINE_FETCH);
} else {
listRefreshIntent
.setAction(TwitterService.ACTION_MELIST_FETCH);
listRefreshIntent.putExtra(TwitterService.ME_LIST_ID,
widgetInfo.listItemId);
}
ctx.startService(listRefreshIntent);
}
});
}
private DatabaseManager dbManager;
/**
* @param context
* Initializing DatabaseManager
*/
private void initDatabase(Context context) {
if (dbManager == null) {
dbManager = DatabaseManager.INSTANCE;
dbManager.init(context);
}
}
/**
* @param context
* @param appWidgetId
* @return Method to populate app widget listView and setting button click
* action as well
*/
private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
// for (int i = 0; i < N; i++) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
Intent svcIntent = new Intent(context, WidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
remoteViews
.setRemoteAdapter(appWidgetId, R.id.tweetListView, svcIntent);
remoteViews.setEmptyView(R.id.tweetListView, R.id.empty_view);
Log.i("Update App Widget", "Update app widgets");
remoteViews.setTextViewText(R.id.headingTextView,
dbManager.getTweetListName(appWidgetId));
final Intent refreshIntent = new Intent(context, WidgetProvider.class);
refreshIntent
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
refreshIntent.setAction(WidgetProvider.WIDGET_LIST_REFRESH);
final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(
context, appWidgetId, refreshIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// refreshPendingIntent.
remoteViews.setOnClickPendingIntent(R.id.refreshImageView,
refreshPendingIntent);
final Intent settingIntent = new Intent(context, WidgetProvider.class);
settingIntent
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
settingIntent.setAction(WIDGET_LIST_SETTING);
final PendingIntent settingPendingIntent = PendingIntent.getBroadcast(
context, appWidgetId, settingIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.settingImageView,
settingPendingIntent);
initAlarmManager(context, appWidgetId,
SessionStore.getUpdateInterval(context, appWidgetId));
return remoteViews;
}
/**
* @param context
* @param appWidgetId
* @param updateIntervalInMillis
* Using helper class GeneralUtils to initialize AlarmManager for
* periodic update of widgets as per the value set on Update
* Interval Spinner
*/
private void initAlarmManager(Context context, int appWidgetId,
long updateIntervalInMillis) {
GeneralUtils.initAlarmManager(context, appWidgetId,
updateIntervalInMillis);
}
// ---Respective Methods to add Uri in relation with appwidget Id to
// uniquely identify AlarmManager intent to start/stop it
public static void addUri(int appWidgetId, Uri uri) {
uriHolder.put(Integer.valueOf(appWidgetId), uri);
}
public static Uri getUri(int appWidgetId) {
return uriHolder.get(appWidgetId);
}
public static void remoteUri(int appWidgetId) {
uriHolder.remove(appWidgetId);
}
// -----------------------------------------------------------------------------------------------
}
|
laaptu/twitterwidget
|
src/com/demo/widget/twitter/appwidget/controls/WidgetProvider.java
|
Java
|
apache-2.0
| 11,491
|
package me.superkoh.kframework.lib.payment.wechat.sdk.common.report;
import me.superkoh.kframework.lib.payment.wechat.sdk.common.report.protocol.ReportReqData;
import me.superkoh.kframework.lib.payment.wechat.sdk.common.report.service.ReportService;
/**
* User: rizenguo
* Date: 2014/12/3
* Time: 11:42
*/
public class Reporter {
private ReportRunable r;
private Thread t;
private ReportService rs;
/**
* 请求统计上报API
* @param reportReqData 这个数据对象里面包含了API要求提交的各种数据字段
*/
public Reporter(ReportReqData reportReqData){
rs = new ReportService(reportReqData);
}
public void run(){
r = new ReportRunable(rs);
t = new Thread(r);
t.setDaemon(true); //后台线程
t.start();
}
}
|
superkoh/k-framework
|
k-payment/wechat/src/main/java/me/superkoh/kframework/lib/payment/wechat/sdk/common/report/Reporter.java
|
Java
|
apache-2.0
| 821
|
/**
* SIX OVAL - https://nakamura5akihito.github.io/
* Copyright (C) 2010 Akihito Nakamura
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.opensec.six.oval.model.windows;
import io.opensec.six.oval.model.ComponentType;
import io.opensec.six.oval.model.Family;
import io.opensec.six.oval.model.common.CheckEnumeration;
import io.opensec.six.oval.model.definitions.StateRefType;
import io.opensec.six.oval.model.definitions.SystemObjectRefType;
import io.opensec.six.oval.model.definitions.TestType;
/**
* The file audit permissions test is used to check
* the audit permissions associated with Windows files.
*
* @author Akihito Nakamura, AIST
* @see <a href="http://oval.mitre.org/language/">OVAL Language</a>
* @deprecated Deprecated as of version 5.3:
* Replaced by the fileauditedpermissions53 test and
* will be removed in version 6.0 of the language.
*/
@Deprecated
public class FileAuditedPermissionsTest
extends TestType
{
/**
* Constructor.
*/
public FileAuditedPermissionsTest()
{
this( null, 0 );
}
public FileAuditedPermissionsTest(
final String id,
final int version
)
{
this( id, version, null, null );
}
public FileAuditedPermissionsTest(
final String id,
final int version,
final String comment,
final CheckEnumeration check
)
{
this( id, version, comment, check, null, null );
}
public FileAuditedPermissionsTest(
final String id,
final int version,
final String comment,
final CheckEnumeration check,
final SystemObjectRefType object,
final StateRefType[] stateList
)
{
super( id, version, comment, check, object, stateList );
// _oval_platform_type = OvalPlatformType.windows;
// _oval_component_type = OvalComponentType.fileauditedpermissions;
_oval_family = Family.WINDOWS;
_oval_component = ComponentType.FILEAUDITEDPERMISSIONS;
}
//**************************************************************
// java.lang.Object
//**************************************************************
@Override
public int hashCode()
{
return super.hashCode();
}
@Override
public boolean equals(
final Object obj
)
{
if (!(obj instanceof FileAuditedPermissionsTest)) {
return false;
}
return super.equals( obj );
}
@Override
public String toString()
{
return "fileauditedpermissions_test[" + super.toString() + "]";
}
}
//FileAuditedPermissionsTest
|
nakamura5akihito/six-oval
|
src/main/java/io/opensec/six/oval/model/windows/FileAuditedPermissionsTest.java
|
Java
|
apache-2.0
| 3,416
|
package com.sharksharding.sql.visitor;
///*
// * Copyright 1999-2101 Alibaba Group Holding Ltd.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//package com.alibaba.druid.sql.visitor;
//
//import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
//import com.alibaba.druid.sql.ast.expr.SQLCharExpr;
//import com.alibaba.druid.sql.ast.expr.SQLInListExpr;
//import com.alibaba.druid.sql.ast.expr.SQLIntegerExpr;
//import com.alibaba.druid.sql.ast.expr.SQLNCharExpr;
//import com.alibaba.druid.sql.ast.expr.SQLNullExpr;
//import com.alibaba.druid.sql.ast.expr.SQLNumberExpr;
//
//public class ParameterizedOutputVisitor extends SQLASTOutputVisitor implements ParameterizedVisitor {
//
// private int replaceCount;
//
// public ParameterizedOutputVisitor(){
// this(new StringBuilder());
// }
//
// public ParameterizedOutputVisitor(Appendable appender){
// super(appender);
// }
//
// public int getReplaceCount() {
// return this.replaceCount;
// }
//
// public void incrementReplaceCunt() {
// replaceCount++;
// }
//
// public boolean visit(SQLInListExpr x) {
// return ParameterizedOutputVisitorUtils.visit(this, x);
// }
//
// public boolean visit(SQLBinaryOpExpr x) {
// x = ParameterizedOutputVisitorUtils.merge(this, x);
//
// return super.visit(x);
// }
//
// public boolean visit(SQLIntegerExpr x) {
// if (!ParameterizedOutputVisitorUtils.checkParameterize(x)) {
// return super.visit(x);
// }
//
// return ParameterizedOutputVisitorUtils.visit(this, x);
// }
//
// public boolean visit(SQLNumberExpr x) {
// if (!ParameterizedOutputVisitorUtils.checkParameterize(x)) {
// return super.visit(x);
// }
//
// return ParameterizedOutputVisitorUtils.visit(this, x);
// }
//
// public boolean visit(SQLCharExpr x) {
// if (!ParameterizedOutputVisitorUtils.checkParameterize(x)) {
// return super.visit(x);
// }
//
// return ParameterizedOutputVisitorUtils.visit(this, x);
// }
//
// public boolean visit(SQLNCharExpr x) {
// if (!ParameterizedOutputVisitorUtils.checkParameterize(x)) {
// return super.visit(x);
// }
//
// return ParameterizedOutputVisitorUtils.visit(this, x);
// }
//
// public boolean visit(SQLNullExpr x) {
// if (!ParameterizedOutputVisitorUtils.checkParameterize(x)) {
// return super.visit(x);
// }
//
// return ParameterizedOutputVisitorUtils.visit(this, x);
// }
//
//}
|
gaoxianglong/shark
|
src/main/java/com/sharksharding/sql/visitor/ParameterizedOutputVisitor.java
|
Java
|
apache-2.0
| 3,116
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<b>Angkor Team</b>
</div>
<div class="login-box-body">
<p class="login-box-msg">Mobile Backend as a Service</p>
<form wicket:id="form">
<div class="form-group">
<label wicket:for="loginField">
<wicket:message key="label.login">Login</wicket:message>
</label>
<input wicket:id="loginField" type="text" class="form-control"/>
<span wicket:id="loginFeedback" class="help-block"/>
</div>
<div class="form-group">
<label wicket:for="passwordField">
<wicket:message key="label.password">Password</wicket:message>
</label>
<input wicket:id="passwordField" type="password" class="form-control"/>
<span wicket:id="passwordFeedback" class="help-block"/>
</div>
<div class="form-group">
<label wicket:for="languageField">
<wicket:message key="label.language">Language</wicket:message>
</label>
<select wicket:id="languageField" class="form-control"/>
<span wicket:id="languageFeedback" class="help-block"/>
</div>
<div class="row">
<div class="col-xs-6">
<button wicket:id="loginButton" type="submit" class="btn btn-primary btn-block btn-flat">
<wicket:message key="button.login">Login</wicket:message>
</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
|
PkayJava/MBaaS
|
mbaas-server/src/main/resources/com/angkorteam/mbaas/server/page/LoginPage.html
|
HTML
|
apache-2.0
| 1,804
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jun 10 10:20:17 MST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.elytron.CertificateAuthority (BOM: * : All 2.6.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2020-06-10">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.elytron.CertificateAuthority (BOM: * : All 2.6.1.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/CertificateAuthority.html" target="_top">Frames</a></li>
<li><a href="CertificateAuthority.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.elytron.CertificateAuthority" class="title">Uses of Class<br>org.wildfly.swarm.config.elytron.CertificateAuthority</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config">org.wildfly.swarm.config</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.elytron">org.wildfly.swarm.config.elytron</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a> in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> that return <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></code></td>
<td class="colLast"><span class="typeNameLabel">Elytron.ElytronResources.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/Elytron.ElytronResources.html#certificateAuthority-java.lang.String-">certificateAuthority</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> that return types with arguments of type <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a>></code></td>
<td class="colLast"><span class="typeNameLabel">Elytron.ElytronResources.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/Elytron.ElytronResources.html#certificateAuthorities--">certificateAuthorities</a></span>()</code>
<div class="block">Get the list of CertificateAuthority resources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/Elytron.html" title="type parameter in Elytron">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">Elytron.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/Elytron.html#certificateAuthority-org.wildfly.swarm.config.elytron.CertificateAuthority-">certificateAuthority</a></span>(<a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a> value)</code>
<div class="block">Add the CertificateAuthority object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> with type arguments of type <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/Elytron.html" title="type parameter in Elytron">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">Elytron.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/Elytron.html#certificateAuthorities-java.util.List-">certificateAuthorities</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</a><<a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a>> value)</code>
<div class="block">Add all CertificateAuthority objects to this subresource</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.elytron">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a> in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a> with type parameters of type <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a><T extends <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a><T>></span></code>
<div class="block">A certificate authority definition.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthorityConsumer.html" title="interface in org.wildfly.swarm.config.elytron">CertificateAuthorityConsumer</a><T extends <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a><T>></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthoritySupplier.html" title="interface in org.wildfly.swarm.config.elytron">CertificateAuthoritySupplier</a><T extends <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a>></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/elytron/package-summary.html">org.wildfly.swarm.config.elytron</a> that return <a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">CertificateAuthority</a></code></td>
<td class="colLast"><span class="typeNameLabel">CertificateAuthoritySupplier.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthoritySupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of CertificateAuthority resource</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/elytron/CertificateAuthority.html" title="class in org.wildfly.swarm.config.elytron">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/elytron/class-use/CertificateAuthority.html" target="_top">Frames</a></li>
<li><a href="CertificateAuthority.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2.6.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/elytron/class-use/CertificateAuthority.html
|
HTML
|
apache-2.0
| 15,708
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112) on Thu Jul 06 10:54:05 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.RequestController (Public javadocs 2017.7.0 API)</title>
<meta name="date" content="2017-07-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.RequestController (Public javadocs 2017.7.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.7.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/RequestController.html" target="_top">Frames</a></li>
<li><a href="RequestController.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.RequestController" class="title">Uses of Class<br>org.wildfly.swarm.config.RequestController</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config">org.wildfly.swarm.config</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.request.controller">org.wildfly.swarm.request.controller</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a> in <a href="../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> with type parameters of type <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a><T extends <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a><T>></span></code>
<div class="block">The request controller subsystem.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/RequestControllerConsumer.html" title="interface in org.wildfly.swarm.config">RequestControllerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a><T>></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/RequestControllerSupplier.html" title="interface in org.wildfly.swarm.config">RequestControllerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a>></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> that return <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a></code></td>
<td class="colLast"><span class="typeNameLabel">RequestControllerSupplier.</span><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/RequestControllerSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of RequestController resource</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.request.controller">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a> in <a href="../../../../../org/wildfly/swarm/request/controller/package-summary.html">org.wildfly.swarm.request.controller</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">RequestController</a> in <a href="../../../../../org/wildfly/swarm/request/controller/package-summary.html">org.wildfly.swarm.request.controller</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/request/controller/RequestControllerFraction.html" title="class in org.wildfly.swarm.request.controller">RequestControllerFraction</a></span></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/RequestController.html" title="class in org.wildfly.swarm.config">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.7.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/class-use/RequestController.html" target="_top">Frames</a></li>
<li><a href="RequestController.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2017.7.0/apidocs/org/wildfly/swarm/config/class-use/RequestController.html
|
HTML
|
apache-2.0
| 10,590
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.project;
import com.android.builder.model.AndroidProject;
import com.android.sdklib.AndroidTargetHash;
import com.android.sdklib.AndroidVersion;
import com.android.tools.idea.gradle.IdeaAndroidProject;
import com.android.tools.idea.gradle.messages.Message;
import com.android.tools.idea.gradle.messages.ProjectSyncMessages;
import com.android.tools.idea.gradle.service.notification.hyperlink.NotificationHyperlink;
import com.android.tools.idea.gradle.service.notification.hyperlink.OpenFileHyperlink;
import com.android.tools.idea.gradle.service.notification.hyperlink.OpenUrlHyperlink;
import com.android.tools.idea.sdk.IdeSdks;
import com.android.tools.idea.sdk.Jdks;
import com.android.tools.idea.structure.gradle.AndroidProjectSettingsService;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.NonNavigatable;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyLexer;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.must.android.module.extension.AndroidModuleExtension;
import java.util.List;
import static com.android.tools.idea.gradle.util.GradleUtil.getGradleBuildFile;
import static com.android.tools.idea.gradle.util.Projects.setHasWrongJdk;
import static com.android.tools.idea.sdk.Jdks.isApplicableJdk;
final class ProjectJdkChecks {
private ProjectJdkChecks() {
}
static boolean hasCorrectJdkVersion(@NotNull Module module) {
AndroidFacet facet = ModuleUtilCore.getExtension(module, AndroidModuleExtension.class);
if (facet != null && facet.getIdeaAndroidProject() != null) {
return hasCorrectJdkVersion(module, facet.getIdeaAndroidProject());
}
return true;
}
static boolean hasCorrectJdkVersion(@NotNull Module module, @NotNull IdeaAndroidProject model) {
AndroidProject androidProject = model.getDelegate();
String compileTarget = androidProject.getCompileTarget();
AndroidVersion version = AndroidTargetHash.getPlatformVersion(compileTarget);
if (version != null && version.getFeatureLevel() >= 21) {
Sdk jdk = IdeSdks.getJdk();
if (jdk != null && !isApplicableJdk(jdk, LanguageLevel.JDK_1_7)) {
Project project = module.getProject();
List<NotificationHyperlink> hyperlinks = Lists.newArrayList();
hyperlinks.add(new OpenUrlHyperlink(Jdks.DOWNLOAD_JDK_7_URL, "Download JDK 7"));
ProjectSettingsService service = ProjectSettingsService.getInstance(project);
if (service instanceof AndroidProjectSettingsService) {
hyperlinks.add(new SelectJdkHyperlink((AndroidProjectSettingsService)service));
}
Message msg;
String text = "compileSdkVersion " + compileTarget + " requires compiling with JDK 7";
VirtualFile buildFile = getGradleBuildFile(module);
String groupName = "Project Configuration";
if (buildFile != null) {
int lineNumber = -1;
int column = -1;
Document document = FileDocumentManager.getInstance().getDocument(buildFile);
if (document != null) {
int offset = findCompileSdkVersionValueOffset(document.getText());
if (offset > -1) {
lineNumber = document.getLineNumber(offset);
if (lineNumber > -1) {
int lineStartOffset = document.getLineStartOffset(lineNumber);
column = offset - lineStartOffset;
}
}
}
hyperlinks.add(new OpenFileHyperlink(buildFile.getPath(), "Open build.gradle File", lineNumber, column));
msg = new Message(project, groupName, Message.Type.ERROR, buildFile, lineNumber, column, text);
}
else {
msg = new Message(groupName, Message.Type.ERROR, NonNavigatable.INSTANCE, text);
}
ProjectSyncMessages messages = ProjectSyncMessages.getInstance(project);
messages.add(msg, hyperlinks.toArray(new NotificationHyperlink[hyperlinks.size()]));
setHasWrongJdk(project, true);
return false;
}
}
return true;
}
// Returns the offset where the 'compileSdkVersion' value is in a build.gradle file.
@VisibleForTesting
static int findCompileSdkVersionValueOffset(@NotNull String buildFileContents) {
GroovyLexer lexer = new GroovyLexer();
lexer.start(buildFileContents);
int end = -1;
while (lexer.getTokenType() != null) {
IElementType type = lexer.getTokenType();
String text = lexer.getTokenText();
if (type == GroovyTokenTypes.mIDENT) {
if ("compileSdkVersion".equals(text)) {
end = lexer.getTokenEnd();
}
else if (end > -1) {
return end;
}
}
else if (type == TokenType.WHITE_SPACE && end > -1) {
end++;
}
else if (end > -1) {
return end;
}
lexer.advance();
}
return -1;
}
private static class SelectJdkHyperlink extends NotificationHyperlink {
@NotNull private final AndroidProjectSettingsService mySettingsService;
SelectJdkHyperlink(@NotNull AndroidProjectSettingsService settingsService) {
super("select.jdk", "Select a JDK from the File System");
mySettingsService = settingsService;
}
@Override
protected void execute(@NotNull Project project) {
mySettingsService.chooseJdkLocation();
}
}
}
|
consulo/consulo-android
|
android/android/src/com/android/tools/idea/gradle/project/ProjectJdkChecks.java
|
Java
|
apache-2.0
| 6,654
|
package com.lp.techDemo.http.message.listener;
public interface GeneralMessageConsumer {
void onMessageReceive();
}
|
Roronoa-Zoro/TechDemos
|
src/main/java/com/lp/techDemo/http/message/listener/GeneralMessageConsumer.java
|
Java
|
apache-2.0
| 119
|
# Eugenia heckelii Pancher & Sebert SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Austromyrtus/Austromyrtus vieillardii/ Syn. Eugenia heckelii/README.md
|
Markdown
|
apache-2.0
| 190
|
SVGCalendar = function (root_width, root_height, i_options) {
var DEFAULTS = {
start_date: new Date()// Date : default is today
//--- end_date
, end_date: null// Date : default is today
, day_num: null// int : active when end_date is null
, week_num: 4// int : active when end_date and day_num is null
//--- layouts
, day_name_height: 30 // int
, day_name_transform: 'translate(0, ${height})' // str
//-- options
, start_day: 'monday' // str or null : if null, calendar start today
, table_options: {} //
, cell_hook: null//
};
var SVGNS = 'http://www.w3.org/2000/svg';
var that = this;
var CLASSES = {
selecting: 'selecting',
active: 'active',
cell: 'svg_cell',
table: 'svg_calendar',
row_name: 'row_name',
column_name: 'column_name',
even_month:'even_month',
odd_month:'odd_month',
holiday: 'holiday',
disabled:'disabled'
};
// extend args d:jquery
var args = (function () {
var options = $.extend(true, {}, DEFAULTS);
$.extend(true, options, i_options);
return options;
})();
// args
$.extend(true, CLASSES, args.CLASSES);
this.options = args;
// week of days
var day2int = function (day_str) {
// if invalid input, return -1
day_str = day_str.toLowerCase().slice(0, 3);
return ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].indexOf(day_str);
};
var int2day = function (day_int, is_short) {
// if invalid input, return undefined
day_str = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][day_int%7];
if(is_short){
day_str = day_str.slice(0,3);
}
return day_str;
};
var get_date_delta_by_day = function (date1,date2) {
var diff = Math.abs(date1.getTime() - date2.getTime());
return Math.ceil(diff/(24*60*60*1000))
};
// today
var today = new Date();
//--- gen start and end
// - assigned_start_date
// - assigned_end_date
// - table_start_date
// - table_end_date
var assigned_start_date = args.start_date;
var table_start_date = (function () {
if (args.start_day === null) {
return assigned_start_date;
}
var week_of_day = day2int(args.start_day);
var delta_day = (today.getDay() + 7 - week_of_day) % 7;
var res_day = new Date();
res_day.setDate(today.getDate() - delta_day);
return res_day;
})();
var assigned_end_date = (function () {
var res_date = new Date(assigned_start_date.getTime());
if (args.end_date !== null) {
return args.end_date;
}
if (args.day_num !== null) {
res_date.setDate(res_date.getDate() + args.day_num);
return res_date;
}
if (args.week_num !== null) {
res_date.setDate(table_start_date.getDate() + 7 * args.week_num-1);
return res_date;
}
})();
var table_end_date = (function () {
var last_week_of_day = (7 + table_start_date.getDay() - 1)%7;
var delta_day = 7-(assigned_end_date.getDay() - last_week_of_day) % 7;
var res_date = new Date(assigned_end_date.getTime());
res_date.setDate(res_date.getDate() + delta_day);
return res_date;
})();
var row_num = Math.ceil(get_date_delta_by_day(table_start_date, table_end_date)/7);
// init calendar text value
var cell_texts = new Array(7);
(function(){
var ptr_date = new Date(table_start_date.getTime());
for(var row=0;row<row_num;row++){
cell_texts[row] = new Array(7);
for(var col=0;col<7;col++){
if((row==0&&col==0) || ptr_date.getDate()==1){
cell_texts[row][col] = ""+(ptr_date.getMonth()+1)+"/"+ptr_date.getDate();
}else{
cell_texts[row][col] = ""+ptr_date.getDate();
}
ptr_date.setDate(ptr_date.getDate()+1);
}
}
})();
// init column_name
var column_names = new Array(7);
(function(){
var offset = table_start_date.getDay();
for(var i = 0;i<7;i++){
column_names[i] = int2day(i+offset)
}
})();
var cell_hook = function (cell_elem, that_table) {
var delta = cell_elem.data('row')*7+cell_elem.data('col');
var date = new Date(table_start_date.getTime()+delta*24*60*60*1000);
cell_elem.data('date', date);
cell_elem.addClass([CLASSES.even_month,CLASSES.odd_month][(date.getMonth()+1)%2]);
if(date.getDay()==6 ||date.getDay()==0){
cell_elem.addClass(CLASSES.holiday);
}
if(args.cell_hook !== null){
args.cell_hook(cell_elem, that_table)
}
};
// table options
var table_options = {
column_num:7,
row_num:row_num,
cell_texts: cell_texts,
cell_texts_is_row_col:true,
CLASSES:CLASSES,
column_names: column_names,
column_name_height: args.day_name_height,
column_name_text_transform: args.day_name_transform,
select_mode:'horizontal',
cell_hook: cell_hook
};
// over write
$.extend(true, table_options, args.table_options);
// init table
this.table = new SVGTable(root_width, root_height, table_options);
};
SVGCalendar.prototype.get_root_elem = function () {
return this.table.get_root_elem();
};
SVGCalendar.prototype.get_active_dates = function(){
var active_cells = this.table.get_active_cells();
var active_dates = [];
for(var i=active_cells.length;i--;){
var date = new Date(active_cells[i].data('date').getTime());
active_dates.push(date)
}
return active_dates;
};
|
cocuh/SVG-Table
|
src/svg-calendar.js
|
JavaScript
|
apache-2.0
| 5,972
|
package WordGraph::EdgeFeature;
use Moose;
use namespace::autoclean;
# id
has 'id' => ( is => 'ro' , isa => 'Str' , required => 1 );
with('Feature');
# params
has 'params' => ( is => 'ro' , isa => 'HashRef' , default => sub { {} } );
sub cache_key {
my $this = shift;
my $instance = shift;
my $edge = shift;
my $graph = shift;
# TODO: include graph id asap
my $cache_key = join( "::" , $edge->[0] , $edge->[1] , $instance->id );
return $cache_key;
}
# value
sub compute {
my $this = shift;
my $instance = shift;
my $edge = shift;
my $graph = shift;
my %features;
my $feature_key = $this->id();
# 1 - collect common resources
my $common_resources = $this->get_resources( $graph , $edge , $instance );
# 2 - compute node-level features (if required)
my $source_features = $this->value_node( $graph , $edge , $instance , $common_resources , 0 );
if ( $source_features ) {
$this->_update_features( "source" , \%features , $source_features );
}
my $sink_features = $this->value_node( $graph , $edge , $instance , $common_resources , 1 );
if ( $sink_features ) {
$this->_update_features( "sink" , \%features , $sink_features );
}
# 3 - compute edge-level features (if required)
my $edge_features = $this->value_edge( $graph , $edge , $instance , $common_resources , $source_features , $sink_features );
if ( $edge_features ) {
$this->_update_features( "edge" , \%features , $edge_features );
}
return \%features;
}
# default implementation of get_resources
sub get_resources {
my $this = shift;
my $instance = shift;
my $edge = shift;
my $graph = shift;
return $this->_get_resources( $graph , $edge , $instance );
}
# CURRENT : feature generation code as role applied onto Category::UrlData instances ?
# default implementation of _get_resources
sub _get_resources {
my $this = shift;
my $instance = shift;
my $edge = shift;
my $graph = shift;
# nothing
return {};
}
sub _update_features {
my $this = shift;
my $domain = shift;
my $features_ref = shift;
my $add_features = shift;
# TODO : can I somehow merge these two branches ?
if ( ref( $add_features ) ) {
foreach my $add_feature_id ( keys( %{ $add_features } ) ) {
my $feature_key = $this->key( $domain , $add_feature_id );
$features_ref->{ $feature_key } = $add_features->{ $add_feature_id };
}
}
else {
my $feature_key = $this->key( $domain );
$features_ref->{ $feature_key } = $add_features;
}
}
# feature key
sub key {
my $this = shift;
my $domain = shift;
return feature_key( $domain , $this->id() , @_ );
}
sub feature_key {
return join( "::" , map { if ( ref( $_ ) ) { $_->[ 0 ] } else { $_ } } @_ );
}
# default feature normalizer (no normalization)
sub _normalizer {
my $this = shift;
my $graph = shift;
my $instance = shift;
return 1;
}
__PACKAGE__->meta->make_immutable;
1;
|
ypetinot/web-summarization
|
summarizers/graph-summarizer-4/src/WordGraph/EdgeFeature.pm
|
Perl
|
apache-2.0
| 3,024
|
/*
//Class Declaration (Triangle.h)
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include <iostream>
using namespace std;
class Triangle{
private:
double Hypotenuse;
double Opposite;
double Adjacent;
public:
Triangle();
//Overloaded Constructor
Triangle(double,double,double);
//Destructor
~Triangle();
void set_hypotenuse(double);
void set_opposite(double);
void set_adjacent(double);
double get_hypotenuse();
double get_opposite();
double get_adjacent();
double sine();
double cosine();
double tangent();
};
#endif //TRIANGLE_H
*/
#include <iostream>
#include "Triangle.h"
using namespace std;
Triangle::set_hypotenuse(double nH){
Hypotenuse = nH;
}
Triangle::set_adjacent(double nA){
Adjacent = nA;
}
Triangle::set_opposite(double nO){
Opposite = nO;
}
Triangle::Triangle(){
cout << "The triangle constructor was called!" << endl;
}
Triangle::Triangle(double nH, double nA, double nO){
Hypotenuse = nH;
Adjacent = nA;
Opposite = nO;
cout << "The overloaded triangle constructor was called!" << endl;
}
~Triangle(){
cout << "The triangle distructor was called!" << endl;
}
double Triangle::sine(){
return Opposite / Hypotenuse;
}
double Triangle::cosine(){
return Adjacent / Hypotenuse;
}
double Triangle::tangent(){
return Opposite / Adjacent;
}
|
AldanisVigo/CPlusPlus
|
TriangleClass/Triangle.cpp
|
C++
|
apache-2.0
| 1,277
|
using System.Activities;
using System.Collections.Generic;
using Base.ActivityInterface;
using Base.Dto;
using Microsoft.Practices.ServiceLocation;
namespace WorkflowActivityLibrary.Activity
{
public class ConfirmEmail : CodeActivity
{
public InArgument<EmailDto> Dto { set; get; }
public OutArgument<FlowStatusDto> ActivityOutput { set; get; }
protected override void Execute(CodeActivityContext context)
{
var provider = ServiceLocator.Current.GetInstance<IFlowExtensionProvider>();
var dto = context.GetValue(Dto);
var output = provider.ConfirmEmail(dto);
var item = new FlowStatusDto() {Steps = new List<ActivityOutput>()};
if (output != null)
item.Steps.Add(output);
context.SetValue(ActivityOutput, item);
}
}
}
|
kanewanggit/MbTcsClone
|
Core/BusinessLogic/Activity/ConfirmEmail.cs
|
C#
|
apache-2.0
| 866
|
## git-tutorial
Toy shell for git tutorial purposes
Fork this repository, and then clone it by running the following command:
git clone git@github.com:<username>/git-tutorial-code
### C++
* Building:
cd cpp
mkdir build
cd build
cmake ../
make
* Running:
./lust
### Python
* Running:
cd python
./lust.py
### Maintainers
Developed by:Daria
|
lmark1/git-tutorial-code
|
README.md
|
Markdown
|
apache-2.0
| 400
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Server Error :(</title>
<style>
::-moz-selection {
background: #b3d4fc;
text-shadow: none;
}
::selection {
background: #b3d4fc;
text-shadow: none;
}
html {
padding: 100px 10px;
font-size: 20px;
line-height: 1.4;
color: #737373;
background: #f0f0f0;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
html,
input {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
body {
max-width: 600px;
_width: 600px;
padding: 30px 0px 50px;
border: 1px solid #b3b3b3;
border-radius: 4px;
margin: 0 auto;
box-shadow: 0 1px 10px #a7a7a7, inset 0 1px 0 #fff;
background: #fcfcfc;
}
h1 {
margin: 0 10px;
font-size: 50px;
text-align: center;
}
h1 span {
color: #bbb;
}
h3 {
margin: 1.5em 0 0.5em;
}
p {
margin: 1em 0;
}
ul {
padding: 0 0 0 40px;
margin: 1em 0;
}
.container {
max-width: 550px;
_width: 550px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h1>Server API error <span> :(</span></h1>
<p>Sorry, but the API server was unable to return data</p>
<p>Please <a href="//entry.carre-project.eu">try again</a> and if the problem persists contact the administrators.</p>
<p style="height:20px;"></p>
<hr>
<div style="float:left;">
<img src="assets/images/carre_logo.png" width="36" height="40" alt="CARRE">
<div style="float:right"> <a style="text-decoration: none;" href="https://www.carre-project.eu">CARRE Project</a> © 2015</div>
</div>
<p style="height:20px;"></p>
</div>
</body>
</html>
|
carre-project/carre-entry-system
|
src/500.html
|
HTML
|
apache-2.0
| 1,886
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Mon Mar 31 18:15:55 CEST 2014 -->
<title>gui.panels.monitoring.delays</title>
<meta name="date" content="2014-03-31">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../gui/panels/monitoring/delays/package-summary.html" target="classFrame">gui.panels.monitoring.delays</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="DelaysAverageDisplayer.html" title="class in gui.panels.monitoring.delays" target="classFrame">DelaysAverageDisplayer</a></li>
<li><a href="DelaysAveragesGraph.html" title="class in gui.panels.monitoring.delays" target="classFrame">DelaysAveragesGraph</a></li>
<li><a href="DelaysInfosProvider.html" title="class in gui.panels.monitoring.delays" target="classFrame">DelaysInfosProvider</a></li>
</ul>
</div>
</body>
</html>
|
etrange02/Perftest
|
doc/gui/panels/monitoring/delays/package-frame.html
|
HTML
|
apache-2.0
| 1,079
|
<?php
/**
* @author XiaoCid
* @copyright 2013
*/
?>
<h1>Pre Proses Data</h1>
<div class="data-page">
<center>
<div class="column span9">
<div class=""><img id="loader" class="loader_off" src="<?= Yii::app()->getBaseUrl().'../images/loader_disabled.gif'; ?>"/></div>
<br />
<button id="btn_mulai" type="button" class="btn btn-primary btn-large">Mulai</button>
</div>
</center>
</div>
<?php
?>
<script>
var loader_on = '<?= Yii::app()->getBaseUrl().'../images/loader.gif'; ?>';
var loader_off = '<?= Yii::app()->getBaseUrl().'../images/loader_disabled.gif'; ?>';
var loader = $('#loader');
$(function() {
$('#btn_mulai').click(function (){
if(loader.hasClass('loader_off')){
loader.removeClass('loader_off');
loader.addClass('loader_on');
loader.attr('src', loader_on);
$('button').html('Berhenti')
$('button').addClass('disabled');
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->createUrl('/mining/preprosesDataTwitter'); ?>",
//data: postData , //assign the var here
success: function(msg){
loader.removeClass('loader_on');
loader.addClass('loader_off');
loader.attr('src', loader_off);
$('button').html('Mulai');
$('button').removeClass('disabled');
alert( "Pre Proses Data Selesai pada: "+msg+'!');
}
});
return false;
}else{
loader.removeClass('loader_on');
loader.addClass('loader_off');
loader.attr('src', loader_off);
$('button').html('Mulai');
$('button').removeClass('disabled');
}
})
});
</script>
|
xiaocids/trending_business
|
protected/views/mining/indexPreproses.php
|
PHP
|
apache-2.0
| 2,049
|
package de.peeeq.wurstio.map.importer;
import com.google.common.io.Files;
import com.google.common.io.LittleEndianDataInputStream;
import de.peeeq.wurstio.mpq.MpqEditor;
import de.peeeq.wurstio.mpq.MpqEditorFactory;
import de.peeeq.wurstscript.RunArgs;
import de.peeeq.wurstscript.WLogger;
import de.peeeq.wurstscript.utils.TempDir;
import javax.swing.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.Optional;
public class ImportFile {
private static final String DEFAULT_IMPORT_PATH = "war3mapImported\\";
private static final int FILE_VERSION = 1;
/**
* Use this to start the extraction process
*/
public static void extractImportsFromMap(File mapFile, RunArgs runArgs) {
WLogger.info("Extracting all imported Files...");
if (!mapFile.exists() || !mapFile.isFile() || mapFile.getName().endsWith("w3m")) {
JOptionPane.showMessageDialog(null, "Map " + mapFile.getAbsolutePath() + " does not exist or is of wrong format (w3x only)");
return;
}
try {
File projectFolder = mapFile.getParentFile();
File importDirectory = getImportDirectory(projectFolder);
File tempMap = getCopyOfMap(mapFile);
extractImportsFrom(importDirectory, tempMap, runArgs);
} catch (Exception e) {
WLogger.severe(e);
JOptionPane.showMessageDialog(null, "Could not export objects (2): " + e.getMessage());
}
}
private static void extractImportsFrom(File importDirectory, File tempMap, RunArgs runArgs) throws Exception {
try (MpqEditor editor = MpqEditorFactory.getEditor(Optional.of(tempMap))) {
LinkedList<String> failed = extractImportedFiles(editor, importDirectory);
if (failed.isEmpty()) {
JOptionPane.showMessageDialog(null, "All imports were extracted to " + importDirectory.getAbsolutePath());
} else {
String message = "Following files could not be extracted:\n" + String.join(",", failed);
WLogger.info(message);
JOptionPane.showMessageDialog(null, message);
}
}
}
private static LinkedList<String> extractImportedFiles(MpqEditor mpq, File directory) {
LinkedList<String> failed = new LinkedList<>();
byte[] temp;
try {
temp = mpq.extractFile("war3map.imp");
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "No vaild war3map.imp was found, or there are no imports");
return failed;
}
try (LittleEndianDataInputStream reader = new LittleEndianDataInputStream(new ByteArrayInputStream(temp))) {
@SuppressWarnings("unused")
int fileFormatVersion = reader.readInt(); // Not needed
int fileCount = reader.readInt();
WLogger.info("Imported FileCount: " + fileCount);
for (int i = 1; i <= fileCount; i++) {
extractImportedFile(mpq, directory, failed, reader);
}
return failed;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void extractImportedFile(MpqEditor mpq, File directory, LinkedList<String> failed, LittleEndianDataInputStream reader) throws Exception {
byte b = reader.readByte();
String path = directory.getPath() + "\\";
String mpqpath = "";
if (isStandardPath(b)) {
path += DEFAULT_IMPORT_PATH;
mpqpath += DEFAULT_IMPORT_PATH;
}
String filename = readString(reader);
WLogger.info("Extracting file: " + filename);
filename = filename.trim();
mpqpath += filename;
path += filename;
extractFile(mpq, directory, failed, path, mpqpath, filename);
}
private static void extractFile(MpqEditor mpq, File directory, LinkedList<String> failed, String path, String mpqpath, String filename) throws Exception {
File out = new File(path);
out.getParentFile().mkdirs();
try {
byte[] xx = mpq.extractFile(mpqpath);
Files.write(xx, out);
} catch (IOException e) {
out.delete();
out = new File(directory.getPath() + "\\" + DEFAULT_IMPORT_PATH + filename);
out.getParentFile().mkdirs();
try {
byte[] xx = mpq.extractFile(DEFAULT_IMPORT_PATH + mpqpath);
Files.write(xx, out);
} catch (IOException e1) {
failed.add(mpqpath);
}
}
}
/**
* Blizzard magic numbers for standard path
*/
private static boolean isStandardPath(byte b) {
return b == 5 || b == 8;
}
/**
* Reads chars from the inputstream until it hits a 0-char
*/
private static String readString(LittleEndianDataInputStream reader) throws IOException {
StringBuilder sb = new StringBuilder();
try {
while (true) {
char c = (char) reader.readByte();
if (c == 0) {
return sb.toString();
}
sb.append(c);
}
} catch (EOFException e) {
return sb.toString();
}
}
private static LinkedList<File> getFilesOfDirectory(File dir, LinkedList<File> addTo) {
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
getFilesOfDirectory(f, addTo);
} else {
addTo.add(f);
}
}
return addTo;
}
private static void insertImportedFiles(MpqEditor mpq, File directory) throws Exception {
LinkedList<File> files = new LinkedList<>();
getFilesOfDirectory(directory, files);
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(byteOut);
dataOut.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(FILE_VERSION).array());
dataOut.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(files.size()).array());
for (File f : files) {
Path p = f.toPath();
p = directory.toPath().relativize(p);
String normalizedWc3Path = p.toString().replaceAll("/", "\\\\");
dataOut.writeByte((byte) 13);
dataOut.write(normalizedWc3Path.getBytes("UTF-8"));
dataOut.write((byte) 0);
WLogger.info("importing file: " + normalizedWc3Path);
mpq.deleteFile(normalizedWc3Path);
mpq.insertFile(normalizedWc3Path, f);
}
dataOut.flush();
mpq.deleteFile("war3map.imp");
mpq.insertFile("war3map.imp", byteOut.toByteArray());
}
public static void importFilesFromImportDirectory(File projectFolder, MpqEditor ed) {
File importDirectory = getImportDirectory(projectFolder);
if (importDirectory.exists() && importDirectory.isDirectory()) {
WLogger.info("importing from: " + importDirectory.getAbsolutePath());
WLogger.info("projectFolder: " + projectFolder.getAbsolutePath());
try {
insertImportedFiles(ed, importDirectory);
} catch (Exception e) {
WLogger.severe(e);
JOptionPane.showMessageDialog(null, "Couldn't import resources from " + importDirectory + ": " + e.getMessage());
}
}
}
private static File getCopyOfMap(File mapFile) throws IOException {
File mapTemp = File.createTempFile("temp", "w3x", TempDir.get());
mapTemp.deleteOnExit();
Files.copy(mapFile, mapTemp);
return mapTemp;
}
private static File getImportDirectory(File projectFolder) {
return new File(projectFolder, "imports");
}
}
|
peq/WurstScript
|
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/map/importer/ImportFile.java
|
Java
|
apache-2.0
| 7,961
|
// Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
ARRAY_PATTERN,
BINDING_IDENTIFIER,
OBJECT_PATTERN,
OBJECT_PATTERN_FIELD,
PAREN_EXPRESSION,
SPREAD_PATTERN_ELEMENT
} from '../syntax/trees/ParseTreeType.js';
import {ParseTreeVisitor} from '../syntax/ParseTreeVisitor.js';
import {VAR} from '../syntax/TokenType.js';
import {assert} from '../util/assert.js';
// TODO: Update once destructuring has been refactored.
// TODO: Add entry more entry points:
// for..in statment
// for statement
/**
* Gets the identifiers bound in {@code tree}. The tree should be a block
* statement. This means if {@code tree} is:
*
* <pre>
* { function f(x) { var y; } }
* </pre>
*
* Then only {@code "f"} is bound; {@code "x"} and {@code "y"} are bound in
* the separate lexical scope of {@code f}. Note that only const/let bound
* variables (such as {@code "f"} in this example) are returned. Variables
* declared with "var" are only returned when {@code includeFunctionScope} is
* set to true.
*
* If {@code tree} was instead:
* <pre>
* { var z = function f(x) { var y; }; }
* </pre>
*
* Then only {@code "z"} is bound
*
* @param {Block} tree
* @param {boolean=} includeFunctionScope
* @return {Object}
*/
export function variablesInBlock(tree, includeFunctionScope) {
var binder = new VariableBinder(includeFunctionScope, tree);
binder.visitAny(tree);
return binder.identifiers_;
};
/**
* Gets the identifiers bound in the context of a function,
* {@code tree}, other than the function name itself. For example, if
* {@code tree} is:
*
* <pre>
* function f(x) { var y; f(); }
* </pre>
*
* Then a set containing only {@code "x"} and {@code "y"} is returned. Note
* that we treat {@code "f"} as free in the body of {@code f}, because
* AlphaRenamer uses this fact to determine if the function name is shadowed
* by another name in the body of the function.
*
* <p>Only identifiers that are bound <em>throughout</em> the
* specified tree are returned, for example:
*
* <pre>
* function f() {
* try {
* } catch (x) {
* function g(y) { }
* }
* }
* </pre>
*
* Reports nothing as being bound, because {@code "x"} is only bound in the
* scope of the catch block; {@code "g"} is let bound to the catch block, and
* {@code "y"} is only bound in the scope of {@code g}.
*
* <p>{@code "arguments"} is only reported as bound if it is
* explicitly bound in the function. If it is not explicitly bound,
* {@code "arguments"} is implicitly bound during function
* invocation.
*
* @param {FunctionDeclaration} tree
* @return {Object}
*/
export function variablesInFunction(tree) {
var binder = new VariableBinder(true, tree.functionBody);
binder.bindVariablesInFunction_(tree);
return binder.identifiers_;
};
/**
* Finds the identifiers that are bound in a given scope. Identifiers
* can be bound by function declarations, formal parameter lists,
* variable declarations, and catch headers.
*/
export class VariableBinder extends ParseTreeVisitor {
/**
* @param {boolean} inFunctionScope
* @param {Block=} scope
*/
constructor(includeFunctionScope, scope) {
super();
// Should we include:
// * all "var" declarations
// * all block scoped declarations occurring in the top level function
// block.
this.includeFunctionScope_ = includeFunctionScope;
// Block within which we are looking for declarations:
// * block scoped declaration occurring in this block.
// If function != null this refers to the top level function block.
this.scope_ = scope || null;
// Block currently being processed
this.block_ = null;
this.identifiers_ = Object.create(null);
}
/** @param {FunctionDeclaration} tree */
bindVariablesInFunction_(tree) {
var parameters = tree.formalParameterList.parameters;
for (var i = 0; i < parameters.length; i++) {
this.bindParameter_(parameters[i]);
}
this.visitAny(tree.functionBody);
}
// TODO(arv): This is where we should do the binding but I need to refactor
// destructuring first.
// visitBindingIdentifier(tree) {
//
// }
/** @param {Block} tree */
visitBlock(tree) {
// Save and set current block
var parentBlock = this.block_;
this.block_ = tree;
// visit the statements
this.visitList(tree.statements);
// restore current block
this.block_ = parentBlock;
}
visitFunctionDeclaration(tree) {
// functions follow the binding rules of 'let'
if (this.block_ == this.scope_)
this.bind_(tree.name.identifierToken);
}
visitFunctionExpression(tree) {
// We don't recurse into function bodies, because they create
// their own lexical scope.
}
/** @param {VariableDeclarationList} tree */
visitVariableDeclarationList(tree) {
// "var" variables are bound if we are scanning the whole function only
// "let/const" are bound if (we are scanning block scope or function) AND
// the scope currently processed is the scope we care about
// (either the block scope being scanned or the top level function scope)
if ((tree.declarationType == VAR && this.includeFunctionScope_) ||
(tree.declarationType != VAR && this.block_ == this.scope_)) {
// declare the variables
super.visitVariableDeclarationList(tree);
} else {
// skipping let/const declarations in nested blocks
var decls = tree.declarations;
for (var i = 0; i < decls.length; i++) {
this.visitAny(decls[i].initializer);
}
}
}
/** @param {VariableDeclaration} tree */
visitVariableDeclaration(tree) {
this.bindVariableDeclaration_(tree.lvalue);
super.visitVariableDeclaration(tree);
}
/** @param {IdentifierToken} identifier */
bind_(identifier) {
assert(typeof identifier.value == 'string');
this.identifiers_[identifier.value] = true;
}
/** @param {ParseTree} parameter */
bindParameter_(parameter) {
if (parameter.isRestParameter()) {
this.bind_(parameter.identifier);
} else {
// Formal parameters are otherwise like variable
// declarations--identifier expressions and patterns
this.bindVariableDeclaration_(parameter.binding);
}
}
/** @param {ParseTree} parameter */
bindVariableDeclaration_(tree) {
// TODO(arv): This should just visit all the BindingIdentifiers once
// destructuring has been refactored.
switch (tree.type) {
case BINDING_IDENTIFIER:
this.bind_(tree.identifierToken);
break;
case ARRAY_PATTERN:
var elements = tree.elements;
for (var i = 0; i < elements.length; i++) {
this.bindVariableDeclaration_(elements[i]);
}
break;
case SPREAD_PATTERN_ELEMENT:
this.bindVariableDeclaration_(tree.lvalue);
break;
case OBJECT_PATTERN:
var fields = tree.fields;
for (var i = 0; i < fields.length; i++) {
this.bindVariableDeclaration_(fields[i]);
}
break;
case OBJECT_PATTERN_FIELD:
var field = tree;
if (field.element == null) {
this.bind_(field.name);
} else {
this.bindVariableDeclaration_(field.element);
}
break;
case PAREN_EXPRESSION:
this.bindVariableDeclaration_(tree.expression);
break;
default:
throw new Error('unreachable');
}
}
}
|
rwaldron/traceur-compiler
|
src/semantics/VariableBinder.js
|
JavaScript
|
apache-2.0
| 7,968
|
/*
* Copyright (c) 2010-2013 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.schema.util;
import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.bind.JAXBException;
import com.evolveum.midpoint.prism.impl.util.JaxbTestUtil;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.MidPointPrismContextFactory;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
/**
* @author Pavol Mederly
*
*/
@Deprecated
public class JAXBUtilTest {
@BeforeSuite
public void setup() throws SchemaException, SAXException, IOException {
PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY);
}
@Test
public void testUnmarshallerUtf() throws JAXBException, SchemaException, FileNotFoundException {
// GIVEN
UserType user = JaxbTestUtil.getInstance().unmarshalElement(new File("src/test/resources/util/user-utf8.xml"), UserType.class)
.getValue();
// WHEN
PolyStringType fullName = user.getFullName();
// THEN
assertTrue("National characters incorrectly decoded", "Jožko Nováčik".equals(fullName.getOrig()));
}
@Test
public void testUnmarshallerIso88592() throws JAXBException, SchemaException, FileNotFoundException {
// GIVEN
UserType user = JaxbTestUtil.getInstance().unmarshalElement(new File("src/test/resources/util/user-8859-2.xml"),UserType.class)
.getValue();
// WHEN
PolyStringType fullname = user.getFullName();
// THEN
assertTrue("National characters incorrectly decoded", "Jožko Nováčik".equals(fullname.getOrig()));
}
@Test
public void testUnmarshallerStringUtf8() throws JAXBException, SchemaException {
// GIVEN
String s = "<?xml version='1.0' encoding='utf-8'?> " +
"<user oid='deadbeef-c001-f00d-1111-222233330001'" +
" xmlns:t='http://prism.evolveum.com/xml/ns/public/types-3'" +
" xmlns='http://midpoint.evolveum.com/xml/ns/public/common/common-3'>" +
" <fullName><t:orig>Jožko Nováčik</t:orig><t:norm>jozko novacik</t:norm></fullName>" +
"</user>";
UserType user = JaxbTestUtil.getInstance().unmarshalElement(s, UserType.class).getValue();
// WHEN
PolyStringType fullname = user.getFullName();
// THEN
assertTrue("Diacritics correctly decoded", "Jožko Nováčik".equals(fullname.getOrig()));
}
@Test
public void testUnmarshallerStringIso88592() throws JAXBException, SchemaException {
// GIVEN
String s = "<?xml version='1.0' encoding='iso-8859-2'?> " +
"<user oid='deadbeef-c001-f00d-1111-222233330001'" +
" xmlns:t='http://prism.evolveum.com/xml/ns/public/types-3'" +
" xmlns='http://midpoint.evolveum.com/xml/ns/public/common/common-3'>" +
" <fullName><t:orig>Jožko Nováčik</t:orig><t:norm>jozko novacik</t:norm></fullName>" +
"</user>";
UserType user = JaxbTestUtil.getInstance().unmarshalElement(s, UserType.class).getValue();
// WHEN
PolyStringType fullname = user.getFullName();
// THEN
assertTrue("Diacritics correctly decoded", "Jožko Nováčik".equals(fullname.getOrig()));
}
}
|
bshp/midPoint
|
infra/schema/src/test/java/com/evolveum/midpoint/schema/util/JAXBUtilTest.java
|
Java
|
apache-2.0
| 4,090
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Fri Aug 08 17:46:28 CEST 2003 -->
<TITLE>
Spring Framework: Class JndiTemplateEditor
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/JndiTemplateEditor.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../com/interface21/jndi/JndiTemplate.html"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="JndiTemplateEditor.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: INNER | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
com.interface21.jndi</FONT>
<BR>
Class JndiTemplateEditor</H2>
<PRE>
java.lang.Object
|
+--java.beans.PropertyEditorSupport
|
+--<B>com.interface21.jndi.JndiTemplateEditor</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.beans.PropertyEditor</DD>
</DL>
<HR>
<DL>
<DT>public class <B>JndiTemplateEditor</B><DT>extends java.beans.PropertyEditorSupport</DL>
<P>
Properties editor for JndiTemplate objects. Allows properties-format strings to
be used to represent properties editors.
<P>
<DL>
<DT><B>Since: </B><DD>09-May-2003</DD>
<DT><B>Version: </B><DD>$Id: JndiTemplateEditor.java,v 1.1 2003/05/19 15:23:19 johnsonr Exp $</DD>
<DT><B>Author: </B><DD>Rod Johnson</DD>
</DL>
<HR>
<P>
<!-- ======== INNER CLASS SUMMARY ======== -->
<!-- =========== FIELD SUMMARY =========== -->
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../com/interface21/jndi/JndiTemplateEditor.html#JndiTemplateEditor()">JndiTemplateEditor</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Method Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../com/interface21/jndi/JndiTemplateEditor.html#setAsText(java.lang.String)">setAsText</A></B>(java.lang.String text)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.beans.PropertyEditorSupport"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class java.beans.PropertyEditorSupport</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>addPropertyChangeListener, firePropertyChange, getAsText, getCustomEditor, getJavaInitializationString, getTags, getValue, isPaintable, paintValue, removePropertyChangeListener, setValue, supportsCustomEditor</CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class java.lang.Object</B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="JndiTemplateEditor()"><!-- --></A><H3>
JndiTemplateEditor</H3>
<PRE>
public <B>JndiTemplateEditor</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Method Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="setAsText(java.lang.String)"><!-- --></A><H3>
setAsText</H3>
<PRE>
public void <B>setAsText</B>(java.lang.String text)
throws java.lang.IllegalArgumentException</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>setAsText</CODE> in class <CODE>java.beans.PropertyEditorSupport</CODE></DL>
</DD>
<DD><DL>
<DT><B>See Also: </B><DD><CODE>PropertyEditor.setAsText(java.lang.String)</CODE></DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/JndiTemplateEditor.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../com/interface21/jndi/JndiTemplate.html"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="JndiTemplateEditor.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: INNER | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<i>Rod Johnson and Spring contributors 2001-2003.</i>
</BODY>
</HTML>
|
Will1229/LearnSpring
|
spring-framework-0.9.1/docs/api/com/interface21/jndi/JndiTemplateEditor.html
|
HTML
|
apache-2.0
| 9,891
|
package me.vociegif.android.widget.easing;
public class Circ implements Easing {
@Override
public double easeOut(double time, double start, double end, double duration) {
return end * Math.sqrt(1.0 - (time = time / duration - 1.0) * time) + start;
}
@Override
public double easeIn(double time, double start, double end, double duration) {
return -end * (Math.sqrt(1.0 - (time /= duration) * time) - 1.0) + start;
}
@Override
public double easeInOut(double time, double start, double end, double duration) {
if ((time /= duration / 2) < 1)
return -end / 2.0 * (Math.sqrt(1.0 - time * time) - 1.0) + start;
return end / 2.0 * (Math.sqrt(1.0 - (time -= 2.0) * time) + 1.0) + start;
}
}
|
junchenChow/exciting-app
|
app/src/main/java/me/vociegif/android/widget/easing/Circ.java
|
Java
|
apache-2.0
| 768
|
/* Copyright 2017 LinkedIn Corp. Licensed under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package notifier
import (
"encoding/json"
"fmt"
"net/http"
"text/template"
"time"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/spf13/viper"
"go.uber.org/zap"
"github.com/linkedin/Burrow/core/protocol"
)
func fixtureHTTPNotifier() *HTTPNotifier {
module := HTTPNotifier{
Log: zap.NewNop(),
}
module.App = &protocol.ApplicationContext{}
viper.Reset()
viper.Set("notifier.test.class-name", "http")
viper.Set("notifier.test.url-open", "url_open")
viper.Set("notifier.test.url-close", "url_close")
viper.Set("notifier.test.template-open", "template_open")
viper.Set("notifier.test.template-close", "template_close")
viper.Set("notifier.test.send-close", false)
viper.Set("notifier.test.headers", map[string]string{"Token": "testtoken"})
viper.Set("notifier.test.noverify", true)
return &module
}
func TestHttpNotifier_ImplementsModule(t *testing.T) {
assert.Implements(t, (*protocol.Module)(nil), new(HTTPNotifier))
assert.Implements(t, (*Module)(nil), new(HTTPNotifier))
}
func TestHttpNotifier_Configure(t *testing.T) {
module := fixtureHTTPNotifier()
module.Configure("test", "notifier.test")
assert.NotNil(t, module.httpClient, "Expected httpClient to be set with a client object")
}
func TestHttpNotifier_Bad_Configuration(t *testing.T) {
module := fixtureHTTPNotifier()
viper.Set("notifier.test.url-open", "")
assert.Panics(t, func() { module.Configure("test", "notifier.test") }, "HTTP notifier needs a supplied email")
}
func TestHttpNotifier_StartStop(t *testing.T) {
module := fixtureHTTPNotifier()
module.Configure("test", "notifier.test")
err := module.Start()
assert.Nil(t, err, "Expected Start to return no error")
err = module.Stop()
assert.Nil(t, err, "Expected Stop to return no error")
}
func TestHttpNotifier_AcceptConsumerGroup(t *testing.T) {
module := fixtureHTTPNotifier()
module.Configure("test", "notifier.test")
// Should always return true
assert.True(t, module.AcceptConsumerGroup(&protocol.ConsumerGroupStatus{}), "Expected any status to return True")
}
// Struct that will be used for sending HTTP requests for testing
type HTTPRequest struct {
Template string
ID string
Cluster string
Group string
}
func TestHttpNotifier_Notify_Open(t *testing.T) {
// handler that validates that we get the right values
requestHandler := func(w http.ResponseWriter, r *http.Request) {
// Must get an appropriate Content-Type header
headers, ok := r.Header["Content-Type"]
assert.True(t, ok, "Expected to receive Content-Type header")
assert.Len(t, headers, 1, "Expected to receive exactly one Content-Type header")
assert.Equalf(t, "application/json", headers[0], "Expected Content-Type header to be 'application/json', not '%v'", headers[0])
tokenHeaders, ok := r.Header["Token"]
assert.True(t, ok, "Expected to receive Token header")
assert.Equalf(t, "testtoken", tokenHeaders[0], "Expected Token header to be 'testtoken', not '%v'", tokenHeaders[0])
assert.Equalf(t, "id=testidstring", r.URL.RawQuery, "Expected URL querystring to be id=testidstring, not %v", r.URL)
decoder := json.NewDecoder(r.Body)
var req HTTPRequest
err := decoder.Decode(&req)
if err != nil {
assert.Failf(t, "Failed to decode message body", "Failed to decode message body: %v", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
assert.Equalf(t, "template_open", req.Template, "Expected Template to be template_open, not %v", req.Template)
assert.Equalf(t, "testidstring", req.ID, "Expected ID to be testidstring, not %v", req.ID)
assert.Equalf(t, "testcluster", req.Cluster, "Expected Cluster to be testcluster, not %v", req.Cluster)
assert.Equalf(t, "testgroup", req.Group, "Expected Group to be testgroup, not %v", req.Group)
fmt.Fprint(w, "ok")
}
// create test server with handler
ts := httptest.NewServer(http.HandlerFunc(requestHandler))
defer ts.Close()
module := fixtureHTTPNotifier()
viper.Set("notifier.test.url-open", fmt.Sprintf("%s?id={{.ID}}", ts.URL))
// Template sends the ID, cluster, and group
module.templateOpen, _ = template.New("test").Parse("{\"template\":\"template_open\",\"id\":\"{{.ID}}\",\"cluster\":\"{{.Cluster}}\",\"group\":\"{{.Group}}\"}")
module.Configure("test", "notifier.test")
status := &protocol.ConsumerGroupStatus{
Status: protocol.StatusWarning,
Cluster: "testcluster",
Group: "testgroup",
}
module.Notify(status, "testidstring", time.Now(), false)
}
func TestHttpNotifier_Notify_Close(t *testing.T) {
// handler that validates that we get the right values
requestHandler := func(w http.ResponseWriter, r *http.Request) {
// Must get an appropriate Content-Type header
headers, ok := r.Header["Content-Type"]
assert.True(t, ok, "Expected to receive Content-Type header")
assert.Len(t, headers, 1, "Expected to receive exactly one Content-Type header")
assert.Equalf(t, "application/json", headers[0], "Expected Content-Type header to be 'application/json', not '%v'", headers[0])
tokenHeaders, ok := r.Header["Token"]
assert.True(t, ok, "Expected to receive Token header")
assert.Equalf(t, "testtoken", tokenHeaders[0], "Expected Token header to be 'testtoken', not '%v'", tokenHeaders[0])
assert.Equalf(t, "id=testidstring", r.URL.RawQuery, "Expected URL querystring to be id=testidstring, not %v", r.URL)
decoder := json.NewDecoder(r.Body)
var req HTTPRequest
err := decoder.Decode(&req)
if err != nil {
assert.Failf(t, "Failed to decode message body", "Failed to decode message body: %v", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
assert.Equalf(t, "template_close", req.Template, "Expected Template to be template_close, not %v", req.Template)
assert.Equalf(t, "testidstring", req.ID, "Expected ID to be testidstring, not %v", req.ID)
assert.Equalf(t, "testcluster", req.Cluster, "Expected Cluster to be testcluster, not %v", req.Cluster)
assert.Equalf(t, "testgroup", req.Group, "Expected Group to be testgroup, not %v", req.Group)
fmt.Fprint(w, "ok")
}
// create test server with handler
ts := httptest.NewServer(http.HandlerFunc(requestHandler))
defer ts.Close()
module := fixtureHTTPNotifier()
viper.Set("notifier.test.send-close", true)
viper.Set("notifier.test.url-close", fmt.Sprintf("%s?id={{.ID}}", ts.URL))
// Template sends the ID, cluster, and group
module.templateClose, _ = template.New("test").Parse("{\"template\":\"template_close\",\"id\":\"{{.ID}}\",\"cluster\":\"{{.Cluster}}\",\"group\":\"{{.Group}}\"}")
module.Configure("test", "notifier.test")
status := &protocol.ConsumerGroupStatus{
Status: protocol.StatusWarning,
Cluster: "testcluster",
Group: "testgroup",
}
module.Notify(status, "testidstring", time.Now(), true)
}
|
linkedin/Burrow
|
core/internal/notifier/http_test.go
|
GO
|
apache-2.0
| 7,282
|
package com.google.maps.metrics;
import io.opencensus.stats.Aggregation;
import io.opencensus.stats.Aggregation.Count;
import io.opencensus.stats.Aggregation.Distribution;
import io.opencensus.stats.BucketBoundaries;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.stats.Stats;
import io.opencensus.stats.View;
import io.opencensus.stats.ViewManager;
import io.opencensus.tags.TagKey;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/*
* OpenCensus metrics which are measured for every request.
*/
public final class OpenCensusMetrics {
private OpenCensusMetrics() {}
public static final class Tags {
private Tags() {}
public static final TagKey REQUEST_NAME = TagKey.create("request_name");
public static final TagKey HTTP_CODE = TagKey.create("http_code");
public static final TagKey API_STATUS = TagKey.create("api_status");
}
public static final class Measures {
private Measures() {}
public static final MeasureLong LATENCY =
MeasureLong.create(
"maps.googleapis.com/measure/client/latency",
"Total time between library method called and results returned",
"ms");
public static final MeasureLong NETWORK_LATENCY =
MeasureLong.create(
"maps.googleapis.com/measure/client/network_latency",
"Network time inside the library",
"ms");
public static final MeasureLong RETRY_COUNT =
MeasureLong.create(
"maps.googleapis.com/measure/client/retry_count",
"How many times any request was retried",
"1");
}
private static final class Aggregations {
private Aggregations() {}
private static final Aggregation COUNT = Count.create();
private static final Aggregation DISTRIBUTION_INTEGERS_10 =
Distribution.create(
BucketBoundaries.create(
Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)));
// every bucket is ~25% bigger = 20 * 2^(N/3)
private static final Aggregation DISTRIBUTION_LATENCY =
Distribution.create(
BucketBoundaries.create(
Arrays.asList(
0.0, 20.0, 25.2, 31.7, 40.0, 50.4, 63.5, 80.0, 100.8, 127.0, 160.0, 201.6,
254.0, 320.0, 403.2, 508.0, 640.0, 806.3, 1015.9, 1280.0, 1612.7, 2031.9,
2560.0, 3225.4, 4063.7)));
}
public static final class Views {
private Views() {}
private static final List<TagKey> fields =
tags(Tags.REQUEST_NAME, Tags.HTTP_CODE, Tags.API_STATUS);
public static final View REQUEST_COUNT =
View.create(
View.Name.create("maps.googleapis.com/client/request_count"),
"Request counts",
Measures.LATENCY,
Aggregations.COUNT,
fields);
public static final View REQUEST_LATENCY =
View.create(
View.Name.create("maps.googleapis.com/client/request_latency"),
"Latency in msecs",
Measures.LATENCY,
Aggregations.DISTRIBUTION_LATENCY,
fields);
public static final View NETWORK_LATENCY =
View.create(
View.Name.create("maps.googleapis.com/client/network_latency"),
"Network latency in msecs (internal)",
Measures.NETWORK_LATENCY,
Aggregations.DISTRIBUTION_LATENCY,
fields);
public static final View RETRY_COUNT =
View.create(
View.Name.create("maps.googleapis.com/client/retry_count"),
"Retries per request",
Measures.RETRY_COUNT,
Aggregations.DISTRIBUTION_INTEGERS_10,
fields);
}
public static void registerAllViews() {
registerAllViews(Stats.getViewManager());
}
public static void registerAllViews(ViewManager viewManager) {
View[] views_to_register =
new View[] {
Views.REQUEST_COUNT, Views.REQUEST_LATENCY, Views.NETWORK_LATENCY, Views.RETRY_COUNT
};
for (View view : views_to_register) {
viewManager.registerView(view);
}
}
private static List<TagKey> tags(TagKey... items) {
return Collections.unmodifiableList(Arrays.asList(items));
}
}
|
googlemaps/google-maps-services-java
|
src/main/java/com/google/maps/metrics/OpenCensusMetrics.java
|
Java
|
apache-2.0
| 4,259
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace DataTableFormatters
{
internal class MonospacedDataTableFormatter : BaseDataTableFormatter
{
private readonly IFormatConfiguration[] _options;
public MonospacedDataTableFormatter(IFormatConfiguration[] options)
{
_options = options;
}
private const string UpperLeftCorner = "+";
private const string UpperBorder = "-";
private const string UpperSplit = "+";
private const string UpperRightCorner = "+";
private const string MiddleLeftCorner = "+";
private const string MiddleBorder = "-";
private const string MiddleSplit = "+";
private const string MiddleRightCorner = "+";
private const string LowerLeftCorner = "+";
private const string LowerBorder = "-";
private const string LowerSplit = "+";
private const string LowerRightCorner = "+";
private const string LeftBorder = "|";
private const string Split = "|";
private const string RightBorder = "|";
protected override IEnumerable<string> GetStringRepresentation(DataTable dataTable)
{
if (dataTable == null)
throw new ArgumentNullException("dataTable");
var columnWidths = dataTable.DataColumns().Select(ColumnMaxElementLength).ToList();
return Concatenate(
UpperHorizontalLine(columnWidths),
Headers(columnWidths),
MiddleHorizontalLine(columnWidths),
Contents(dataTable.DataRows(), columnWidths),
LowerHorizontalLine(columnWidths));
}
private static ColumnAndWidth ColumnMaxElementLength(DataColumn column)
{
int? maxLength = column.Table.DataRows()
.Select(row => (int?)row[column].ToString().Length)
.Max();
return new ColumnAndWidth(
column,
Math.Max(
column.ColumnName.Length,
maxLength ?? 0));
}
private static IEnumerable<string> UpperHorizontalLine(IList<ColumnAndWidth> columnWidths)
{
return Interlace(
UpperLeftCorner + UpperBorder,
columnWidths.Select(x => new string(UpperBorder.Single(), x.Width)),
UpperBorder + UpperSplit + UpperBorder,
UpperBorder + UpperRightCorner + Environment.NewLine);
}
private static IEnumerable<string> MiddleHorizontalLine(IList<ColumnAndWidth> columnWidths)
{
return Interlace(
MiddleLeftCorner + MiddleBorder,
columnWidths.Select(x => new string(MiddleBorder.Single(), x.Width)),
MiddleBorder + MiddleSplit + MiddleBorder,
MiddleBorder + MiddleRightCorner + Environment.NewLine);
}
private static IEnumerable<string> LowerHorizontalLine(IList<ColumnAndWidth> columnWidths)
{
return Interlace(
LowerLeftCorner + LowerBorder,
columnWidths.Select(x => new string(LowerBorder.Single(), x.Width)),
LowerBorder + LowerSplit + LowerBorder,
LowerBorder + LowerRightCorner + Environment.NewLine);
}
private IEnumerable<string> Headers(IList<ColumnAndWidth> columnWidths)
{
return Interlace(
LeftBorder + " ",
columnWidths.Select(x =>
{
var alignedColumnName = Align(x.ColumnName, x.ColumnName, x.Width);
return alignedColumnName;
}),
" " + Split + " ",
" " + RightBorder + Environment.NewLine);
}
private string Align(string columnName, string content, int width)
{
return _options.OfType<RightAlign>().Any(x => x.ColumnName == columnName)
? content.PadLeft(width)
: content.PadRight(width);
}
private IEnumerable<string> Contents(IEnumerable<DataRow> rows, IList<ColumnAndWidth> columnWidths)
{
return rows.SelectMany(row => Row(columnWidths, row));
}
private IEnumerable<string> Row(IList<ColumnAndWidth> columnWidths, DataRow row)
{
return Interlace(
LeftBorder + " ",
columnWidths.Select((x, i) => Cell(row, i, x)),
" " + Split + " ",
" " + RightBorder + Environment.NewLine);
}
private string Cell(DataRow row, int index, ColumnAndWidth columnWidth)
{
string stringRepresentation;
if (row[index] == DBNull.Value)
{
stringRepresentation = "NULL";
}
else
{
var format = _options.OfType<CustomFormat>().FirstOrDefault(y => y.ColumnName == columnWidth.ColumnName);
var formatString = format == null ? "{0}" : "{0:" + format.FormatString + "}";
stringRepresentation = string.Format(formatString, row[index]);
}
string alignedContent = Align(columnWidth.ColumnName, stringRepresentation, columnWidth.Width);
return alignedContent;
}
private static IEnumerable<T> Interlace<T>(T prefix, IEnumerable<T> list, T separator, T suffix)
{
yield return prefix;
if (list.Any())
{
yield return list.First();
foreach (T item in list.Skip(1))
{
yield return separator;
yield return item;
}
}
yield return suffix;
}
private static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists)
{
return lists.SelectMany(x => x);
}
private class ColumnAndWidth
{
public ColumnAndWidth(DataColumn column, int width)
{
ColumnName = column.ColumnName;
Width = width;
}
public string ColumnName { get; set; }
public int Width { get; set; }
}
}
}
|
DataTableFormatters/DataTableFormatters
|
src/DataTableFormatters/MonospacedDataTableFormatter.cs
|
C#
|
apache-2.0
| 6,340
|
<html><body>
<style>
body, h1, h2, h3, div, span, p, pre, a {
margin: 0;
padding: 0;
border: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
body {
font-size: 13px;
padding: 1em;
}
h1 {
font-size: 26px;
margin-bottom: 1em;
}
h2 {
font-size: 24px;
margin-bottom: 1em;
}
h3 {
font-size: 20px;
margin-bottom: 1em;
margin-top: 1em;
}
pre, code {
line-height: 1.5;
font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Lucida Console', monospace;
}
pre {
margin-top: 0.5em;
}
h1, h2, h3, p {
font-family: Arial, sans serif;
}
h1, h2, h3 {
border-bottom: solid #CCC 1px;
}
.toc_element {
margin-top: 0.5em;
}
.firstline {
margin-left: 2 em;
}
.method {
margin-top: 1em;
border: solid 1px #CCC;
padding: 1em;
background: #EEE;
}
.details {
font-weight: bold;
font-size: 14px;
}
</style>
<h1><a href="artifactregistry_v1beta1.html">Artifact Registry API</a> . <a href="artifactregistry_v1beta1.projects.html">projects</a> . <a href="artifactregistry_v1beta1.projects.locations.html">locations</a> . <a href="artifactregistry_v1beta1.projects.locations.repositories.html">repositories</a> . <a href="artifactregistry_v1beta1.projects.locations.repositories.packages.html">packages</a></h1>
<h2>Instance Methods</h2>
<p class="toc_element">
<code><a href="artifactregistry_v1beta1.projects.locations.repositories.packages.tags.html">tags()</a></code>
</p>
<p class="firstline">Returns the tags Resource.</p>
<p class="toc_element">
<code><a href="artifactregistry_v1beta1.projects.locations.repositories.packages.versions.html">versions()</a></code>
</p>
<p class="firstline">Returns the versions Resource.</p>
<p class="toc_element">
<code><a href="#close">close()</a></code></p>
<p class="firstline">Close httplib2 connections.</p>
<p class="toc_element">
<code><a href="#delete">delete(name, x__xgafv=None)</a></code></p>
<p class="firstline">Deletes a package and all of its versions and tags. The returned operation will complete once the package has been deleted.</p>
<p class="toc_element">
<code><a href="#get">get(name, x__xgafv=None)</a></code></p>
<p class="firstline">Gets a package.</p>
<p class="toc_element">
<code><a href="#list">list(parent, pageSize=None, pageToken=None, x__xgafv=None)</a></code></p>
<p class="firstline">Lists packages.</p>
<p class="toc_element">
<code><a href="#list_next">list_next(previous_request, previous_response)</a></code></p>
<p class="firstline">Retrieves the next page of results.</p>
<h3>Method Details</h3>
<div class="method">
<code class="details" id="close">close()</code>
<pre>Close httplib2 connections.</pre>
</div>
<div class="method">
<code class="details" id="delete">delete(name, x__xgafv=None)</code>
<pre>Deletes a package and all of its versions and tags. The returned operation will complete once the package has been deleted.
Args:
name: string, Required. The name of the package to delete. (required)
x__xgafv: string, V1 error format.
Allowed values
1 - v1 error format
2 - v2 error format
Returns:
An object of the form:
{ # This resource represents a long-running operation that is the result of a network API call.
"done": True or False, # If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.
"error": { # The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). # The error result of the operation in case of failure or cancellation.
"code": 42, # The status code, which should be an enum value of google.rpc.Code.
"details": [ # A list of messages that carry the error details. There is a common set of message types for APIs to use.
{
"a_key": "", # Properties of the object. Contains field @type with type URL.
},
],
"message": "A String", # A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
},
"metadata": { # Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.
"a_key": "", # Properties of the object. Contains field @type with type URL.
},
"name": "A String", # The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
"response": { # The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
"a_key": "", # Properties of the object. Contains field @type with type URL.
},
}</pre>
</div>
<div class="method">
<code class="details" id="get">get(name, x__xgafv=None)</code>
<pre>Gets a package.
Args:
name: string, Required. The name of the package to retrieve. (required)
x__xgafv: string, V1 error format.
Allowed values
1 - v1 error format
2 - v2 error format
Returns:
An object of the form:
{ # Packages are named collections of versions.
"createTime": "A String", # The time when the package was created.
"displayName": "A String", # The display name of the package.
"name": "A String", # The name of the package, for example: "projects/p1/locations/us-central1/repositories/repo1/packages/pkg1". If the package ID part contains slashes, the slashes are escaped.
"updateTime": "A String", # The time when the package was last updated. This includes publishing a new version of the package.
}</pre>
</div>
<div class="method">
<code class="details" id="list">list(parent, pageSize=None, pageToken=None, x__xgafv=None)</code>
<pre>Lists packages.
Args:
parent: string, Required. The name of the parent resource whose packages will be listed. (required)
pageSize: integer, The maximum number of packages to return. Maximum page size is 1,000.
pageToken: string, The next_page_token value returned from a previous list request, if any.
x__xgafv: string, V1 error format.
Allowed values
1 - v1 error format
2 - v2 error format
Returns:
An object of the form:
{ # The response from listing packages.
"nextPageToken": "A String", # The token to retrieve the next page of packages, or empty if there are no more packages to return.
"packages": [ # The packages returned.
{ # Packages are named collections of versions.
"createTime": "A String", # The time when the package was created.
"displayName": "A String", # The display name of the package.
"name": "A String", # The name of the package, for example: "projects/p1/locations/us-central1/repositories/repo1/packages/pkg1". If the package ID part contains slashes, the slashes are escaped.
"updateTime": "A String", # The time when the package was last updated. This includes publishing a new version of the package.
},
],
}</pre>
</div>
<div class="method">
<code class="details" id="list_next">list_next(previous_request, previous_response)</code>
<pre>Retrieves the next page of results.
Args:
previous_request: The request for the previous page. (required)
previous_response: The response from the request for the previous page. (required)
Returns:
A request object that you can call 'execute()' on to request the next
page. Returns None if there are no more items in the collection.
</pre>
</div>
</body></html>
|
googleapis/google-api-python-client
|
docs/dyn/artifactregistry_v1beta1.projects.locations.repositories.packages.html
|
HTML
|
apache-2.0
| 8,857
|
/*
* Copyright (C) 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Modified from SWT's org.eclipse.swt.opengl.GLCanvas with license:
/*******************************************************************************
* Copyright (c) 2000, 2016 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.google.gapid.glcanvas;
import static org.lwjgl.system.MemoryUtil.memAddress;
import org.eclipse.swt.SWT;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.lwjgl.opengl.WGL;
import org.lwjgl.opengl.WGLARBMultisample;
import org.lwjgl.opengl.WGLARBPixelFormat;
import org.lwjgl.system.JNI;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.system.windows.GDI32;
import org.lwjgl.system.windows.PIXELFORMATDESCRIPTOR;
import org.lwjgl.system.windows.User32;
import java.nio.IntBuffer;
public abstract class GlCanvas extends Canvas {
private static final String USE_OWNDC_KEY = "org.eclipse.swt.internal.win32.useOwnDC";
private final long context;
private final boolean initialized;
public GlCanvas(Composite parent, int style) {
super(parent, checkStyle(parent, style));
Canvas dummy = new Canvas(parent, style);
parent.getDisplay().setData(USE_OWNDC_KEY, Boolean.FALSE);
Context dummyContext = new Context(dummy.handle).createSimplePixelFormat();
if (dummyContext == null) {
context = 0;
initialized = false;
return;
}
Context actualContext;
if (dummyContext.createPixelFormat()) {
actualContext = new Context(handle).setPixelFormat(dummyContext.pixelFormat);
} else {
actualContext = new Context(handle).createSimplePixelFormat();
}
if (actualContext == null) {
context = 0;
initialized = false;
} else {
context = actualContext.context;
initialized = true;
}
dummyContext.release();
dummy.dispose();
if (initialized) {
addListener(SWT.Dispose, e -> {
terminate();
WGL.wglDeleteContext(context);
});
}
}
private static int checkStyle(Composite parent, int style) {
if (parent != null) {
if (!OS.IsWinCE && OS.WIN32_VERSION >= OS.VERSION(6, 0)) {
parent.getDisplay().setData(USE_OWNDC_KEY, Boolean.TRUE);
}
}
return style;
}
public boolean isOpenGL() {
return initialized;
}
public void setCurrent () {
checkWidget();
if (!initialized) {
return;
}
long dc = User32.GetDC(handle);
WGL.wglMakeCurrent(dc, context);
User32.ReleaseDC(handle, dc);
}
public void swapBuffers () {
checkWidget();
if (!initialized) {
return;
}
long dc = User32.GetDC(handle);
GDI32.SwapBuffers(dc);
User32.ReleaseDC(handle, dc);
}
/** Override to perform GL cleanup handling. */
protected abstract void terminate();
private static class Context {
public final long handle;
public final long dc;
public int pixelFormat;
public long context;
public Context(long handle) {
this.handle = handle;
this.dc = User32.GetDC(handle);
}
public Context createSimplePixelFormat() {
PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.calloc();
pfd.nSize((short)PIXELFORMATDESCRIPTOR.SIZEOF);
pfd.nVersion((short)1);
pfd.dwFlags(GDI32.PFD_DRAW_TO_WINDOW | GDI32.PFD_SUPPORT_OPENGL | GDI32.PFD_DOUBLEBUFFER);
pfd.dwLayerMask(GDI32.PFD_MAIN_PLANE);
pfd.iPixelType(GDI32.PFD_TYPE_RGBA);
pfd.cRedBits((byte)8);
pfd.cGreenBits((byte)8);
pfd.cBlueBits((byte)8);
pfd.cDepthBits((byte)24);
pixelFormat = GDI32.ChoosePixelFormat(dc, pfd);
if (pixelFormat == 0 || !GDI32.SetPixelFormat(dc, pixelFormat, pfd)) {
release();
return null;
}
return createContext();
}
public Context setPixelFormat(int format) {
this.pixelFormat = format;
PIXELFORMATDESCRIPTOR pfd = PIXELFORMATDESCRIPTOR.calloc();
pfd.nSize((short)PIXELFORMATDESCRIPTOR.SIZEOF);
pfd.nVersion((short)1);
pfd.dwFlags(GDI32.PFD_DRAW_TO_WINDOW | GDI32.PFD_SUPPORT_OPENGL | GDI32.PFD_DOUBLEBUFFER);
pfd.dwLayerMask(GDI32.PFD_MAIN_PLANE);
pfd.iPixelType(GDI32.PFD_TYPE_RGBA);
pfd.cRedBits((byte)8);
pfd.cGreenBits((byte)8);
pfd.cBlueBits((byte)8);
pfd.cDepthBits((byte)24);
if (!GDI32.SetPixelFormat(dc, pixelFormat, pfd)) {
release();
return null;
}
return createContext();
}
private Context createContext() {
context = WGL.wglCreateContext(dc);
if (context == 0 || !WGL.wglMakeCurrent(dc, context)) {
User32.ReleaseDC(handle, dc);
return null;
}
return this;
}
public boolean createPixelFormat() {
long chooseFormat = WGL.wglGetProcAddress("wglChoosePixelFormatARB");
if (chooseFormat == 0) {
chooseFormat = WGL.wglGetProcAddress("wglChoosePixelFormatEXT");
if (chooseFormat == 0) {
return false;
}
}
IntBuffer buf = MemoryStack.stackCallocInt(20);
long bufAddr = memAddress(buf);
set(buf, WGLARBPixelFormat.WGL_DRAW_TO_WINDOW_ARB, 1);
set(buf, WGLARBPixelFormat.WGL_SUPPORT_OPENGL_ARB, 1);
set(buf, WGLARBPixelFormat.WGL_ACCELERATION_ARB, WGLARBPixelFormat.WGL_FULL_ACCELERATION_ARB);
set(buf, WGLARBPixelFormat.WGL_PIXEL_TYPE_ARB, WGLARBPixelFormat.WGL_TYPE_RGBA_ARB);
set(buf, WGLARBPixelFormat.WGL_COLOR_BITS_ARB, 24);
set(buf, WGLARBPixelFormat.WGL_DEPTH_BITS_ARB, 24);
set(buf, WGLARBPixelFormat.WGL_DOUBLE_BUFFER_ARB, 1);
set(buf, WGLARBMultisample.WGL_SAMPLE_BUFFERS_ARB, 1);
set(buf, WGLARBMultisample.WGL_SAMPLES_ARB, 4);
set(buf, 0, 0);
long result = MemoryStack.nstackMalloc(4, 4 * 2);
if (JNI.callPPPPPI(chooseFormat, dc, bufAddr, 0L, 1, result + 4, result) != 1 ||
MemoryUtil.memGetInt(result) == 0) {
return false;
}
pixelFormat = MemoryUtil.memGetInt(result + 4);
return true;
}
private static void set(IntBuffer attrib, int name, int value) {
attrib.put(name).put(value);
}
public void release() {
User32.ReleaseDC(handle, dc);
if (context != 0) {
WGL.wglDeleteContext(context);
}
}
}
}
|
baldwinn860/gapid
|
gapic/src/platform/windows/com/google/gapid/glcanvas/GlCanvas.java
|
Java
|
apache-2.0
| 7,294
|
/* Module support implementation */
#include "Python.h"
#define FLAG_SIZE_T 1
typedef double va_double;
static PyObject *va_build_value(const char *, va_list, int);
static PyObject **va_build_stack(PyObject **small_stack, Py_ssize_t small_stack_len, const char *, va_list, int, Py_ssize_t*);
/* Package context -- the full module name for package imports */
const char *_Py_PackageContext = NULL;
int
_Py_convert_optional_to_ssize_t(PyObject *obj, void *result)
{
Py_ssize_t limit;
if (obj == Py_None) {
return 1;
}
else if (PyIndex_Check(obj)) {
limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError);
if (limit == -1 && PyErr_Occurred()) {
return 0;
}
}
else {
PyErr_Format(PyExc_TypeError,
"argument should be integer or None, not '%.200s'",
Py_TYPE(obj)->tp_name);
return 0;
}
*((Py_ssize_t *)result) = limit;
return 1;
}
/* Helper for mkvalue() to scan the length of a format */
static Py_ssize_t
countformat(const char *format, char endchar)
{
Py_ssize_t count = 0;
int level = 0;
while (level > 0 || *format != endchar) {
switch (*format) {
case '\0':
/* Premature end */
PyErr_SetString(PyExc_SystemError,
"unmatched paren in format");
return -1;
case '(':
case '[':
case '{':
if (level == 0) {
count++;
}
level++;
break;
case ')':
case ']':
case '}':
level--;
break;
case '#':
case '&':
case ',':
case ':':
case ' ':
case '\t':
break;
default:
if (level == 0) {
count++;
}
}
format++;
}
return count;
}
/* Generic function to create a value -- the inverse of getargs() */
/* After an original idea and first implementation by Steven Miale */
static PyObject *do_mktuple(const char**, va_list *, char, Py_ssize_t, int);
static int do_mkstack(PyObject **, const char**, va_list *, char, Py_ssize_t, int);
static PyObject *do_mklist(const char**, va_list *, char, Py_ssize_t, int);
static PyObject *do_mkdict(const char**, va_list *, char, Py_ssize_t, int);
static PyObject *do_mkvalue(const char**, va_list *, int);
static void
do_ignore(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags)
{
PyObject *v;
Py_ssize_t i;
assert(PyErr_Occurred());
v = PyTuple_New(n);
for (i = 0; i < n; i++) {
PyObject *exception, *value, *tb, *w;
PyErr_Fetch(&exception, &value, &tb);
w = do_mkvalue(p_format, p_va, flags);
PyErr_Restore(exception, value, tb);
if (w != NULL) {
if (v != NULL) {
PyTuple_SET_ITEM(v, i, w);
}
else {
Py_DECREF(w);
}
}
}
Py_XDECREF(v);
if (**p_format != endchar) {
PyErr_SetString(PyExc_SystemError,
"Unmatched paren in format");
return;
}
if (endchar) {
++*p_format;
}
}
static PyObject *
do_mkdict(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags)
{
PyObject *d;
Py_ssize_t i;
if (n < 0)
return NULL;
if (n % 2) {
PyErr_SetString(PyExc_SystemError,
"Bad dict format");
do_ignore(p_format, p_va, endchar, n, flags);
return NULL;
}
/* Note that we can't bail immediately on error as this will leak
refcounts on any 'N' arguments. */
if ((d = PyDict_New()) == NULL) {
do_ignore(p_format, p_va, endchar, n, flags);
return NULL;
}
for (i = 0; i < n; i+= 2) {
PyObject *k, *v;
k = do_mkvalue(p_format, p_va, flags);
if (k == NULL) {
do_ignore(p_format, p_va, endchar, n - i - 1, flags);
Py_DECREF(d);
return NULL;
}
v = do_mkvalue(p_format, p_va, flags);
if (v == NULL || PyDict_SetItem(d, k, v) < 0) {
do_ignore(p_format, p_va, endchar, n - i - 2, flags);
Py_DECREF(k);
Py_XDECREF(v);
Py_DECREF(d);
return NULL;
}
Py_DECREF(k);
Py_DECREF(v);
}
if (**p_format != endchar) {
Py_DECREF(d);
PyErr_SetString(PyExc_SystemError,
"Unmatched paren in format");
return NULL;
}
if (endchar)
++*p_format;
return d;
}
static PyObject *
do_mklist(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags)
{
PyObject *v;
Py_ssize_t i;
if (n < 0)
return NULL;
/* Note that we can't bail immediately on error as this will leak
refcounts on any 'N' arguments. */
v = PyList_New(n);
if (v == NULL) {
do_ignore(p_format, p_va, endchar, n, flags);
return NULL;
}
for (i = 0; i < n; i++) {
PyObject *w = do_mkvalue(p_format, p_va, flags);
if (w == NULL) {
do_ignore(p_format, p_va, endchar, n - i - 1, flags);
Py_DECREF(v);
return NULL;
}
PyList_SET_ITEM(v, i, w);
}
if (**p_format != endchar) {
Py_DECREF(v);
PyErr_SetString(PyExc_SystemError,
"Unmatched paren in format");
return NULL;
}
if (endchar)
++*p_format;
return v;
}
static int
do_mkstack(PyObject **stack, const char **p_format, va_list *p_va,
char endchar, Py_ssize_t n, int flags)
{
Py_ssize_t i;
if (n < 0) {
return -1;
}
/* Note that we can't bail immediately on error as this will leak
refcounts on any 'N' arguments. */
for (i = 0; i < n; i++) {
PyObject *w = do_mkvalue(p_format, p_va, flags);
if (w == NULL) {
do_ignore(p_format, p_va, endchar, n - i - 1, flags);
goto error;
}
stack[i] = w;
}
if (**p_format != endchar) {
PyErr_SetString(PyExc_SystemError,
"Unmatched paren in format");
goto error;
}
if (endchar) {
++*p_format;
}
return 0;
error:
n = i;
for (i=0; i < n; i++) {
Py_DECREF(stack[i]);
}
return -1;
}
static PyObject *
do_mktuple(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags)
{
PyObject *v;
Py_ssize_t i;
if (n < 0)
return NULL;
/* Note that we can't bail immediately on error as this will leak
refcounts on any 'N' arguments. */
if ((v = PyTuple_New(n)) == NULL) {
do_ignore(p_format, p_va, endchar, n, flags);
return NULL;
}
for (i = 0; i < n; i++) {
PyObject *w = do_mkvalue(p_format, p_va, flags);
if (w == NULL) {
do_ignore(p_format, p_va, endchar, n - i - 1, flags);
Py_DECREF(v);
return NULL;
}
PyTuple_SET_ITEM(v, i, w);
}
if (**p_format != endchar) {
Py_DECREF(v);
PyErr_SetString(PyExc_SystemError,
"Unmatched paren in format");
return NULL;
}
if (endchar)
++*p_format;
return v;
}
static PyObject *
do_mkvalue(const char **p_format, va_list *p_va, int flags)
{
for (;;) {
switch (*(*p_format)++) {
case '(':
return do_mktuple(p_format, p_va, ')',
countformat(*p_format, ')'), flags);
case '[':
return do_mklist(p_format, p_va, ']',
countformat(*p_format, ']'), flags);
case '{':
return do_mkdict(p_format, p_va, '}',
countformat(*p_format, '}'), flags);
case 'b':
case 'B':
case 'h':
case 'i':
return PyLong_FromLong((long)va_arg(*p_va, int));
case 'H':
return PyLong_FromLong((long)va_arg(*p_va, unsigned int));
case 'I':
{
unsigned int n;
n = va_arg(*p_va, unsigned int);
return PyLong_FromUnsignedLong(n);
}
case 'n':
#if SIZEOF_SIZE_T!=SIZEOF_LONG
return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t));
#endif
/* Fall through from 'n' to 'l' if Py_ssize_t is long */
case 'l':
return PyLong_FromLong(va_arg(*p_va, long));
case 'k':
{
unsigned long n;
n = va_arg(*p_va, unsigned long);
return PyLong_FromUnsignedLong(n);
}
case 'L':
return PyLong_FromLongLong((long long)va_arg(*p_va, long long));
case 'K':
return PyLong_FromUnsignedLongLong((long long)va_arg(*p_va, unsigned long long));
case 'u':
{
PyObject *v;
Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *);
Py_ssize_t n;
if (**p_format == '#') {
++*p_format;
if (flags & FLAG_SIZE_T)
n = va_arg(*p_va, Py_ssize_t);
else {
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"PY_SSIZE_T_CLEAN will be required for '#' formats", 1)) {
return NULL;
}
n = va_arg(*p_va, int);
}
}
else
n = -1;
if (u == NULL) {
v = Py_None;
Py_INCREF(v);
}
else {
if (n < 0)
n = wcslen(u);
v = PyUnicode_FromWideChar(u, n);
}
return v;
}
case 'f':
case 'd':
return PyFloat_FromDouble(
(double)va_arg(*p_va, va_double));
case 'D':
return PyComplex_FromCComplex(
*((Py_complex *)va_arg(*p_va, Py_complex *)));
case 'c':
{
char p[1];
p[0] = (char)va_arg(*p_va, int);
return PyBytes_FromStringAndSize(p, 1);
}
case 'C':
{
int i = va_arg(*p_va, int);
return PyUnicode_FromOrdinal(i);
}
case 's':
case 'z':
case 'U': /* XXX deprecated alias */
{
PyObject *v;
const char *str = va_arg(*p_va, const char *);
Py_ssize_t n;
if (**p_format == '#') {
++*p_format;
if (flags & FLAG_SIZE_T)
n = va_arg(*p_va, Py_ssize_t);
else {
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"PY_SSIZE_T_CLEAN will be required for '#' formats", 1)) {
return NULL;
}
n = va_arg(*p_va, int);
}
}
else
n = -1;
if (str == NULL) {
v = Py_None;
Py_INCREF(v);
}
else {
if (n < 0) {
size_t m = strlen(str);
if (m > PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string too long for Python string");
return NULL;
}
n = (Py_ssize_t)m;
}
v = PyUnicode_FromStringAndSize(str, n);
}
return v;
}
case 'y':
{
PyObject *v;
const char *str = va_arg(*p_va, const char *);
Py_ssize_t n;
if (**p_format == '#') {
++*p_format;
if (flags & FLAG_SIZE_T)
n = va_arg(*p_va, Py_ssize_t);
else {
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"PY_SSIZE_T_CLEAN will be required for '#' formats", 1)) {
return NULL;
}
n = va_arg(*p_va, int);
}
}
else
n = -1;
if (str == NULL) {
v = Py_None;
Py_INCREF(v);
}
else {
if (n < 0) {
size_t m = strlen(str);
if (m > PY_SSIZE_T_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string too long for Python bytes");
return NULL;
}
n = (Py_ssize_t)m;
}
v = PyBytes_FromStringAndSize(str, n);
}
return v;
}
case 'N':
case 'S':
case 'O':
if (**p_format == '&') {
typedef PyObject *(*converter)(void *);
converter func = va_arg(*p_va, converter);
void *arg = va_arg(*p_va, void *);
++*p_format;
return (*func)(arg);
}
else {
PyObject *v;
v = va_arg(*p_va, PyObject *);
if (v != NULL) {
if (*(*p_format - 1) != 'N')
Py_INCREF(v);
}
else if (!PyErr_Occurred())
/* If a NULL was passed
* because a call that should
* have constructed a value
* failed, that's OK, and we
* pass the error on; but if
* no error occurred it's not
* clear that the caller knew
* what she was doing. */
PyErr_SetString(PyExc_SystemError,
"NULL object passed to Py_BuildValue");
return v;
}
case ':':
case ',':
case ' ':
case '\t':
break;
default:
PyErr_SetString(PyExc_SystemError,
"bad format char passed to Py_BuildValue");
return NULL;
}
}
}
PyObject *
Py_BuildValue(const char *format, ...)
{
va_list va;
PyObject* retval;
va_start(va, format);
retval = va_build_value(format, va, 0);
va_end(va);
return retval;
}
PyObject *
_Py_BuildValue_SizeT(const char *format, ...)
{
va_list va;
PyObject* retval;
va_start(va, format);
retval = va_build_value(format, va, FLAG_SIZE_T);
va_end(va);
return retval;
}
PyObject *
Py_VaBuildValue(const char *format, va_list va)
{
return va_build_value(format, va, 0);
}
PyObject *
_Py_VaBuildValue_SizeT(const char *format, va_list va)
{
return va_build_value(format, va, FLAG_SIZE_T);
}
static PyObject *
va_build_value(const char *format, va_list va, int flags)
{
const char *f = format;
Py_ssize_t n = countformat(f, '\0');
va_list lva;
PyObject *retval;
if (n < 0)
return NULL;
if (n == 0) {
Py_RETURN_NONE;
}
va_copy(lva, va);
if (n == 1) {
retval = do_mkvalue(&f, &lva, flags);
} else {
retval = do_mktuple(&f, &lva, '\0', n, flags);
}
va_end(lva);
return retval;
}
PyObject **
_Py_VaBuildStack(PyObject **small_stack, Py_ssize_t small_stack_len,
const char *format, va_list va, Py_ssize_t *p_nargs)
{
return va_build_stack(small_stack, small_stack_len, format, va, 0, p_nargs);
}
PyObject **
_Py_VaBuildStack_SizeT(PyObject **small_stack, Py_ssize_t small_stack_len,
const char *format, va_list va, Py_ssize_t *p_nargs)
{
return va_build_stack(small_stack, small_stack_len, format, va, FLAG_SIZE_T, p_nargs);
}
static PyObject **
va_build_stack(PyObject **small_stack, Py_ssize_t small_stack_len,
const char *format, va_list va, int flags, Py_ssize_t *p_nargs)
{
const char *f;
Py_ssize_t n;
va_list lva;
PyObject **stack;
int res;
n = countformat(format, '\0');
if (n < 0) {
*p_nargs = 0;
return NULL;
}
if (n == 0) {
*p_nargs = 0;
return small_stack;
}
if (n <= small_stack_len) {
stack = small_stack;
}
else {
stack = PyMem_Malloc(n * sizeof(stack[0]));
if (stack == NULL) {
PyErr_NoMemory();
return NULL;
}
}
va_copy(lva, va);
f = format;
res = do_mkstack(stack, &f, &lva, '\0', n, flags);
va_end(lva);
if (res < 0) {
return NULL;
}
*p_nargs = n;
return stack;
}
int
PyModule_AddObject(PyObject *m, const char *name, PyObject *o)
{
PyObject *dict;
if (!PyModule_Check(m)) {
PyErr_SetString(PyExc_TypeError,
"PyModule_AddObject() needs module as first arg");
return -1;
}
if (!o) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_TypeError,
"PyModule_AddObject() needs non-NULL value");
return -1;
}
dict = PyModule_GetDict(m);
if (dict == NULL) {
/* Internal error -- modules must have a dict! */
PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
PyModule_GetName(m));
return -1;
}
if (PyDict_SetItemString(dict, name, o))
return -1;
Py_DECREF(o);
return 0;
}
int
PyModule_AddIntConstant(PyObject *m, const char *name, long value)
{
PyObject *o = PyLong_FromLong(value);
if (!o)
return -1;
if (PyModule_AddObject(m, name, o) == 0)
return 0;
Py_DECREF(o);
return -1;
}
int
PyModule_AddStringConstant(PyObject *m, const char *name, const char *value)
{
PyObject *o = PyUnicode_FromString(value);
if (!o)
return -1;
if (PyModule_AddObject(m, name, o) == 0)
return 0;
Py_DECREF(o);
return -1;
}
|
batermj/algorithm-challenger
|
code-analysis/programming_anguage/python/source_codes/Python3.8.0/Python-3.8.0/Python/modsupport.c
|
C
|
apache-2.0
| 18,022
|
# -*- coding: utf-8 -*-
#
# Copyright(c) 2010 poweredsites.org
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import functools
import urllib
from tornado.web import HTTPError
from tornado.options import options
from poweredsites.libs import cache # cache decorator alias
def admin(method):
"""Decorate with this method to restrict to site admins."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
if self.request.method == "GET":
url = self.get_login_url()
if "?" not in url:
url += "?" + urllib.urlencode(dict(next=self.request.full_url()))
self.redirect(url)
return
raise HTTPError(403)
elif not self.is_admin:
if self.request.method == "GET":
self.redirect(options.home_url)
return
raise HTTPError(403)
else:
return method(self, *args, **kwargs)
return wrapper
def staff(method):
"""Decorate with this method to restrict to site staff."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
if self.request.method == "GET":
url = self.get_login_url()
if "?" not in url:
url += "?" + urllib.urlencode(dict(next=self.request.full_url()))
self.redirect(url)
return
raise HTTPError(403)
elif not self.is_staff:
if self.request.method == "GET":
self.redirect(options.home_url)
return
raise HTTPError(403)
else:
return method(self, *args, **kwargs)
return wrapper
def authenticated(method):
"""Decorate methods with this to require that the user be logged in.
Fix the redirect url with full_url.
Tornado use uri by default.
"""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
if self.request.method == "GET":
url = self.get_login_url()
if "?" not in url:
url += "?" + urllib.urlencode(dict(next=self.request.full_url()))
self.redirect(url)
return
raise HTTPError(403)
return method(self, *args, **kwargs)
return wrapper
|
felinx/poweredsites
|
poweredsites/libs/decorators.py
|
Python
|
apache-2.0
| 3,016
|
Byte Buddy release notes
------------------------
### 10. February 2022: version 1.12.8
- Make `Step` type in `MemberSubstitution` public as intended.
- Add factory that uses `ArrayDeque` instead of `LinkedList` if the used JVM supports it (Java 6+).
- Fix resolution of internal names for arrays in `TypeReferenceAdjustment`.
### 15. January 2022: version 1.12.7
- Adjust warm-up API to return warmed-up byte code.
- Check *release* property in Byte Buddy Maven plugin.
- Propagate exception from Byte Buddy's class file transformer to improve wrapping behavior.
- Avoid loading of `ElementType` when checking compatibility as the current VM might not provide all constants.
- Allow for disabling stack adjustment as it might not always be possible.
- Make stack adjustment more robust when *goto* targets contain stack values.
### 20. December 2021: version 1.12.6
- Mark argument for `equals` method as `@MaybeNull`.
- Mark argument for `ElementMatcher` as `@UnknownNull`.
### 16. December 2021: version 1.12.5
- Add alias annotations to avoid compilation warnings for optional findbugs dependency.
- Adjust `HashCodeEqualsPlugin` to allow for inclusion of custom annotation type on equals method parameter.
### 15. December 2021: version 1.12.4
- Make paths in Gradle plugin relative and therewith cachable.
- Add explicit check for empty or non-existent source folder to Maven and Gradle plugins.
- Add support for modules when accessing system class loader for `Nexus` or `Installer`.
- Add nullability annotations to all type members which are nullable and declare non-nullability the default.
### 2. December 2021: version 1.12.3
- Move configuration for Java version to extension and avoid implicit configuration during task execution to allow for using a configuration cache.
- Make fail last the alternative to fail fast instead of not failing the build. Enable fail fast by default in the Gradle plugin.
- Use instrumented type in `MemberSubstitution` to include newly added properties in its description.
### 22. November 2021: version 1.12.2
- Improve error message when class file version is not supported.
- Avoid duplication of fields to store auxiliary objects.
- Fix Gradle plugin to be skipped when input files are empty.
- Resolve dynamic bootstrap constant type correctly.
### 9. November 2021: version 1.12.1
- Fix binary incompatibility in `BaseNameResolver` for suffixing naming strategy.
- Introduce caller sensitive base name resolver for suffixing naming strategies and use it as default if Graal native image property is discovered.
### 5. November 2021: version 1.12.0
- Introduce detection for Graal native image execution.
- Correctly resolve interface implementations in revers order when compiling method graph.
- Adjust lambda instrumentation strategy to support Java 17.
### 29. October 2021: version 1.11.22
- Remove automatic frame padding mechanism in favor of explicit *NOP* instruction after injected blocks.
### 18. October 2021: version 1.11.21
- Allow `Advice.PostProcessor` to emit frames.
- Add possibility for `Advice.AssignReturned` to suppress exceptions.
- Add frame when rebasing constructors to avoid breakage if frames are assumed prior to super constructor call.
### 11. October 2021: version 1.11.20
- Add option for `AsScalar` annotation to assign default value instead of ignoring it.
- Add *transform-runtime* goal to Byte Buddy Mojo to allow for running plugins with runtime class path included.
### 5. October 2021: version 1.11.19
- Add `Advice.AssignReturned` post processor to allow for assigning values from `Advice` that uses delegation rather than inlining.
- Allow for declaring `Advice.Local` values from both enter and exit advice.
- Add option for using runtime class path rather than only compile scope from Byte Buddy Maven plugin.
- Avoid loading of annotation proxies within Byte Buddy's internal API.
- Add plugin to add Java `Repeatable` annotations without requiring a JDK 8+.
### 23. September 2021: version 1.11.18
- Avoid binary incompatibility due to signature change by reintroducing method overload.
- Use plugin to add annotations for dispatcher methods to avoid breakage when using obfuscators.
### 22. September 2021: version 1.11.17
- Better error message upon attachment failure due to overridden attach socket.
- Retain label order for instructions in `Advice` to avoid incorrect offsets in stack map frames.
- Change `MethodGraph.Compiler` API to accept generic types.
- Add plugin to add `Proxied` annotations to all proxied methods of a dispatcher. This avoids problems in obfuscators.
- Fix resolution of type initializer in a `Nexus`.
### 17. September 2021: version 1.11.16
- Avoid naming conflicts when adding super and default method delegation for the same method using `MethodDelegation`.
- Fix module visibility for `Invoker` to avoid breakage if Byte Buddy is shaded into another module with different package exports.
### 2. September 2021: version 1.11.15
- Add *net.bytebuddy* prefix to Byte Buddy specific privileges.
- Rework `JavaDispatcher` to require specific privilege but use Byte Buddy's protection domain for dispatchers, once acquired.
### 31. August 2021: version 1.11.14
- Adjust `InvocationHandlerAdapter` to use `null` for methods without parameters as specified by contract.
- Offer option to use `null` for `MethodDelegation` and `Advice` if method has no parameters.
- Add method to seal unsealed class loaders after the fact.
- Use correct type for resolving security manager method in `ByteBuddyAgent`.
### 18. August 2021: version 1.11.13
- Introduce `warmUp` to further avoid circularities when using `AgentBuilder`.
- Fix ignore matcher of `AgentBuilder` to include *jdk.internal.reflect* package by default.
### 6. August 2021: version 1.11.12
- Always use reflection and not a `JavaDispatcher` when a method potentially checks the access context via a security manager.
### 5. August 2021: version 1.11.11
- Do not pollute access context for security manager when defining classes via a method handle lookup.
### 4. August 2021: version 1.11.10
- Added option for Gradle plugin to register `adjustmentPostProcessor` to manually add task dependencies.
### 27. July 2021: version 1.11.9
- Include *jdk.reflect* package in default ignore matcher.
- Retain parameter names for constructor of Java record as it is done by *javac*.
- Throw `NoSuchTypeException` on non-resolved types rather then `IllegalStateException`.
- Weaken visibility checks for fields set by `MethodCall`.
### 15. July 2021: version 1.11.8
- Fix package exposure for `JavaDispatcher` class when Byte Buddy is used as a module.
### 14. July 2021: version 1.11.7
- Introduce a more complex error handler for Gradle builds in favor of strict mode.
- Include method for reading all loaded `Class` values of a loaded dynamic type.
- Include Byte Buddy version in *module-info*.
- Fix package list in *module-info*.
### 2. July 2021: version 1.11.6
- Add fallback for `JavaDispatcher` that works on Android and other platforms that do not support dynamic class definitions.
- Make Gradle task dependency resolution more robust and configurable.
- Update ASM and support Java 18 without experimental configuration.
### 19. June 2021: version 1.11.5
- Remove `AccessController` API to replace with weaved access control via `AccessControllerPlugin`.
### 19. June 2021: version 1.11.4
- Add constant for Java 18
- Improve constructor resolution for `Plugin`s.
- Add convenience method for translating `TypeDescription.Generic` to a builder.
- Add convenience method for resolving an annotation property from a property name.
### 18. June 2021: version 1.11.3
- Introduce `AccessControllerPlugin` to weave use of `AccessController` only if available.
- Fix use of incorrect type when chaining `InvokeDynamic`.
- Better emulate visitation order of ASM when creating types.
- Avoid writing duplicate entries for submitted subtypes in sealed types.
- Better encapsulate `JavaDispatcher` utility.
- Add frame padding to initialization handler when redefining or rebasing a class.
- Do not assume that `TypeVariable`s are `AnnotatedElement`s to support Java 7 and earlier.
### 11. June 2021: version 1.11.2
- Fixes resolution of array types for Java descriptors of `JavaConstant`.
- Properly process Android's version string and avoid relying on the version string where possible.
- Allow for self-calls when creating a `MethodCall` and identifying a method via a matcher.
### 1. June 2021: version 1.11.1
- Add JNA based `ClassInjector` for use if JNA is already available.
- Allow `HashCodeEqualsPlugin` to derive hash code from instrumented type rather then lowest type in hierarchy.
- Retain *this* variable name for index 0 when using advice with remapped locals.
- Rework `AnnotationDescription` for `TypePool` to mirror JVM behavior if annotation properties are changed inconsistently.
- Add several `StackManipulation`s for common operations.
- Remove unwanted dependency to `Instrumentation` API from `JavaModule` type.
- Rework use of reflection to use `JavaDispatcher` API which also allows for custom generation of proxies without use of reflection.
- Fully rework `JavaConstant` API to integrate with Java's `ConstantDesc` API and to allow for production of such descriptions.
- Fix different bugs to properly support representation sealed classes.
### 19. April 2021: version 1.11.0
- Rework resubmission strategy to allow for immediate resubmission or on error.
- Fix type for constructor call when setting field in MethodCall.
- Include thread in default agent logger.
- Add compound property to InvocationHandlerAdapter.
- Flatten conjunction and disjunction matchers.
- Add method to get possibly known class file version of TypeDescription.
- Correctly consider generic array type when computing erasure.
### 9. March 2021: version 1.10.22
- Refactor `JavaConstant` API and fix handle resolution.
- Adjust bootstrap method validation to account for possible dynamic constants.
- Make class loaders parallel capable.
- Correct code for attaching to Windows VMs with 32 bit.
- Allow configuration for Gradle plugin to consider class path as incremental.
### 21. February 2021: version 1.10.21
- Update ASM and add support for Java 17.
- Make plugin discoverability configurable.
- Add advice suppression handler for rethrowing.
### 3. February 2021: version 1.10.20
- Reuse simple but commonly used matchers as constants to avoid repeated allocation.
- Allow build plugins to be discovered from a plugin's class path.
- Do not use cached version of classes that are currently transformed.
- Allow using an incremental class path for build plugins in Gradle.
- Fix filter applied to declared, non-virtual methods in `MethodCall`.
### 21. December 2020: version 1.10.19
- Fix constructor type resolution in `MethodCall`.
- Add support for incremental builds to Byte Buddy Maven plugin.
- Correctly handle empty, primitive arrays as annotation properties in `TypePool`.
- Improve matching of rebaseale methods by using signature tokens rather then full tokens.
- Use *get* as prefix for getters of `Boolean` wrapper properties.
- Consider types in `net.bytebuddy.renamed` package in Byte Buddy agent.
- Set names for all cached variables.
- Do not fail validation for generic properties in Java 1.4 class files since they can be legally contained due to JSR14.
### 1. November 2020: version 1.10.18
- Fixes descriptor used for method handle constant of field.
- Fixes assignability check for varargs.
- Allow using static interface methods for bootstraping.
- Allow providing null to setsValue for field assignment.
- Cleans up providing of constant arguments as type description, enum or constant.
- Support getPackage in legacy class loaders.
- Allow method call by matcher on private method of instrumented type.
### 7. October 2020: version 1.10.17
- Adjust Gradle plugin to properly consider registration order with the Java plugin.
- Correct task adjustment when using Byte Buddy in a multimodule project.
### 23. September 2020: version 1.10.16
- Update to ASM 9 for full support of sealed types.
### 19. September 2020: version 1.10.15
- Rewrite of Gradle plugin, including support for incremental builds.
- Fix `MethodCall` bug when loading arguments from array.
- Mark rebased methods `private final` as required by the JVM when using a native method preifx.
- Fix stack excess monitoring when using advice to discover excess stack values correctly to avoid verifier error.
### 31. July 2020: version 1.10.14
- Fix build config to include Eclipse e2e file.
- Allow for not printing a warning if no file is transformed in build plugin.
- Fix invokability check in `MethodCall` validation.
- Avoid premature validation of `InstrumentType`'s method modifiers.
- Use type cache by default when using loaded type class pool since class lookup showed to be rather expensive.
### 27. June 2020: version 1.10.13
- Add possibility to filter class loaders before attempting to load a class using the `AgentBuilder`'s resubmission feature.
- Add `nameOf` matcher for more efficient string matching based on a hash set.
### 18. June 2020: version 1.10.12
- Experimental support for Java 16.
- Support all constant pool constant types in all APIs.
- Adjust methods for bootstrap arguments to allow types of *constantdynamic* constants.
- Correctly resolve handle type for method handles on private constructors.
- Fix stack size computation for minimal methods in `Advice`.
### 4. June 2020: version 1.10.11
- Emit full frame after super or auxiliary constructor call in constructors if no full frame was already issued within this constructor.
- Support methods that start with a stack map frame before any code.
- Pop array after `@AllArguments` parameter.
- Fix source inclusion for ASM commons.
- Avoid resolution of detached types when replacing target types in generic arrays on members of instrumented types.
- Fix validation of member substitution.
- Include post processor for `Advice`.
### 29. April 2020: version 1.10.10
- Update ASM to 8.0.1
- Close Dex files in Android class loader.
- Add abstraction for advice dispatcher to allow for use of invokedynamic.
- Properly handle incompatible type changes in parsed annotations.
- Add support for Java records.
### 29. March 2020: version 1.10.9
- Add validation for interface method modifiers.
- Correct discovery of MacOs temp directory for Byte Buddy Agent `VirtualMachine`.
- Add parallel processor for Byte Buddy build engine.
- Add preprocessor for Byte Buddy build engine.
- Explicitly load Java's `Module` from boot loader to avoid loading pseudo compiler target bundled with NetBeans.
- Add convenience method for creating lookup-based class loading strategy with fallback to Unsafe for Java 8 and older.
- Add caching for method, field and parameter description hashCode methods.
### 16. February 2020: version 1.10.8
- Adjust use of types of the `java.instrument` module to avoid errors if the module is not present on a JVM.
### 21. January 2020: version 1.10.7
- Correct discovery of old J9 VMs.
- Correct invocation of `AgentBuilder.Listener` during retransformation.
- Allow forbidding self-attachment using own artifact.
- Add possibility to patch class file transformers.
- Fix equality check for float and double primitives.
- Add guards for annotation API to handle buggy reflection API with mandated parameters.
- Update ASM.
### 19. December 2019: version 1.10.6
- Add experimental support for Java 15.
- Allow `AndroidClassLoadingStrategy` to work with newer API level.
### 11. December 2019: version 1.10.5
- Fixes Gradle plugin release to include correct dependency.
- Fixes source jar release for shaded *byte-buddy* artifact.
### 28. November 2019: version 1.10.4
- Throw exception upon illegal creation of entry-only advice with local parameters to avoid verify error.
- Remove escaping for execution path on Windows with spaces for Byte Buddy agent.
- Fix J9 detection for older IBM-released versions of J9 in Byte Buddy agent.
### 8. November 2019: version 1.10.3
- Allow overriding the name of the native library for Windows attach emulation.
- Use correct type pool in build plugin engine for decorators.
- Fix attach emulation for OpenJ9 on MacOS.
### 16. October 2019: version 1.10.2
- Upgrade ASM to version 7.2.
- Improve class file version detection for class files.
- Check argument length of Windows attach emulation.
### 9. August 2019: version 1.10.1
- Extend `VirtualMachine` API emulation.
- Reopen socket for POSIX-HotSpot connections after each command being sent to avoid broken pipe errors.
- Only use JNA API that is available in JNA versions 4 and 5 for better compatibility.
- Include correct license information in artifacts.
- Add injection API based on `jdk.internal.misc.Unsafe` to support agents on platforms that do not include *jdk.unsupported*.
- Add `AgentBuilder.InjectionStrategy` to allow usage of internal injection API.
- Open package in `AgentBuilder` if from and to edges are added.
### 3. August 2019: version 1.10.0
- Add API for loading native agents from Byte Buddy agent.
- Extend `VirtualMachine` API to include other methods.
- Fix error handling in `VirtualMachine` API.
- Fix temporary folder resolution for `VirtualMachine` API.
- Add API for `MemberAttributeExtension`.
- Rework of `AnnotationDescription` API to emulate JVM error handling for incorrect or inconsistent values.
- Add generic type-aware `Assigner`.
- Fix method handle-based injector for Java 14.
### 27. July 2019: version 1.9.16
- Add support for attach emulation on Solaris.
- Fix JNA signatures for attach emulation on POSIX.
- Add standard call conventions for Windows JNA calls.
### 21. July 2019: version 1.9.15
- Add emulated attach mechanism for HotSpot on Windows and for OpenJ9/J9 on POSIX and Windows (if JNA is present).
- Reimplement POSIX attach mechanism for HotSpot to use JNA (if present).
### 8. July 2019: version 1.9.14
- Add Java 14 compatibility.
- Refactor emulated attach mechanism and use JNA in order to prepare supporting other mechanisms in the future.
- Reinterrupt threads if interruption exceptions are catched in threads not owned by Byte Buddy.
- Refactor class file dumping.
- Publish Gradle plugin to Gradle plugin repository.
### 24. May 2019: version 1.9.13
- Added matcher for super class hierarchy that ignores interfaces.
- Extend API for member substitution.
- Minor API extensions.
### 26. March 2019: version 1.9.12
- Fixed stack map frame generation during constructor advice.
- Improves frame generation for cropping-capable frames.
### 21. March 2019: version 1.9.11
- Remove field reference in injected class due to possibility of loading Byte Buddy on the boot loader.
- Updated to ASM 7.1.
- Fix unsafe injection on Java 12/13.
### 11. February 2019: version 1.9.10
- Fixed `ByteArrayClassLoader` when used from boot class loader.
- Fixed shading to include ASM class required during renaming.
### 4. February 2019: version 1.9.9
- Properly interrupt resubmission process in agent builder.
- Fix visibility checks for nest mates.
### 24. January 2019: version 1.9.8
- Extend `MethodCall` to allow for loading target from `StackManipulation`.
- Allow for injection into `MultipleParentClassLoader`.
- Performance improvement on array creation.
- Allow for custom strategy for visibility bridge creation.
### 10. January 2019: version 1.9.7
- Retain native modifier when defining a method without method body.
- Allow appending class loader to multiple parent class loader with hierarchy check.
- Add support for Java 13.
- Extend experimental property to allow for detection of unknown versions.
### 13. December 2018: version 1.9.6
- Add the JVM extension / platform class loaders to the default excludes for the `AgentBuilder`.
- Refactor `MethodCall` to better reuse intermediates. This implies some API changes in the customization API.
- Add hook to `AgentBuilder` to customize class file transformer.
### 22. November 2018: version 1.9.5
- Fixed lookup injection for classes in the default package in Java 9.
### 13. November 2018: version 1.9.4
- Add API for explicit field access from `FieldAccessor`.
- Fix stack size adjustment for custom `MemberSubstitution`s.
- Performance improvement for classes with many methods.
### 28. October 2018: version 1.9.3
- Update to ASM 7.0 final
- Improve field setting capabilities of `FieldAccessor` and `MethodCall`.
### 15. October 2018: version 1.9.2
- Allow for delegation to method result for `MethodDelegation`.
- Extend `MemberSubstitution` to allow for delegating to matched member.
- Create multi-release jar for module-info carrying artifacts.
- Properly handle directory elements in plugin engine with in-memory or folder target.
### 5. October 2018: version 1.9.1
- Minor API change of `Plugin.Engine.Source` to allow for closing resources that need to be opened.
- Reinstantiate class injection on Java 12 with new Unsafe use.
- Allow for disabling use of Unsafe alltogether.
- Adjust Gradle build plugin to use closure for argument instantiation.
- Prepare method arguments on `MethodCall`.
### 29. September 2018: version 1.9.0
- Update to ASM 7 for non-experimental Java 11 support.
- Reduce byte code level to Java 5.
- Add *module-info.class* for *byte-buddy* and *byte-buddy-agent* artifacts.
- Extend `ClassInjector` API to allow supplying string to byte array mappings.
- Add visitor to allow adjustment of inner class attribute.
- Refactor agent builder API to use decoration by default and rather require explicit termination.
- Add `Plugin.Engine` to allow simple static enhancements and rework build plugins for Maven and Gradle to use it.
- Refactor `AsmVisitorWrapper.ForDeclaredMethods` to only instrument methods on `.method` but offer `.invokable` for anthing.
### 8. September 2018: version 1.8.22
- Add guard to `EnclosedMethod` property upon redefinition to avoid error with Groovy which often gets the propery wrong.
- Add possibility to sort fields in plugin-generated equals method.
- Add class file locator for URL instances.
### 3. September 2018: version 1.8.21
- Added caching for expensive methods of reflection API.
- Fix treatment of inner class attributes for redefinition and rebasement.
- Extend build plugin API to achieve better Java agent compatibility.
- Add convenience API for creating lambda expressions.
### 29. August 2018: version 1.8.20
- Fix decoration to include non-virtual methods.
- Add build plugin for caching the return value of a method.
### 28. August 2018: version 1.8.19
- Fix annotation handling in decorator strategy.
- Several minor bug fixes for `MethodCall`.
- Fix shading for signature remapper.
### 27. August 2018: version 1.8.18
- Add API for defining inner types and nest mate groups.
- Add decoration transformer for more efficient application of ASM visitors.
- Allow chaining of `MethodCall`s.
- Prohibit illegal constructor invocation from `MethodCall`s.
### 6. August 2018: version 1.8.17
- Fix class loader injection using `putBoolean`.
- Do not set timeout for Unix attach simulation if value is `0`.
- Avoid incorrect lookup of `getDefinedPackage` on Java 8 IBM VMs.
- Fix type checks on constantdynamic support.
### 3. August 2018: version 1.8.16
- Add support for dynamic class file constants for Java 11+.
- Suppress lazy resolution errors within `MemberSubstitution::relaxed`.
- Generalize method matcher for `clone` method.
- Add `toString` method to `ClassFileVersion`.
- Reenable `ClassFileInjection.Default.INJECTION` in Java 11+ via fallback onto `Unsafe::putBoolean`.
### 26. July 2018: version 1.8.15
- Add preliminary support for Java 12.
### 24. July 2018: version 1.8.14
- Query explicitly added class loaders before the instrumented class's class loader in advice transformer for an agent builder.
- Add nullcheck for `Instrumentation::getAllLoadedClasses`.
- Allow for access controller-based lookups for `Method` constants.
- Use `getMethod` instead of `getDeclaredMethod` for method lookup if possible.
### 5. July 2018: version 1.8.13
- Update to ASM 6.2
- Reinstate support for latest Java 11 EA if `net.bytebuddy.experimental` is set.
- Fix edge completion for `AgentBuilder`.
- Dump input class file if the `net.bytebuddy.dump` is set.
- Add convenience chaining methods to `Implementation.Compound`.
- Fix nestmate changes in method invocation.
### 25. May 2018: version 1.8.12
- Fix misrepresentation of default package as `null`.
- Add `Advice.Exit` annotation and allow for method repetition based on exit advice value.
- Add `Advice.Local` annotation to allow for stack allocation of additional variables.
- Improve advice's method size handler.
### 4. May 2018: version 1.8.11
- Avoid shading unused ASM classes with incomplete links what breaks lint on Android and JPMS module generation.
### 28. April 2018: version 1.8.10
- Extended support for self-attachment by using current jar file for Java 9+.
- Minor performance improvements.
### 27. April 2018: version 1.8.9
- Several performance improvements.
- Adjust `toString` implementation for parameterized types to the changed OpenJDK 8+ behavior.
- Attempt self-attachment using the current jar file.
### 20. April 2018: version 1.8.8
- Use cache for loaded `TypeDescription` to avoid overallocation.
- Generalize exception handler API for `Advice`.
### 19. April 2018: version 1.8.7
- Added `ClassWriterStrategy` that allows controlling how the constant pool is copied.
### 18. April 2018: version 1.8.6
- Introduced concept of sealing the `InjectionClassLoader` to avoid abuse.
- Avoid class loader leak by not storing exceptions thrown in class initializers which can keep references to their first loading class in their backtrace.
- Add `ClassFileBufferStrategy` to agent builder.
- Retain deprecation modifier on intercepted methods and fields on class files prior to Java 5.
### 15. April 2018: version 1.8.5
- Release with `equals` and `hashCode` methods being generated based on the fixes in the previous version.
### 15. April 2018: version 1.8.4
- Only open ASM if this is specified via the boolean property `net.bytebuddy.experimental`.
- Fix resolution of invoking methods of `Object` on interfaces to not specialize on the interface type. The latter is also failing verification on Android.
- Several performance improvements.
- Do no longer use unsafe injection as a default class loading strategy.
### 31. March 2018: version 1.8.3
- Allow Java 11 classes by opening ASM.
- Remove Lombok and add methods using Byte Buddy plugin.
### 31. March 2018: version 1.8.2
- Reduce log output for Gradle and Maven plugin.
- Fix class check in `EqualsMethod`.
### 28. March 2018: version 1.8.1
- Add implementations for `HashCodeMethod`, `EqualsMethod` and `ToStringMethod` including build tool plugins.
- Refactor handling of stack map frame translation within `Advice` to allow for handling of methods with inconsistent stack map frames if the method arguments are copied.
- Make argument copying the default choice if exit advice is enabled.
- Fix a bug in parameter annotation computation within `Advice`.
- Update to ASM 6.1.1.
### 13. March 2018: version 1.8.0
- Refactored `Advice` argument handling to be controlled by a dedicated structure.
- Added basic logic for argument copying in `Advice`.
- Fix performance degradation for cached fields.
- Add support for Java 10 and preliminary support for Java 11.
### 2. March 2018: version 1.7.11
- Fix Maven and Gradle plugins to resolve correct class file version.
- Add method to `ClassReloadingStrategy` to allow specification of explicit redefinition strategy. Change default redefinition strategy.
- Improve stack map frame validation in `Advice`.
- Fix type resolution for virtual calls in `MemberSubstitution`.
### 2. February 2018: version 1.7.10
- Fixes self-attachment on Java 9+ on Windows.
- Check for non-accessibility on `MethodCall`.
- Change static proxy fields to be `volatile`.
- Do not copy security-related meta-data on jar file copying.
- Guard resolution of annotations for methods with synthetic parameters.
- Forbid skipping code in constructors for `Advice`.
- Added constructor strategy for defining a default constructor that invokes a non-default constructor.
- Improve performance of accessor methods and cache fields by reducing use of `String::format`.
### 6. November 2017: version 1.7.9
- Fixes `RAW_TYPES` mode for loaded types where properties were resolved incorrectly.
- Adds support for Java 10 version number.
### 24. October 2017: version 1.7.8
- Added property `net.bytebuddy.raw` to allow for suppress generic type navigation.
### 22. October 2017: version 1.7.7
- Make self-attachment more robust on Windows.
- Add M2E instructions for Maven plugin.
- Improve hash function for members and avoid collision field names.
- Convenience for custom target binders.
### 8. October 2017: version 1.7.6
- Update ASM to version 6 final.
- Accept `null` in custom bound `Advice`.
- Fix fail fast in build plugins.
- Permit repeated exception in method signature.
### 30. August 2017: version 1.7.5
- Prevents premature termination of reattempting retransformation.
### 30. August 2017: version 1.7.4
- Add convenience methods for defining bean properties.
- Minor fixes to support Java 9 and allow building on JDK9.
### 11. August 2017: version 1.7.3
- Allow configuring `TypePool` to use within `Advice`.
### 05. August 2017: version 1.7.2
- Fixes possibility to customize binding in `MethodDelegation`.
- Update to ASM 6 beta to support Java 9 fully.
### 15. June 2017: version 1.7.1
- Added `DiscoveryStrategy` for redefinition to determine types to be redefined.
- Changed Maven plugin to only warn of missing output directory which might be missing.
- Added global circularity lock.
- Removed sporadic use of Java util logging API.
### 14. May 2017: version 1.7.0
- Define names for automatic modules in Java 9.
- Introduce property `net.bytebuddy.nexus.disabled` to allow disabling `Nexus` mechanism.
- Do not use context `ProtectionDomain` when using `Nexus` class.
- Normalize `Advice` class custom bindings via opening internally used `OffsetMapping` API. Remove `CustomValue` binding which is less powerful.
- Do not group `transient` with `volatile` modifier.
- Introduce `MemberRemoval` component for removing fields and/or methods.
- Introduce first version for `MemberSubstituion` class for replacing field/method access.
### 26. April 2017: version 1.6.14
- Extended `AgentBuilder` listener API.
- Added trivial `RawMatcher`.
- Check modules for modifiability.
- Adapt new Java 9 namespaces for modules.
- Start external process for self-attachment if self-attachment is not allowed.
### 17. April 2017: version 1.6.13
- Explicit consistency check for stack map frame information in `Advice`.
- Extended `InstallationListener` API.
- Fixed stack size information on variable storage.
### 18. March 2017: version 1.6.12
- Add `InstallationListener` in favor of `InstallationStrategy` and allow resubmission strategy to hook into it in order to cancel submitted jobs.
### 12. March 2017: version 1.6.11
- Fix modifier adjustment for visibility bridges (did not work last time)
- Added class injector for Java 9 handle class definition.
### 1. March 2017: version 1.6.10
- Allow installation of `ClassFileTransformer` in byte array class loader.
- Adjust visibility for bridge methods.
### 20. February 2017: version 1.6.9
- Properly add visibility bridges for default methods.
- Added matcher for unresolvable types.
- Improved `ByteBuddyAgent` API.
- Fixed Gradle and Maven plugin path resolution.
### 12. February 2017: version 1.6.8
- Avoid logging on empty resubmission.
- Retain actual modifiers on frozen instrumented type.
### 26. January 2017: version 1.6.7
- Refactored `Resubmitter` to a DSL-step within the redefinition configuration.
- Added additional element matchers.
### 24. January 2017: version 1.6.6
- Fixed computation of modifiers for rebased method in native state.
### 20. January 2017: version 1.6.5
- Improved lazy resolution of super types in matchers.
- Added frozen instrumented type and factory for such types when no class file format changes are desired.
- Improved lazy resolution for generic type signatures.
### 19. January 2017: version 1.6.4
- Refactored super type visitors to always be lazy until generic properties are required to be resolved.
- Apply proper raw type resolution. Made default method graph compiler reify generic types to compute correct bridges.
### 13. January 2017: version 1.6.3
- Improved `Resubmitter` configuration.
- Added `AgentBuilder.Transformation.ForAdvice` to allow for simple creation of `Advice` classes from Java agents.
### 11. January 2017: version 1.6.2
- Removed obsolete `toString` representations.
- Start using Lombok for equals/hashCode unless explicit.
- Add security manager check to Byte Buddy agent.
- Added asynchronous super type loading strategies.
- Added resubmitter.
- Added class injection strategy for Android.
- Fixed type initializer instrumentation for redefinitions.
- Added `loaded` property for listener on agent builder.
### 5. January 2017: version 1.6.1
- Added check to `@Pipe` for method invokability.
- Added unsafe `ClassInjector` and class loading strategy.
- Improved reflection-based class injector on Java 9.
- Removed unnecessary class file location using modules on Java 9.
- Improved fail-safety for type variable resolution to allow processing incorrectly declared type variables.
### 2. January 2017: version 1.6.0
- Added `InjectingClassLoader` with class loading strategy that allows for reflection-free loading.
- Added proper class loader locking to injection strategy.
- Fixed method lookup to not use *declared* accessors unless necessary to avoid security manager check.
- Added `@SuperMethod` and `@DefaultMethod` annotations for `MethodDelegation`.
- Refactored `AsmVisitorWrapper` to accept a list of fields and methods that are intercepted. This allows to use the wrapper also for methods that are overridden.
- Added a `MethodGraph.Compiler.ForDeclaredMethods` to avoid processing full type hierarchy if only type enhancement should be done without declaring new methods on a type. This should be used in combination with `Advice` instead of `MethodGraph.Empty` as those methods are supplied to the ASM visitor wrappers.
- Refactored `MethodDelegation` to precompile records for all candidates to avoid duplicate annotation processing.
### 29. December 2016: version 1.5.13
- Updates to ASM 5.2
- Updates Android DX-maker.
- Adds API to `MultipleParentClassLoader` to use other loader than bootstrap loader as a parent which is not always legal, e.g. on Android.
- Make `ClassInjector` use official class loading lock if one is available.
- Make `ClassInjector` use `getDefinedPackage` instead of `getPackage` if available.
- Declare UNIX socket library as provided in Byte Buddy agent to only add the dependency on demand.
### 27. December 2016: version 1.5.12
- Refactored rebasing of type initializers. Do no longer rebase into static method to pass validation for final static field assignment on Java 9.
- Added fallback to `sun.misc.Unsafe` for class definition if reflective access to the protected `ClassLoader` methods is not available which are required for the injection strategy.
- Added super-type-loading `DescriptorStrategy` for agent builder.
- Added assignment checks for `MethodCall` for invocation target.
### 20. December 2016: version 1.5.11
- Resolved compound components to linearize nested collections for vastly improved performance with large structures.
- Added `TypeCache`.
- Added fallback to assign `null` to `SuperCall` and `DefaultCall` if assignment is impossible.
- Deprecated `Forwarding` in favor of `MethodCall`.
- Fixed matcher for interfaces in type builder DSL.
- Fixed resolution of field type in `MethodCall`.
### 16. December 2016: version 1.5.10
- Added possibility for readding types after a failed retransformation batch.
- Added partitioning batch allocator.
### 13. December 2016: version 1.5.9
- Allow specifying `TargetType` in `Advice.FieldValue`.
- Allow array value explosion in `MethodCall`.
- Extended `FieldAccessor` to allow reading `FieldDescription`s directly.
- Fixed class name resolution in Maven and Gradle plugins.
### 5. December 2016: version 1.5.8
- Added implementation for attachment on Linux and HotSpot using a non-JDK VM.
- Fixed argument resolution for `ByteBuddyAgent`.
- Fixed field resolution for `MethodCall` to allow custom definition of fields.
- Fixed visibility checks.
- Do not override default method for proxies for `Pipe`.
### 25. November 2016: version 1.5.7
- Fixed type discovery for custom advice annotation bindings.
### 18. November 2016: version 1.5.6
- Added possibility to configure suppression handler in `Advice` classes.
### 17. November 2016: version 1.5.5
- Refactored `Advice` to use stack manipulations and `Assigner`.
- Refactored `Advice` to use `Return` instead of `BoxedReturn` and added `AllArguments` instead of `BoxedArguments` in conjunction with allowing to use dynamic typing for assignments via the annotation.
- Added fixed value instrumentation for method parameters.
- Added weak class loader referencing for `Nexus` and allow registration of a `ReferenceQueue`.
### 11. November 2016: version 1.5.4
- Extended `MethodCall` API.
- Added additional element matchers.
- Extended `AsmVisitorWrapper` API.
### 3. November 2016: version 1.5.3
- Refactored `Advice` to allow usage as a wrapper for an `Implementation`. This allows chaining of such advices.
- Allow to dynamically locate a `FieldDescription` or `ParameterDescription` from a custom `Advice` annotation which binds the field or parameter value.
- Added `invokeSelf` option to `MethodCall` instrumentation.
### 31. October 2016: version 1.5.2
- Refactored `FieldAccessor` to allow more flexible creation of getters and setters of particular parameters.
- Create string-based hashes for random fields that depend on a value's hash value.
### 27. October 2016: version 1.5.1
- Fixed stack size computation when using `@Advice.Origin`.
### 25. October 2016: version 1.5.0
- Refactor `Instrumentation`s to only delegate to fields instead of requiring their definition. The `defineField` API should be generally preferred for defining fields as it is much richer and therefore easier to extend.
- Made type annotation reader more robust towards older versions of Java 8.
- Refactored lazy type resolution for generic types to no longer eagerly load generic types when navigating through a type hierarchy.
- Unified several implementation APIs and added better abstractions.
- Fixed some missing bits of validation of implementations.
- Do not replicate incompatible bridge methods.
### 17. October 2016: version 1.4.33
- Use `IMITATE_SUPER_CLASS_OPENING` as a default constructor strategy.
- Extract method visibility during method graph compilation.
- Apply a type variable's erasure if a type variable is out of scope instead of throwing an exception. This can happen when subclassing an inner type outside of its outer type or when a compiler such as *scalac* adds inconsistent generic type information.
- Optimize the application of the ignore matcher within an agent builder to only be applied once.
### 11. October 2016: version 1.4.32
- Added `ConstructorStrategy` for inheriting constructors but make them `public`.
- Do not instrument anonymously loaded types during redefinition unless the lambda strategy is enabled.
### 6. October 2016: version 1.4.31
- Reuse `CircularityLock` on all `AgentBuilder`s by default to avoid that Byte Buddy agents introduce circularities to different agents.
- Also allow using `Advice` as `Implementation`.
- Added `FixedValue.self()` and added `FieldPersistence` for describing `volatile` fields.
### 4. October 2016: version 1.4.30
- Also acquire circularity lock during class file retransformation.
- Added slicing `BatchAllocator`.
### 3. October 2016: version 1.4.29
- Explicitly check for recursive transformation of types used during a transformation causing a `ClassCircularityError` from an `AgentBuilder` by adding thread-local locking.
### 30. September 2016: version 1.4.28
- Additional refactoring of the `AgentBuilder` to fix a regression of 1.4.27.
- Unified the error listener and the regular listener that were added in the previous version.
### 29. September 2016: version 1.4.27
- Refactored `AgentBuilder` retransformation mechanism to allow for custom recovery and batch strategies.
- Fixed Gradle plugin build which did not contain files.
- Supply no argument to agent attachment by default instead of empty string argument.
*Note*: Currently, it seems like the new retransformation mechanism introduces a racing condition in class loading resulting in some classes not being instrumented
### 21. September 2016: version 1.4.26
- Refactored `skipOn` property of `Advice` component.
- Allow reading a `Method`/`Constructor` property from `Advice`.
- Fixed bug that duplicated added parameter annotations on a `DynamicType` builder.
### 20. September 2016: version 1.4.25
- Added overloaded versions for `byte-buddy-agent` to allow agent attachment with explicit argument.
- Made `Advice` more flexible to allow skipping of instrumented method for complex advice method return types.
### 15. September 2016: version 1.4.24
- Make `AgentBuilder` produce `ResettableClassFileTransformer`s which can undo their transformation.
### 14. September 2016: version 1.4.23
- Made `TypeDescription.ForLoadedType` serializable for better alignment with reflection API.
- Adapted changes in `Instrumentation` API for Java 9.
- Refactored `AnnotationValue` to apply Java 9 specific string rendering on Java 9 VMs.
- Adapted new `toString` representation of parameterized types on Java 9 VMs.
### 02. September 2016: version 1.4.22
- Added Byte Buddy plugin for Gradle.
- Improved Byte Buddy plugin for Maven.
### 28. August 2016: version 1.4.21
- Fixed modifier resolution for anonymous classes to preserve a shadowed `final` modifier.
- Added Byte Buddy plugin for Maven.
### 21. August 2016: version 1.4.20
- Fixed stack size adjustment for accessing double-sized primitive access array elements.
- Fixed `Advice` adjustment of local variable index for debugging information (improves Java agent compatibility).
- Renamed `TypeLocator` to `PoolStrategy` to avoid confusion with the names.
- Removed `DescriptionStrategy`s that rely on fallback-description as those do not properly fallback for meta data.
- Added `FallbackStrategy` as a replacement which allows to reattempt a transformation without using loaded type information.
### 14. August 2016: version 1.4.19
- Added `@StubValue` and `@Unused` annotations to `Advice` component.
- Added possibility to retain line number information for entry`Advice`
- Removed class loader dependency when querying loaded annotation values.
- Made annotation values more type-safe.
### 9. August 2016: version 1.4.18
- Added automatic support for Java 9 class file location for boot modules.
- Improved `FieldProxy.Binder` to allow for a single accessor interface.
- Fixed counting problem in `Advice` component.
### 1. August 2016: version 1.4.17
- Fixed annotation resolution for Java 9 to exclude the `jdk.internal` namespace by default.
- Do not copy annotations for default constructor strategies but allow configuring annotation strategy.
- Added file-system class file locators for modules in Java 9.
- Added convenience methods to default location strategies.
- Exclude `sun.reflect` namespace by default from `AgentBuilder` to avoid error messages.
- Fixed resolution of type variables for transformed methods and fields.
- Fixed stack-aware method visitor when encountering exchanging duplication instructions.
### 28. July 2016: version 1.4.16
- Added `POOL_LAST_DEFERRED` and `POOL_LAST_FALLBACK` description strategy.
- Fixed resolution of bridge methods for diamond inheritance.
- Refactored modifier API to only expose named modifier checks for an element that apply to it.
- Fixed resolution for type variables for transformed methods.
### 25. July 2016: version 1.4.15
- Fixed frame generation for `void` methods without regular return in `Advice`.
- Fixed `TypeValidation` for Java 8 interfaces not allowing private methods.
- Simplified and documented `AccessController` usage.
### 21. July 2016: version 1.4.14
- Fixed bug with handling of legacy byte code instructions in `Advice` component.
- Cleaned up and refactored usage of `AccessController`. Added privileged handling to `AgentBuilder`.
- Added proper buffering to non-buffered interaction with file streams.
- Make `ByteBuddy` creation more robust by adding a default fallback for unknown VMs.
- Improved support for Java 9.
### 19. July 2016: version 1.4.13
- Lazily compute `Implementation.Target` and `Implementation.Context` in case of a type inlining to provide correct feature set. Added validation if this constraint is broken.
- Make `TypePool` using an eager `TypeDescription` more robust towards errors.
### 15. July 2016: version 1.4.12
- Monitor advice code for inconsistent stack heights at return statements to clean the stack during instrumentation to not trigger verifier errors if such atypical but legal code is encountered.
- Do not generate handlers for return values if an instrumented method or an advice method only throws exceptions but never returns regularly.
### 15. July 2016: version 1.4.11
- Added tracer for the state of the operand stack for the `Advice` component to clear the stack upon a return. Without this, if code would return without leaving the stack empty, a verifier error would be thrown. This typically is only a problem when processing code that was produced by other code generation libraries.
### 15. July 2016: version 1.4.10
- Fixed resolution of modifiers and local type properties from a default type pool.
- Improved key for caching `TypeLocator` to share a key for the system and bootstrap class loader.
### 11. July 2016: version 1.4.9
- Added additional implementations of a `DescriptionStrategy` for `POOL_LAST` and `POOL_FIRST` resolution.
### 6. July 2016: version 1.4.8
- Allow to skip execution of instrumented method from `Advice` via entry advice indicated by return value.
- Added API to transform predefined type variables on a dynamic type.
- Refactored `Transformer` API to be shared for methods, fields and type variables.
- Allow to spread `Advice` methods over multiple classes.
- Added convenience methods to `AsmVisitorWrapper`s for declared fields and methods.
- Performance improvements in `Advice` class for byte code parsing.
### 6. July 2016: version 1.4.7
- Added default `TypePool` that allows for lazy resolution of referenced types. This can both be a performance improvement and allows working with optional types as long as they are not directly required within a transformation. This type pool is now used by default.
- Make interfaces public by default when creating them via `ByteBuddy::makeInterface`.
- Added `TypeResolutionStrategy` to allow for active resolution via the `Nexus` also from outside the `AgentBuilder`.
- Make best effort from a `ClassLoadingStrategy` to not resolve types during loading.
- Added convenience method for loading a dynamic type with an implicit `ClassLoadingStrategy`.
### 30. June 2016: version 1.4.6
- Added a `ClassFileLocator` for a class loader that only references it weakly.
- Allow to supply `TypePool` and `ClassFileLocator` separately within an `AgentBuilder`.
- Made `MethodPool` sensitive to bridge methods which should only be added to classes of a version older than Java 4.
- Fixed creation of Java 9 aware `ClassFileTransformer` to only apply on Java 9 VMs.
- Added matcher for the type of a class loader.
- Fixed name resolution of anonymously-loaded types.
### 24. June 2016: version 1.4.5
- Added `InstallationStrategy` to `AgentBuilder` that allows customization of error handling.
- Added *chunked* redefinition and retransformation strategies.
### 23. June 2016: version 1.4.4
- Added `net.bytebuddy` qualifier when logging.
- Added `net.bytebuddy.dump` system property for specifying a location for writing all created class files.
### 17. June 2016: version 1.4.3
- Fixed bug in `MultipleParentClassLoader` where class loaders were no longer filtered properly.
- Added support for major.minor version 53 (Java 9).
- Made `DescriptionStrategy` customizable.
### 16. June 2016: version 1.4.2
- Changed storage order of return values in `Advice` methods to avoid polluting the local variable array when dealing with nested exception handlers.
- Added caching `ElementMatcher` as a wrapping matcher.
- Exclude Byte Buddy types by default from an `AgentBuilder`.
- Added `DescriptionStrategy` that allows not using reflection in case that a class references non-available classes.
### 7. June 2016: version 1.4.1
- Fixed validation by `MethodCall` instrumentation for number of arguments provided to a method.
- Added further support for module system.
- Allow automatic adding of read-edges to specified classes/modules when instrumenting module classes.
- Implicitly skip methods without byte code from advice component.
### 2. June 2016: version 1.4.0
- Added initial support for Jigsaw modules.
- Adjusted agent builder API to expose modules of instrumented classes.
- Added additional matchers.
- Simplified `BinaryLocator` and changed its name to `TypeLocator`.
### 30. May 2016: version 1.3.20
- Fixed `MultipleParentClassLoader` to support usage as being a parent itself.
- Fixed default ignore matcher for `AgentBuilder` to ignore synthetic types.
### 29. April 2016: version 1.3.19
- Added convenience method to `MethodCall` to add all arguments of the instrumented method.
- Added `optional` attribute to `Advice.This`.
### 25. April 2016: version 1.3.18
- The Owner type of a parameterized type created by a `TypePool` is no longer parameterized for a static inner type.
- The receiver type of a executingTransformer is no longer considered parameterized for a static inner type.
### 23. April 2016: version 1.3.17
- Removed overvalidation of default values for non-static fields.
### 21. April 2016: version 1.3.16
- Better support for Java 1 to Java 4 by automatically resolving type references from a type pool to `forName` lookups.
- Better support for dealing with package-private types by doing the same for invisible types.
- Simplified `MethodHandle` and `MethodType` handling as `JavaInstance`.
### 19. April 2016: version 1.3.15
- Extended the `AgentBuilder` to allow for transformations that apply fall-through semantics, i.e. work as a decorator.
- Added map-based `BinaryLocator`.
### 19. April 2016: version 1.3.14
- Only add frames in `Advice` components if class file version is above 1.5.
- Allow to specify exception type for exit advice to be named. **This implies a default change** where exit advice is no longer invoked by default when an exception is thrown from the instrumented method.
- Added possibility to assign a value to a `@BoxedReturn` value to change the returned value.
### 16. April 2016: version 1.3.13
- Extended the `Advice` component storing serializable values that cannot be represented in the constant pool as encodings in the constant pool.
- Added support for non-inlined `Advice` method.
- Mask modifiers of ASM to not longer leak internal flags beyond the second byte.
- Added support for suppressing an exception of the instrumented method from within exit advice.
### 13. April 2016: version 1.3.12
- Fixed error during computation of frames for the `Advice` computation.
- Avoid reusing labels during the computations of exception tables of the `Advice` component.
### 12. April 2016: version 1.3.11
- Byte Buddy `Advice` now appends handlers to an existing exception handler instead of prepending them. Before, existing exception handlers were shadowed when applying suppression or exit advice on an exception.
- Added additional annotations for `Advice` such as `@Advice.BoxedReturn` and `@Advice.BoxedArguments` for more generic advice. Added possibility to write to fields from advice.
- Added mechanism for adding custom annotations to `Advice` that map compile-time constants.
- Implemented a canonical binder for adding custom compile-time constants to a `MethodDelegation` mapping.
### 8. April 2016: version 1.3.10
- Fixed another bug during frame translation of the `Advice` component when suppression were not catched for an exit advice.
- Improved unit tests to automatically build Byte Buddy with Java 7 and Java 8 byte code targets in integration.
### 7. April 2016: version 1.3.9
- Optimized method size for `Advice` when exception is not catched.
- Improved convenience method `disableClassFormatChanges` for `AgentBuilder`.
### 6. April 2016: version 1.3.8
- Fixed frame computation for the `Advice`.
- Optimized frame computation to emit frames of the minimal, possible size when using `Advice`.
- Only add exit `Advice` once to reduce amount of added bytes to avoid size explosion when a method supplied several exits.
- Optimized `Advice` injection to only add advice infrastructure if entry/exit advice is supplied.
- Optimized exception handling infrastructure for exit `Advice` to only be applied when exceptions are catched.
- Added mapping for the *IINC* instruction which was missing from before.
- Added possibility to propagate AMS reader and writer flags for `AsmVisitorWrapper`.
- Made `Advice` method parser respect ASM reader flags for expanding frames.
### 3. April 2016: version 1.3.7
- Fixed bug when returning from an `Advice` exit method without return value and accessing `@Advice.Thrown`.
- Added additional annotations for advice `@Advice.Ignored` and `@Advice.Origin`.
- Implemented frame translator for `Advice` method to reuse existing frame information instead of recomputing it.
### 1. April 2016: version 1.3.6
- Implemented universal `FieldLocator`.
- Extended `AgentBuilder` API to allow for more flexible matching and ignoring types.
### 18. Match 2016: version 1.3.5
- Added `Advice.FieldValue` annotation for reading fields from advice.
### 13. March 2016: version 1.3.4
- Added support for new Java 9 version scheme.
### 10. March 2016: version 1.3.3
- Added hierarchical notation to default `TypePool`.
### 10. March 2016: version 1.3.2
- Added possibility to suppress `Throwable` from advice methods when using the `Advice` instrumentation.
### 9. March 2016: version 1.3.1
- Added possibility to use contravariant parameters within the `Advice` adapter for ASM.
### 8. March 2016: version 1.3.0
- Added `Advice` adapter for ASM.
- Fixed `AsmVisitorWrapper` registration to be stacked instead of replacing a previous value.
- Added validation for setting field default values what can only be done for `static` fields. Clarified javadoc.
- Fixed attach functionality to work properly on IBM's J9.
### 22. February 2016: version 1.2.3
- Fixed return type resolution for overloaded bridge method.
### 16. February 2016: version 1.2.2
- Fixed redefinition strategy for `AgentBuilder` where transformations were applied twice.
- Added `ClassLoader` as a third argument for the `AgentBuilder.Transformer`.
### 6. February 2016: version 1.2.1
- Added validation for receiver types.
- Set receiver types to be implicit when extracting constructors of a super type.
### 5. February 2016: version 1.2.0
- Added support for receiver type retention during type redefinition and rebasement.
- Added support for receiver type definitions.
### 5. February 2016: version 1.1.1
- Fixed interface assertion of the custom binder types to accept default methods.
- Improved documentation.
### 26. January 2016: version 1.1.0
- Refactored `AgentBuilder` API to be more streamlined with the general API and improved documentation.
- Added possibility to instrument classes that implement lambda expressions.
- Added possibility to explicitly ignore types from an `AgentBuilder`. By default, synthetic types are ignored.
- Proper treatment of deprecation which is now written into the class file as part of the resolved modifier and filtered on reading.
- Added support for Java 9 APIs for process id retrieval.
### 21. January 2016: version 1.0.3
- Added support for Java 9 owner type annotations.
- Fixed bug in type builder validation that prohibited annotations on owner types for non-generic types.
- Added additional element matchers for matching an index parameter type.
### 20. January 2016: version 1.0.2
- Fixed resolution of type paths for inner classes.
- Added preliminary support for receiver types.
- Fixed resolution of type variables from a static context.
### 18. January 2016: version 1.0.1
- Refactored type variable bindings for generic super types: Always retain variables that are defined by methods.
- Retain type annotations that are defined on a `TargetType`.
### 15. January 2016: version 1.0.0
- Added support for type annotations.
- Refactored public API to support type annotations and parameter meta information.
- Several renamings in preparation of the 1.0.0 release.
- Refactored type representation to represent raw types as `TypeDescription`s. This allows for resolution of variables on these types as erasures rather than their unresolved form. Refactored naming of generic types to the common naming scheme with nested classes.
- Replaced generalized token representation to define tokens, type tokens and signature tokens.
- General API improvements and minor bug fixes.
### 4. January 2016: version 0.7.8
- Implemented all type lists of class file-rooted files to fallback to type erasures in case that the length of generic types and raw types does not match. This makes Byte Buddy more robust when dealing with illegally defined class files.
- Fixed rule on a default method's invokeability.
- Extended `MethodCall` implementation to include shortcuts for executing `Runnable` and `Callable` instances.
- Added `failSafe` matcher that returns `false` for types that throw exceptions during navigation.
### 14. December 2015: version 0.7.7
- Fixed type resolution for anonymously loaded classes by the `ClassReloadingStrategy`.
- Added additional `InitiailizationStrategy`s for self-injection where the new default strategy loads types that are independent of the instrumented type before completing the instrumentation. This way, the resolution does not fail for types that are accessed via reflection before initializing the types if a executingTransformer is rebased.
### 11. December 2015: version 0.7.6
- Fixed resolution of `@Origin` for constructors and added possibility to use the `Executable` type.
- Fixed name resolution of types loaded by anonymous class loading.
- Allowed alternative lookup for redefinitions to support types loaded by anonymous class loading.
### 7. December 2015: version 0.7.5
- Fixed generic type resolution optimization for proxies for `@Super`.
### 2. December 2015: version 0.7.4
- Added `TypePool` that returns precomputed `TypeDescription`s for given types.
- Fixed agent and nexus attachment and the corresponding value access.
### 30. November 2015: version 0.7.3
- Added visibility substitution for `@Super` when the instrumented type is instrumented to see changed state on a redefinition.
- Added patch for modifier information of inner classes on a redefinition.
- Added fallback for `Nexus` injection to attempt lookup of already loaded class if resource cannot be located.
### 26. November 2015: version 0.7.2
- Added `TypePool` that falls back to class loading if a class cannot be located.
- Added binary locator for agent builder that uses the above class pool and only parses the class file of the instrumented type.
- Added methods for reading inner classes of a `TypeDescription`.
- Fixed random naming based on random numbers to avoid signed numbers.
- Moved `Nexus` and `Installer` types to a package-level to avoid illegal outer and inner class references which could be resolved eagerly.
- Added validation for illegal constant pool entries.
- Added a `Premature` initialization strategy for optimistically loading auxiliary types.
- Added a `ClassVisitorWrapper` for translating Java class files prior to Java 5 to use explicit class loading rather than class pool constants.
### 16. November 2015: version 0.7.1
- Fixed injection order for types to avoid premature loading by dependent auxiliary types.
- Added additional `ClassFileLocator`s and refactored class file lookup to always use these locators.
### 11. November 2015: version 0.7
- Refactored injection strategy to always inject and load the instrumented type first to avoid premature loading by reference from auxiliary types.
- Refactored `AgentBuilder.Default` to delay auxiliary type injection until load time to avoid premature loading by reference from auxiliary types.
- Added API to add additional code to type initializers while building a type.
- Refactored agent `Nexus` to allow for multiple registrations of self initializers if multiple agents are registered via Byte Buddy.
- Fixed resolution of interface methods that were represented in the type hierarchy multiple times.
- Implemented custom ASM class writer to allow for frame computation via Byte Buddy's type pool when this is required by a user.
- Fallback to no allowing for instrumenting type initializers for rebased or redefined interfaces before Java 8.
### 28. October 2015: version 0.7 (release candidate 6)
- Refactored `AgentBuilder.Default` to delegate exceptions during redefinitions to listener instead of throwing them.
- Fixed bug where instrumented type would count to auxiliary types and trigger injection strategy.
- Fixed bug where interface types would resolve to a non-generic type signature.
- Added strategy to use redefinition or retransformation of the `Instrumentation` API when building agents.
- Added lazy facade to be used by agent builder to improve performance for name-based matchers.
### 15. October 2015: version 0.7 (release candidate 5)
- Fixed parser to suppress exceptions from generic signatures which are not supposed to be included in the class file if no array type is generic.
- Fixed class validator which did not allow `<clinit>` blocks in interface types.
- Added restriction to retransformation to not attempt a retransformation at all if no class should be retransformed.
- Added a factory for creating an `Implementation.Context` that is configurable. This way, it is possible to avoid a rebase of a type initializer which is not always possible.
- Added a possibility to specify for an `AgentBuilder` how it should redefine or rebase a class that is intercepted.
### 13. October 2015: version 0.7 (release candidate 4)
- Fixed naming strategy for fields that cache values which chose duplicate names.
- Fixed resolution of raw types within the type hierarchy which were represented as non-generic `TypeDescription` instances where type variables of members were not resolved.
- Added possibility to specify hints for `ClassReader` and `ClassWriter` instances.
- Fixed resolution for modifiers of members that are defined by Byte Buddy. Previously, Byte Buddy would sometimes attempt to define private synthetic methods on generated interfaces.
- Fixed assignability resolution for arrays.
- Fixed class file parser which would not recognize outer classes for version 1.3 byte code.
### 6. October 2015: version 0.7 (release candidate 3)
- Read `Nexus` instances of the Byte Buddy agents from the enclosing class loader rather than from the system class loader. This allows for their usage from OSGi environments and for user with other custom class loaders.
- Changed modifiers for accessor methods and rebased methods to be public when rebasing or accessing methods of a Java 8 interface. For interfaces, all modifiers must be public, even for such synthetic members.
- Support absolute path names for accessing class file resources of the `ByteArrayClassLoader`.
- Added random suffix to the names of rebased methods to avoid naming conflicts.
### 16. September 2015: version 0.7 (release candidate 2)
- Refactored runtime attachment of Java agents to support Java 9 and additional legacy VM (version 8-).
- Refactored `MethodGraph` to only represent virtual methods.
- Changed notion of visibility to not longer consider the declaring type as part of the visibility.
- Increased flexibility of defining proxy types for `@Super` and `@Default` annotations.
- Added directional `AmbigouityResolver`.
- Fixed detection of methods that can be rebased to not include methods that did not previously exist.
### 11. August 2015: version 0.7 (release candidate 1)
- Added support for generic types.
- Replaced `MethodLookupEngine` with `MethodGraph.Compiler` to provide a richer data structure.
- Added support for bridge methods (type and visibility bridges).
- Refactored the predefined `ElementMatcher`s to allow for matching generic types.
- Replaced the `ModifierResolver` with a more general `MethodTransformer`.
### 11. August 2015: version 0.6.15
- Added support for discovery and handling of Java 9 VMs.
- Fixed class loading for Android 5 (Lollipop) API.
### 20. July 2015: version 0.6.14
- Fixed resolution of ignored methods. Previously, additional ignored methods were not appended but added as an additional criteria for ignoring a method.
### 17. July 2015: version 0.6.13
- Fixed resolution of field accessors to not attempt reading of non-static fields from static methods.
- Fixed renaming strategy for type redefinitions to work around a constraint of ASM where stack map frames required to be expanded even though this was not strictly necessary.
### 10. July 2015: version 0.6.12
- Added API for altering a method's modifiers when intercepting it.
- Added API for allowing to filter default values when writing annotations.
### 22. June 2015: version 0.6.11
- Added additional `ClassFileLocator`s for locating jar files in folders and jar files.
- Added explicit check for invalid access of instance fields from static methods in field accessing interceptors.
- Added the `@StubValue` and `@FieldValue` annotations.
### 18. June 2015: version 0.6.10 (and 0.6.9)
- Corrected the resolution of a type's visibility to another type to determine if a method can be legally overridden.
- Previous version 0.6.9 contained another bug when attempting to fix this problem.
Corrected incorrect deployment of version 0.6.7 which does not use a dependency reduced POM for the *byte-buddy* module.
### 1. June 2015: version 0.6.8 (and 0.6.7)
- Upgraded ASM dependency to 5.0.4.
- Fixed OSGi headers in all relevant artifacts.
*Warning*: The *byte-buddy* artifact of version 0.6.7 is accidentally deployed with a defect POM file which does not exclude the shaded resources.
### 28. May 2015: version 0.6.6
- Fixed error in resolution of the `TargetType` pseudo-variable when used as component type of an array.
### 7. May 2015: version 0.6.5
- Extended public API with convenience methods.
### 6. May 2015: version 0.6.4
- Extended public API to accept more general argument types when appropriate.
- Extended `@Origin` annotation to allow for accepting modifiers.
### 29. April 2015: version 0.6.3
- Made the `TypeDescription.ForLoadedType` class loader agnostic. Before, a class that was loaded by multiple class
loaders would have been considered inequal what is not true for the byte code level.
### 23. April 2015: version 0.6.2
- Added additional class validation such that it becomes impossible to define members on classes that do not fit
the class's structure, i.e. default methods on Java interfaces in version seven.
- Added default `Assigner` singleton.
### 21. April 2015: version 0.6.1
- Added `AnnotationDescription.Builder` to allow easy definition of annotation values without loading any values.
- Added possibility to define enumerations at runtime.
- Added possibility to dynamically read enumerations for the `MethodCall` and `InvokeDynamic` implementations.
- Further API clean-up.
### 15. April 2015: version 0.6
- Renamed the `Instrumentation` interface to `Implementation` to avoid naming conflicts with Java types.
- Renamed the `Field` annotation to `FieldProxy` to avoid naming conflicts with Java types.
- Refactored package structure to make the implementation more readable.
- Added possibility to define annotation default values.
- Avoid creation of an auxiliary placeholder type for method rebasements if it is not required.
- Avoid rebasing of methods if they are not instrumented.
- Reimplemented `TypeWriter`, `MethodRegistry` and other supporting infrastructure to make the code simpler.
- Refactored testing that is related to the previous infrastructure.
### 21. March 2015: version 0.5.6
- Added possibility to write parameter meta information to created classes if it is fully available for a method.
### 20. March 2015: version 0.5.5
- Retrofitted method parameters to be represented by `ParameterDescription`s and added possibility to extract names
and modifiers for these parameters, either by using the Java 8 API (if available) or by reading this information
from the underlying class file.
- Fixed a `NullPointerException` being thrown due to accidental return of a `null` value from a method.
### 15. March 2015: version 0.5.4
- Fixed missing retention of method annotations of instrumented types.
- Allowed dynamic lookup of methods for the `MethodCall` instrumentation.
### 24. February 2015: version 0.5.3
- Changed the `SuperMethodCall` instrumentation to fall back to a default method call if required. A different
behavior was found to surprise users and would introduce subtle bugs in user code as the super method instrumentation
would always work with subclassing due to Java super method call semantics.
- Added a `MethodCall` instrumentation that allows hard-coding a method call.
- Added an `InvokeDynamic` instrumentation that allows runtime dispatching by bootstrap methods.
- Fixed the default `TypePool` to retain generic signatures in order to avoid that agents delete such signatures.
- Fixed a bug in all of the the default `ConstructorStrategy` that effectively prevented intercepting of constructors.
### 18. January 2015: version 0.5.2
- Fixed a bug where interface generation would result in a `NullPointerException`.
- Added additional `ElementMatcher`s that allow to identify class loaders.
### 5. December 2014: version 0.5.1
Added the `andThen` method to the `SuperMethodCall` instrumentation in order to allow for a more convenient
executingTransformer interception where a hard-coded super method call is required by the Java verifier.
### 3. December 2014: version 0.5
- Added the `DeclaringTypeResolver` as a component in the default chain which selects the most specific method out
of two. This is mainly meant to avoid the accidental matching of the methods that are declared by the `Object` type.
- Added `TypeInitializer`s in order to allow `Instrumentation`s to define type initializer blocks.
- Replaced the `MethodMatcher` API with the `ElementMatcher` API which allows for a more sophisticated matching DSL.
- Added a `ClassLoadingStrategy` for Android in its own module.
- Introduced an `AgentBuilder` API and implementation.
### 26. November 2014: version 0.4.1
- Refactored the implementation of the `VoidAwareAssigner` which would otherwise cause unexpected behavior in its
default state.
- Added a missing boxing instruction to the `InvocationHandlerAdapter`.
### 18. November 2014: version 0.4
- Extended `Instrumentation.Context` to support field accessors.
- Added the `TypePool` abstraction and added a default implementation.
- Refactored annotations to have an intermediate form as `AnnotationDescription` which does not need to
represent loaded values.
- Refactored several built-in `Instrumentation`, among others, all implementations now support `TypeDescription`
in addition to loaded `Class` as their arguments
- Added several annotations that apply to the `MethodDelegation`.
### 19. September 2014: version 0.3.1
- Added support for optionally specifying a `ProtectionDomain` for the built-in `ClassLoadingStrategy` implementations.
- Fixed a bug in the resolution of resources of the `ByteArrayClassLoader` and its child-first implementation.
### 15. September 2014: version 0.3
- Added basic support for Java 7 types `MethodHandle` and `MethodType` which are available from Java 7 for injection.
- Added support for type redefinition and type rebasing.
- Added support for accessing a JVM's HotSwap features and a Java agent.
- Added latent a child-first `ClassLoadingStrategy` and manifest versions of the `WRAPPER` and `CHILD_FIRST` default
class loading strategies.
### 20. June 2014: version 0.2.1
- Added proper support for defining class initializers. Added support for field caching from method instrumentations,
mainly for allowing the reuse of `Method` instances for the `@Origin` annotation and the `InvocationHandlerAdapter`.
### 16. June 2014: version 0.2
- Changed the semantics of the `@SuperCall` to be only bindable, if a super method can be invoked. Before, an
exception was thrown if only a non-existent or abstract super method was found.
- Added features for the interaction with Java 8 default methods. Refactored method lookup to extract invokable
default methods.
- Refactored the invocation of super methods to be created by an `Instrumentation.Target`. For a future release,
this hopefully allows for class redefinitions using today's API for creating subclasses.
- Upgraded to ASM 5.0.3.
### 02. May 2014: version 0.1
- First general release.
|
raphw/byte-buddy
|
release-notes.md
|
Markdown
|
apache-2.0
| 74,053
|
document.addEventListener('DOMContentLoaded', function() {
var YouTubeButton = document.getElementById('YouTube');
YouTubeButton.addEventListener('click', function() {
chrome.tabs.getSelected(null, function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://youtube.com';
f.method = 'post';
var i = d.createElement('input');
i.type = 'hidden';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
});
}, false);
}, false);
document.addEventListener('DOMContentLoaded', function() {
var RedditButton = document.getElementById('Reddit');
RedditButton.addEventListener('click', function() {
chrome.tabs.getSelected(null, function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://reddit.com';
f.method = 'post';
var i = d.createElement('input');
i.type = 'hidden';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
});
}, false);
}, false);
|
CoCaBoJangLeS/ExtensionWizards
|
pip_extension/popup.js
|
JavaScript
|
apache-2.0
| 1,120
|
/***********************************************************************
* Copyright (c) 2013-2019 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
***********************************************************************/
package org.locationtech.geomesa.features.avro.serde
import java.nio.ByteBuffer
import org.locationtech.jts.io.InStream
import org.apache.avro.io.Decoder
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.features.avro.AvroSimpleFeature
import org.locationtech.geomesa.utils.text.{WKBUtils, WKTUtils}
/**
* AvroSimpleFeature version 2 changes serialization of Geometry types from
* WKT (Well Known Text) to WKB (Well Known Binary)
*/
object Version2Deserializer extends ASFDeserializer
|
elahrvivaz/geomesa
|
geomesa-features/geomesa-feature-avro/src/main/scala/org/locationtech/geomesa/features/avro/serde/Version2Deserializer.scala
|
Scala
|
apache-2.0
| 998
|
# -*- coding: utf-8 -*-
"""
Problem Statement
Samantha and Sam are playing a game. They have 'N' balls in front of them, each ball numbered from 0 to 9, except the
first ball which is numbered from 1 to 9. Samantha calculates all the sub-strings of the number thus formed, one by one.
If the sub-string is S, Sam has to throw 'S' candies into an initially empty box. At the end of the game, Sam has to
find out the total number of candies in the box, T. As T can be large, Samantha asks Sam to tell T % (109+7) instead.
If Sam answers correctly, he can keep all the candies. Sam can't take all this Maths and asks for your help.
"""
__author__ = 'Danyang'
MOD = 1e9 + 7
class Solution(object):
def solve_TLE(self, cipher):
"""
O(N^2)
:param cipher: the cipher
"""
A = map(int, list(cipher))
f = A[0]
num = A[0]
sig = 1
for i in xrange(1, len(A)):
num = 10 * num + A[i]
sig *= 10
temp = num
temp_sig = sig
while temp_sig >= 1:
f += temp
f %= MOD
temp %= temp_sig
temp_sig /= 10
return int(f)
def solve(self, cipher):
"""
O(N)
example: 1234
1
12, 2
123, 23, 3
1234, 234, 34, 4
:param cipher:
:return:
"""
pre = [0 for _ in cipher]
pre[0] = int(cipher[0])
for i in xrange(1, len(cipher)):
pre[i] = (pre[i - 1] * 10 + int(cipher[i]) * (i + 1)) % MOD
s = 0
for elt in pre:
s = (s + elt) % MOD
return int(s)
if __name__ == "__main__":
import sys
f = open("0.in", "r")
# f = sys.stdin
solution = Solution()
# construct cipher
cipher = f.readline().strip()
# solve
s = "%s\n" % (solution.solve(cipher))
print s,
|
algorhythms/HackerRankAlgorithms
|
Sam and sub-strings.py
|
Python
|
apache-2.0
| 1,919
|
package com.mygdx.game.Dungeon;
import com.badlogic.gdx.math.GridPoint2;
import com.badlogic.gdx.utils.Array;
import com.mygdx.game.Characters.*;
import com.mygdx.game.Dungeon.DungeonTiles.EmptyDungeonTile;
import com.mygdx.game.Dungeon.DungeonTiles.StairsDownDungeonTile;
import com.mygdx.game.Dungeon.DungeonTiles.StairsUpDungeonTile;
import com.mygdx.game.Dungeon.Rooms.Room;
import com.mygdx.game.PathFinding.AstarNode;
import com.mygdx.game.Renderers.DungeonRenderer;
public class Dungeon {
private static Dungeon activeDungeon;
//TODO create a renderable interface and have a list of renderables to iterate through
public final DungeonRenderer renderer;
public final Array<CharacterEntity> monsters;
private final DungeonTile[][] map;
private final Array<Room> dungeonRooms;
private final int mapWidth;
private final int mapHeight;
private float[][] lineOfSightResMap;
int level;
StairsDownDungeonTile stairsDownDungeonTile;
StairsUpDungeonTile stairsUpDungeonTile;
Dungeon floorAbove;
Dungeon floorBelow;
Room startRoom;
public static void setActiveDungeon(Dungeon dungeon){
activeDungeon = dungeon;
}
public static Dungeon getActiveDungeon(){
return activeDungeon;
}
public Dungeon(int mapWidth, int mapHeight){
this.mapWidth = mapWidth;
this.mapHeight = mapHeight;
renderer = new DungeonRenderer(this);
map = new DungeonTile[mapWidth+2][mapHeight+2];
for(int i = 0; i < mapWidth+2; i++){
for (int j = 0; j < mapHeight+2; j++){
map[i][j] = new EmptyDungeonTile(new GridPoint2(i-1, j-1), this);
}
}
dungeonRooms = new Array<>();
monsters = new Array<>();
level = 1;
}
public Dungeon(int mapWidth, int mapHeight, Dungeon floorAbove) {
this(mapWidth, mapHeight);
level = floorAbove.getLevel() + 1;
this.floorAbove = floorAbove;
}
public int getRoomCount(){
return dungeonRooms.size;
}
public int getMapWidth(){
return mapWidth;
}
public int getMapHeight(){
return mapHeight;
}
void addDungeonRoom(Room dungeonRoom) {
dungeonRooms.add(dungeonRoom);
}
public Room getDungeonRoom(int roomId) {
return dungeonRooms.get(roomId);
}
public boolean isTilePassable(GridPoint2 pos){
return map[pos.x+1][pos.y+1].isPassable();
}
public DungeonTile getDungeonTile(GridPoint2 pos){
return map[pos.x+1][pos.y+1];
}
public DungeonTile getDungeonTile(int x, int y){
return map[x+1][y+1];
}
public void setTile(DungeonTile dungeonTile) {
GridPoint2 pos = dungeonTile.getPos();
map[pos.x+1][pos.y+1] = dungeonTile;
}
boolean isTileEmpty(GridPoint2 pos) {
return map[pos.x][pos.y].isEmpty();
}
Array<Array<AstarNode>> getAstarGraph(){
Array<Array<AstarNode>> astarGraph = new Array<>();
for(int i = 0; i < getMapWidth(); i++){
astarGraph.add(new Array<>());
}
for (int i = 0; i < getMapWidth(); i++){
for(int j = 0; j < getMapHeight(); j++){
AstarNode node = new AstarNode();
node.passingCost = getDungeonTile(new GridPoint2(i, j)).getPassingCost();
node.x = i;
node.y = j;
astarGraph.get(i).add(node);
}
}
return astarGraph;
}
// Updates a grid of 1s or 0s that represent if a tile is visible. Used by the LOS algo.
void updateLineOfSightResistanceMap(){
lineOfSightResMap = new float[mapWidth+2][mapHeight+2];
for (int i = 0; i < mapWidth+2; i++){
for (int j = 0; j < mapHeight+2; j++){
if(map[i][j].isVisionObstructing()){
lineOfSightResMap[i][j] = 1;
} else {
lineOfSightResMap[i][j] = 0;
}
}
}
}
public Room getStartRoom() {
return startRoom;
}
public Dungeon getFloorAbove(){
return floorAbove;
}
public Dungeon getFloorBelow(){
if (floorBelow == null){
return floorBelow = DungeonGeneratorFactory.getDungeonGenerator(getLevel()+1).generateDungeonBelow(this);
} else {
return floorBelow;
}
}
public int getLevel() {
return level;
}
public StairsDownDungeonTile getStairsDownDungeonTile() {
return stairsDownDungeonTile;
}
public StairsUpDungeonTile getStairsUpDungeonTile() {
return stairsUpDungeonTile;
}
}
|
Tatskaari/DungeonCrawler
|
core/src/com/mygdx/game/Dungeon/Dungeon.java
|
Java
|
apache-2.0
| 4,702
|
package com.castleby.invoice.repo;
import java.time.LocalDate;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.castleby.invoice.TestBaseClass;
import com.castleby.invoice.entity.Invoice;
import com.castleby.invoice.entity.repo.InvoiceRepository;
@Test
public class TestInvoiceRepository extends TestBaseClass {
@Autowired
private InvoiceRepository repository;
@BeforeMethod
public void before() {
for (Invoice invoice : repository.findAll()) {
repository.delete(invoice);
}
}
@Test
public void testCreateInvoice() {
Invoice invoice = new Invoice();
int size = repository.findAll().size();
invoice = repository.saveAndFlush(invoice);
Assert.assertEquals(size + 1, repository.findAll().size());
}
@Test
public void testDeleteInvoice() {
Invoice invoice = new Invoice();
int size = repository.findAll().size();
invoice = repository.saveAndFlush(invoice);
repository.delete(invoice.getId());
Assert.assertEquals(size, repository.findAll().size());
}
@Test
public void testFindByDateInvoice() {
Date currentDate = new Date();
Invoice invoice = new Invoice();
invoice.setDate(currentDate);
invoice = repository.saveAndFlush(invoice);
Date startDate = new Date(currentDate.getYear(), currentDate.getMonth(), 1);
LocalDate initial = LocalDate.of(currentDate.getYear(), currentDate.getMonth(), 1);
Date endDate = new Date(currentDate.getYear(), currentDate.getMonth(), initial.lengthOfMonth());
Invoice findByDateBetween = repository.findByDateBetween(startDate, endDate);
Assert.assertEquals(invoice, findByDateBetween);
}
}
|
tarasklym/reports
|
src/test/java/com/castleby/invoice/repo/TestInvoiceRepository.java
|
Java
|
apache-2.0
| 1,938
|
# Pedobesia simplex (Meneghini ex Kützing) M.J. Wynne & Leliaert SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Chlorophyta/Bryopsidophyceae/Bryopsidales/Derbesiaceae/Pedobesia/Pedobesia simplex/README.md
|
Markdown
|
apache-2.0
| 221
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.s3a.impl;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.impl.WrappedIOException;
import org.apache.hadoop.util.DurationInfo;
import static org.apache.hadoop.fs.impl.FutureIOSupport.raiseInnerCause;
/**
* A bridge from Callable to Supplier; catching exceptions
* raised by the callable and wrapping them as appropriate.
* @param <T> return type.
*/
public final class CallableSupplier<T> implements Supplier {
private static final Logger LOG =
LoggerFactory.getLogger(CallableSupplier.class);
private final Callable<T> call;
/**
* Create.
* @param call call to invoke.
*/
public CallableSupplier(final Callable<T> call) {
this.call = call;
}
@Override
public Object get() {
try {
return call.call();
} catch (RuntimeException e) {
throw e;
} catch (IOException e) {
throw new WrappedIOException(e);
} catch (Exception e) {
throw new WrappedIOException(new IOException(e));
}
}
/**
* Submit a callable into a completable future.
* RTEs are rethrown.
* Non RTEs are caught and wrapped; IOExceptions to
* {@link WrappedIOException} instances.
* @param executor executor.
* @param call call to invoke
* @param <T> type
* @return the future to wait for
*/
@SuppressWarnings("unchecked")
public static <T> CompletableFuture<T> submit(
final Executor executor,
final Callable<T> call) {
return CompletableFuture.supplyAsync(
new CallableSupplier<T>(call), executor);
}
/**
* Wait for a list of futures to complete. If the list is empty,
* return immediately.
* @param futures list of futures.
* @throws IOException if one of the called futures raised an IOE.
* @throws RuntimeException if one of the futures raised one.
*/
public static <T> void waitForCompletion(
final List<CompletableFuture<T>> futures)
throws IOException {
if (futures.isEmpty()) {
return;
}
// await completion
waitForCompletion(CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0])));
}
/**
* Wait for a single of future to complete, extracting IOEs afterwards.
* @param future future to wait for.
* @throws IOException if one of the called futures raised an IOE.
* @throws RuntimeException if one of the futures raised one.
*/
public static <T> void waitForCompletion(
final CompletableFuture<T> future)
throws IOException {
try (DurationInfo ignore =
new DurationInfo(LOG, false, "Waiting for task completion")) {
future.join();
} catch (CancellationException e) {
throw new IOException(e);
} catch (CompletionException e) {
raiseInnerCause(e);
}
}
}
|
lukmajercak/hadoop
|
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/CallableSupplier.java
|
Java
|
apache-2.0
| 3,916
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.jps.builders.java.dependencyView;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.io.IntInlineKeyDescriptor;
import gnu.trove.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.builders.storage.BuildDataCorruptedException;
import org.jetbrains.jps.incremental.storage.FileKeyDescriptor;
import org.jetbrains.jps.service.JpsServiceManager;
import org.jetbrains.org.objectweb.asm.ClassReader;
import org.jetbrains.org.objectweb.asm.Opcodes;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.annotation.RetentionPolicy;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author: db
*/
public class Mappings {
private final static Logger LOG = Logger.getInstance("#org.jetbrains.ether.dependencyView.Mappings");
private final static String CLASS_TO_SUBCLASSES = "classToSubclasses.tab";
private final static String CLASS_TO_CLASS = "classToClass.tab";
private final static String SHORT_NAMES = "shortNames.tab";
private final static String SOURCE_TO_CLASS = "sourceToClass.tab";
private final static String CLASS_TO_SOURCE = "classToSource.tab";
private static final IntInlineKeyDescriptor INT_KEY_DESCRIPTOR = new IntInlineKeyDescriptor();
private static final int DEFAULT_SET_CAPACITY = 32;
private static final float DEFAULT_SET_LOAD_FACTOR = 0.98f;
private final boolean myIsDelta;
private final boolean myDeltaIsTransient;
private boolean myIsDifferentiated = false;
private boolean myIsRebuild = false;
private final TIntHashSet myChangedClasses;
private final THashSet<File> myChangedFiles;
private final Set<Pair<ClassFileRepr, File>> myDeletedClasses;
private final Set<ClassRepr> myAddedClasses;
private final Object myLock;
private final File myRootDir;
private DependencyContext myContext;
private final int myInitName;
private final int myEmptyName;
private final int myObjectClassName;
private LoggerWrapper<Integer> myDebugS;
private IntIntMultiMaplet myClassToSubclasses;
/**
key: the name of a class who is used;
values: class names that use the class registered as the key
*/
private IntIntMultiMaplet myClassToClassDependency;
private ObjectObjectMultiMaplet<File, ClassFileRepr> mySourceFileToClasses;
private IntObjectMultiMaplet<File> myClassToSourceFile;
/**
* [short className] -> list of FQ names
*/
private IntIntMultiMaplet myShortClassNameIndex;
private IntIntTransientMultiMaplet myRemovedSuperClasses;
private IntIntTransientMultiMaplet myAddedSuperClasses;
@Nullable
private Collection<String> myRemovedFiles;
private Mappings(final Mappings base) throws IOException {
myLock = base.myLock;
myIsDelta = true;
myChangedClasses = new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
myChangedFiles = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
myDeletedClasses = new HashSet<>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
myAddedClasses = new HashSet<>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
myDeltaIsTransient = base.myDeltaIsTransient;
myRootDir = new File(FileUtil.toSystemIndependentName(base.myRootDir.getAbsolutePath()) + File.separatorChar + "myDelta");
myContext = base.myContext;
myInitName = myContext.get("<init>");
myEmptyName = myContext.get("");
myObjectClassName = myContext.get("java/lang/Object");
myDebugS = base.myDebugS;
createImplementation();
}
public Mappings(final File rootDir, final boolean transientDelta) throws IOException {
myLock = new Object();
myIsDelta = false;
myChangedClasses = null;
myChangedFiles = null;
myDeletedClasses = null;
myAddedClasses = null;
myDeltaIsTransient = transientDelta;
myRootDir = rootDir;
createImplementation();
myInitName = myContext.get("<init>");
myEmptyName = myContext.get("");
myObjectClassName = myContext.get("java/lang/Object");
}
private void createImplementation() throws IOException {
if (!myIsDelta) {
myContext = new DependencyContext(myRootDir);
myDebugS = myContext.getLogger(LOG);
}
myRemovedSuperClasses = myIsDelta ? new IntIntTransientMultiMaplet() : null;
myAddedSuperClasses = myIsDelta ? new IntIntTransientMultiMaplet() : null;
final CollectionFactory<File> fileCollectionFactory = new CollectionFactory<File>() {
@Override
public Collection<File> create() {
return new THashSet<>(FileUtil.FILE_HASHING_STRATEGY); // todo: do we really need set and not a list here?
}
};
if (myIsDelta && myDeltaIsTransient) {
myClassToSubclasses = new IntIntTransientMultiMaplet();
myClassToClassDependency = new IntIntTransientMultiMaplet();
myShortClassNameIndex = null;
mySourceFileToClasses = new ObjectObjectTransientMultiMaplet<>(FileUtil.FILE_HASHING_STRATEGY, () -> new THashSet<>(5, DEFAULT_SET_LOAD_FACTOR));
myClassToSourceFile = new IntObjectTransientMultiMaplet<>(fileCollectionFactory);
}
else {
if (myIsDelta) {
myRootDir.mkdirs();
}
myClassToSubclasses = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_SUBCLASSES), INT_KEY_DESCRIPTOR);
myClassToClassDependency = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_CLASS), INT_KEY_DESCRIPTOR);
myShortClassNameIndex = myIsDelta? null : new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, SHORT_NAMES), INT_KEY_DESCRIPTOR);
mySourceFileToClasses = new ObjectObjectPersistentMultiMaplet<>(
DependencyContext.getTableFile(myRootDir, SOURCE_TO_CLASS), new FileKeyDescriptor(), new ClassFileReprExternalizer(myContext),
() -> new THashSet<>(5, DEFAULT_SET_LOAD_FACTOR)
);
myClassToSourceFile = new IntObjectPersistentMultiMaplet<>(
DependencyContext.getTableFile(myRootDir, CLASS_TO_SOURCE), INT_KEY_DESCRIPTOR, new FileKeyDescriptor(), fileCollectionFactory
);
}
}
public String valueOf(final int name) {
return myContext.getValue(name);
}
public int getName(final String string) {
return myContext.get(string);
}
public Mappings createDelta() {
synchronized (myLock) {
try {
return new Mappings(this);
}
catch (IOException e) {
throw new BuildDataCorruptedException(e);
}
}
}
private void compensateRemovedContent(final @NotNull Collection<File> compiled, final @NotNull Collection<File> compiledWithErrors) {
for (final File file : compiled) {
if (!compiledWithErrors.contains(file) && !mySourceFileToClasses.containsKey(file)) {
mySourceFileToClasses.put(file, new HashSet<>());
}
}
}
@Nullable
private ClassRepr getClassReprByName(final @Nullable File source, final int qName) {
final ClassFileRepr reprByName = getReprByName(source, qName);
return reprByName instanceof ClassRepr? (ClassRepr)reprByName : null;
}
@Nullable
private ClassFileRepr getReprByName(@Nullable File source, int qName) {
final Collection<File> sources = source != null? Collections.singleton(source) : myClassToSourceFile.get(qName);
if (sources != null) {
for (File src : sources) {
final Collection<ClassFileRepr> reprs = mySourceFileToClasses.get(src);
if (reprs != null) {
for (ClassFileRepr repr : reprs) {
if (repr.name == qName) {
return repr;
}
}
}
}
}
return null;
}
public void clean() throws IOException {
if (myRootDir != null) {
synchronized (myLock) {
close();
FileUtil.delete(myRootDir);
createImplementation();
}
}
}
public IntIntTransientMultiMaplet getRemovedSuperClasses() {
return myRemovedSuperClasses;
}
public IntIntTransientMultiMaplet getAddedSuperClasses() {
return myAddedSuperClasses;
}
private final LinkedBlockingQueue<Runnable> myPostPasses = new LinkedBlockingQueue<>();
private void runPostPasses() {
final Set<Pair<ClassFileRepr, File>> deleted = myDeletedClasses;
if (deleted != null) {
for (Pair<ClassFileRepr, File> pair : deleted) {
final int deletedClassName = pair.first.name;
final Collection<File> sources = myClassToSourceFile.get(deletedClassName);
if (sources == null || sources.isEmpty()) { // if really deleted and not e.g. moved
myChangedClasses.remove(deletedClassName);
}
}
}
for (Runnable pass = myPostPasses.poll(); pass != null; pass = myPostPasses.poll()) {
pass.run();
}
}
private static final ClassRepr MOCK_CLASS = null;
private static final MethodRepr MOCK_METHOD = null;
private interface MemberComparator {
boolean isSame(ProtoMember member);
}
private class Util {
@Nullable
private final Mappings myMappings;
private Util() {
myMappings = null;
}
private Util(@NotNull Mappings mappings) {
myMappings = mappings;
}
void appendDependents(final ClassFileRepr c, final TIntHashSet result) {
final TIntHashSet depClasses = myClassToClassDependency.get(c.name);
if (depClasses != null) {
addAll(result, depClasses);
}
}
void propagateMemberAccessRec(final TIntHashSet acc, final boolean isField, final boolean root, final MemberComparator comparator, final int reflcass) {
final ClassRepr repr = classReprByName(reflcass);
if (repr != null) {
if (!root) {
final Set<? extends ProtoMember> members = isField ? repr.getFields() : repr.getMethods();
for (ProtoMember m : members) {
if (comparator.isSame(m)) {
return;
}
}
if (!acc.add(reflcass)) {
return; // SOE prevention
}
}
final TIntHashSet subclasses = myClassToSubclasses.get(reflcass);
if (subclasses != null) {
subclasses.forEach(subclass -> {
propagateMemberAccessRec(acc, isField, false, comparator, subclass);
return true;
});
}
}
}
TIntHashSet propagateMemberAccess(final boolean isField, final MemberComparator comparator, final int className) {
final TIntHashSet acc = new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
propagateMemberAccessRec(acc, isField, true, comparator, className);
return acc;
}
TIntHashSet propagateFieldAccess(final int name, final int className) {
return propagateMemberAccess(true, new MemberComparator() {
@Override
public boolean isSame(ProtoMember member) {
return member.name == name;
}
}, className);
}
TIntHashSet propagateMethodAccess(final MethodRepr m, final int className) {
return propagateMemberAccess(false, new MemberComparator() {
@Override
public boolean isSame(ProtoMember member) {
if (member instanceof MethodRepr) {
final MethodRepr memberMethod = (MethodRepr)member;
return memberMethod.name == m.name && Arrays.equals(memberMethod.myArgumentTypes, m.myArgumentTypes);
}
return false;
}
}, className);
}
MethodRepr.Predicate lessSpecific(final MethodRepr than) {
return new MethodRepr.Predicate() {
@Override
public boolean satisfy(final MethodRepr m) {
if (m.name == myInitName || m.name != than.name || m.myArgumentTypes.length != than.myArgumentTypes.length) {
return false;
}
for (int i = 0; i < than.myArgumentTypes.length; i++) {
final Boolean subtypeOf = isSubtypeOf(than.myArgumentTypes[i], m.myArgumentTypes[i]);
if (subtypeOf != null && !subtypeOf) {
return false;
}
}
return true;
}
};
}
private void addOverridingMethods(final MethodRepr m, final ClassRepr fromClass, final MethodRepr.Predicate predicate, final Collection<Pair<MethodRepr, ClassRepr>> container, TIntHashSet visitedClasses) {
if (m.name == myInitName) {
return; // overriding is not defined for constructors
}
final TIntHashSet subClasses = myClassToSubclasses.get(fromClass.name);
if (subClasses == null) {
return;
}
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
}
if (!visitedClasses.add(fromClass.name)) {
return;
}
final TIntHashSet _visitedClasses = visitedClasses;
subClasses.forEach(subClassName -> {
final ClassRepr r = classReprByName(subClassName);
if (r != null) {
boolean cont = true;
final Collection<MethodRepr> methods = r.findMethods(predicate);
for (MethodRepr mm : methods) {
if (isVisibleIn(fromClass, m, r)) {
container.add(Pair.create(mm, r));
cont = false;
}
}
if (cont) {
addOverridingMethods(m, r, predicate, container, _visitedClasses);
}
}
return true;
});
}
private Collection<Pair<MethodRepr, ClassRepr>> findAllMethodsBySpecificity(final MethodRepr m, final ClassRepr c) {
final MethodRepr.Predicate predicate = lessSpecific(m);
final Collection<Pair<MethodRepr, ClassRepr>> result = new HashSet<>();
addOverridenMethods(c, predicate, result, null);
addOverridingMethods(m, c, predicate, result, null);
return result;
}
private Collection<Pair<MethodRepr, ClassRepr>> findOverriddenMethods(final MethodRepr m, final ClassRepr c) {
if (m.name == myInitName) {
return Collections.emptySet(); // overriding is not defined for constructors
}
final Collection<Pair<MethodRepr, ClassRepr>> result = new HashSet<>();
addOverridenMethods(c, MethodRepr.equalByJavaRules(m), result, null);
return result;
}
private boolean hasOverriddenMethods(final ClassRepr fromClass, final MethodRepr.Predicate predicate, TIntHashSet visitedClasses) {
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
visitedClasses.add(fromClass.name);
}
for (int superName : fromClass.getSupers()) {
if (!visitedClasses.add(superName) || superName == myObjectClassName) {
continue;
}
final ClassRepr superClass = classReprByName(superName);
if (superClass != null) {
for (MethodRepr mm : superClass.findMethods(predicate)) {
if (isVisibleIn(superClass, mm, fromClass)) {
return true;
}
}
if (hasOverriddenMethods(superClass, predicate, visitedClasses)) {
return true;
}
}
}
return false;
}
private boolean extendsLibraryClass(final ClassRepr fromClass, TIntHashSet visitedClasses) {
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
visitedClasses.add(fromClass.name);
}
for (int superName : fromClass.getSupers()) {
if (!visitedClasses.add(superName) || superName == myObjectClassName) {
continue;
}
final ClassRepr superClass = classReprByName(superName);
if (superClass == null || extendsLibraryClass(superClass, visitedClasses)) {
return true;
}
}
return false;
}
private void addOverridenMethods(final ClassRepr fromClass, final MethodRepr.Predicate predicate, final Collection<Pair<MethodRepr, ClassRepr>> container, TIntHashSet visitedClasses) {
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
visitedClasses.add(fromClass.name);
}
for (int superName : fromClass.getSupers()) {
if (!visitedClasses.add(superName)) {
continue; // prevent SOE
}
final ClassRepr superClass = classReprByName(superName);
if (superClass != null) {
boolean cont = true;
final Collection<MethodRepr> methods = superClass.findMethods(predicate);
for (MethodRepr mm : methods) {
if (isVisibleIn(superClass, mm, fromClass)) {
container.add(Pair.create(mm, superClass));
cont = false;
}
}
if (cont) {
addOverridenMethods(superClass, predicate, container, visitedClasses);
}
}
else {
container.add(Pair.create(MOCK_METHOD, MOCK_CLASS));
}
}
}
void addOverriddenFields(final FieldRepr f, final ClassRepr fromClass, final Collection<Pair<FieldRepr, ClassRepr>> container, TIntHashSet visitedClasses) {
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
visitedClasses.add(fromClass.name);
}
for (int supername : fromClass.getSupers()) {
if (!visitedClasses.add(supername) || supername == myObjectClassName) {
continue;
}
final ClassRepr superClass = classReprByName(supername);
if (superClass != null) {
final FieldRepr ff = superClass.findField(f.name);
if (ff != null && isVisibleIn(superClass, ff, fromClass)) {
container.add(Pair.create(ff, superClass));
}
else{
addOverriddenFields(f, superClass, container, visitedClasses);
}
}
}
}
boolean hasOverriddenFields(final FieldRepr f, final ClassRepr fromClass, TIntHashSet visitedClasses) {
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
visitedClasses.add(fromClass.name);
}
for (int supername : fromClass.getSupers()) {
if (!visitedClasses.add(supername) || supername == myObjectClassName) {
continue;
}
final ClassRepr superClass = classReprByName(supername);
if (superClass != null) {
final FieldRepr ff = superClass.findField(f.name);
if (ff != null && isVisibleIn(superClass, ff, fromClass)) {
return true;
}
final boolean found = hasOverriddenFields(f, superClass, visitedClasses);
if (found) {
return true;
}
}
}
return false;
}
@Nullable
ClassRepr classReprByName(final int name) {
final ClassFileRepr r = reprByName(name);
return r instanceof ClassRepr? (ClassRepr)r : null;
}
@Nullable
ModuleRepr moduleReprByName(final int name) {
final ClassFileRepr r = reprByName(name);
return r instanceof ModuleRepr? (ModuleRepr)r : null;
}
@Nullable
ClassFileRepr reprByName(final int name) {
if (myMappings != null) {
final ClassFileRepr r = myMappings.getReprByName(null, name);
if (r != null) {
return r;
}
}
return getReprByName(null, name);
}
@Nullable
private Boolean isInheritorOf(final int who, final int whom, TIntHashSet visitedClasses) {
if (who == whom) {
return Boolean.TRUE;
}
final ClassRepr repr = classReprByName(who);
if (repr != null) {
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
visitedClasses.add(who);
}
for (int s : repr.getSupers()) {
if (!visitedClasses.add(s)) {
continue;
}
final Boolean inheritorOf = isInheritorOf(s, whom, visitedClasses);
if (inheritorOf != null && inheritorOf) {
return inheritorOf;
}
}
}
return null;
}
@Nullable
Boolean isSubtypeOf(final TypeRepr.AbstractType who, final TypeRepr.AbstractType whom) {
if (who.equals(whom)) {
return Boolean.TRUE;
}
if (who instanceof TypeRepr.PrimitiveType || whom instanceof TypeRepr.PrimitiveType) {
return Boolean.FALSE;
}
if (who instanceof TypeRepr.ArrayType) {
if (whom instanceof TypeRepr.ArrayType) {
return isSubtypeOf(((TypeRepr.ArrayType)who).elementType, ((TypeRepr.ArrayType)whom).elementType);
}
final String descr = whom.getDescr(myContext);
if (descr.equals("Ljava/lang/Cloneable") || descr.equals("Ljava/lang/Object") || descr.equals("Ljava/io/Serializable")) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
if (whom instanceof TypeRepr.ClassType) {
return isInheritorOf(((TypeRepr.ClassType)who).className, ((TypeRepr.ClassType)whom).className, null);
}
return Boolean.FALSE;
}
boolean isMethodVisible(final ClassRepr classRepr, final MethodRepr m) {
return classRepr.findMethods(MethodRepr.equalByJavaRules(m)).size() > 0 || hasOverriddenMethods(classRepr, MethodRepr.equalByJavaRules(m), null);
}
boolean isFieldVisible(final int className, final FieldRepr field) {
final ClassRepr r = classReprByName(className);
if (r == null || r.getFields().contains(field)) {
return true;
}
return hasOverriddenFields(field, r, null);
}
void collectSupersRecursively(final int className, @NotNull final TIntHashSet container) {
final ClassRepr classRepr = classReprByName(className);
if (classRepr != null) {
final int[] supers = classRepr.getSupers();
if (container.addAll(supers)) {
for (int aSuper : supers) {
collectSupersRecursively(aSuper, container);
}
}
}
}
void affectSubclasses(final int className, final Collection<File> affectedFiles, final Collection<UsageRepr.Usage> affectedUsages, final TIntHashSet dependants, final boolean usages, final Collection<File> alreadyCompiledFiles, TIntHashSet visitedClasses) {
debug("Affecting subclasses of class: ", className);
final Collection<File> allSources = myClassToSourceFile.get(className);
if (allSources == null || allSources.isEmpty()) {
debug("No source file detected for class ", className);
debug("End of affectSubclasses");
return;
}
for (File fName : allSources) {
debug("Source file name: ", fName);
if (!alreadyCompiledFiles.contains(fName)) {
affectedFiles.add(fName);
}
}
if (usages) {
debug("Class usages affection requested");
final ClassRepr classRepr = classReprByName(className);
if (classRepr != null) {
debug("Added class usage for ", classRepr.name);
affectedUsages.add(classRepr.createUsage());
}
}
final TIntHashSet depClasses = myClassToClassDependency.get(className);
if (depClasses != null) {
addAll(dependants, depClasses);
}
final TIntHashSet directSubclasses = myClassToSubclasses.get(className);
if (directSubclasses != null) {
if (visitedClasses == null) {
visitedClasses = new TIntHashSet();
visitedClasses.add(className);
}
final TIntHashSet _visitedClasses = visitedClasses;
directSubclasses.forEach(subClass -> {
if (_visitedClasses.add(subClass)) {
affectSubclasses(subClass, affectedFiles, affectedUsages, dependants, usages, alreadyCompiledFiles, _visitedClasses);
}
return true;
});
}
}
void affectFieldUsages(final FieldRepr field, final TIntHashSet classes, final UsageRepr.Usage rootUsage, final Set<UsageRepr.Usage> affectedUsages, final TIntHashSet dependents) {
affectedUsages.add(rootUsage);
classes.forEach(p -> {
final TIntHashSet deps = myClassToClassDependency.get(p);
if (deps != null) {
addAll(dependents, deps);
}
debug("Affect field usage referenced of class ", p);
affectedUsages.add(rootUsage instanceof UsageRepr.FieldAssignUsage ? field.createAssignUsage(myContext, p) : field.createUsage(myContext, p));
return true;
});
}
void affectMethodUsages(final MethodRepr method, final TIntHashSet subclasses, final UsageRepr.Usage rootUsage, final Set<UsageRepr.Usage> affectedUsages, final TIntHashSet dependents) {
affectedUsages.add(rootUsage);
if (subclasses != null) {
subclasses.forEach(p -> {
final TIntHashSet deps = myClassToClassDependency.get(p);
if (deps != null) {
addAll(dependents, deps);
}
debug("Affect method usage referenced of class ", p);
final UsageRepr.Usage usage =
rootUsage instanceof UsageRepr.MetaMethodUsage ? method.createMetaUsage(myContext, p) : method.createUsage(myContext, p);
affectedUsages.add(usage);
return true;
});
}
}
void affectModule(ModuleRepr m, final Collection<File> affectedFiles) {
Collection<File> depFiles = myMappings != null? myMappings.myClassToSourceFile.get(m.name) : null;
if (depFiles == null) {
depFiles = myClassToSourceFile.get(m.name);
}
if (depFiles != null) {
debug("Affecting module ", m.name);
affectedFiles.addAll(depFiles);
}
}
void affectDependentModules(Differential.DiffState state, final int moduleName, @Nullable UsageConstraint constraint, boolean checkTransitive) {
new Object() {
final TIntHashSet visited = new TIntHashSet();
void perform(final int modName) {
final TIntHashSet depNames = myClassToClassDependency.get(modName);
if (depNames != null && !depNames.isEmpty()) {
final TIntHashSet next = new TIntHashSet();
final UsageRepr.Usage moduleUsage = UsageRepr.createModuleUsage(myContext, modName);
state.myAffectedUsages.add(moduleUsage);
final UsageConstraint prevConstraint = state.myUsageConstraints.put(moduleUsage, constraint == null? UsageConstraint.ANY : constraint);
if (prevConstraint != null) {
state.myUsageConstraints.put(moduleUsage, prevConstraint.or(constraint));
}
depNames.forEach(depName -> {
if (visited.add(depName)) {
final ClassFileRepr depRepr = reprByName(depName);
if (depRepr instanceof ModuleRepr) {
state.myDependants.add(depName);
if (checkTransitive && ((ModuleRepr)depRepr).requiresTransitevely(modName)) {
next.add(depName);
}
}
}
return true;
});
next.forEach(m -> {
perform(m);
return true;
});
}
}
}.perform(moduleName);
}
public class FileFilterConstraint implements UsageConstraint {
@NotNull
private final DependentFilesFilter myFilter;
public FileFilterConstraint(@NotNull DependentFilesFilter filter) {
myFilter = filter;
}
@Override
public boolean checkResidence(int residence) {
final Collection<File> fNames = myClassToSourceFile.get(residence);
if (fNames == null || fNames.isEmpty()) {
return true;
}
for (File fName : fNames) {
if (myFilter.accept(fName)) {
return true;
}
}
return false;
}
}
public class PackageConstraint implements UsageConstraint {
public final String packageName;
public PackageConstraint(final String packageName) {
this.packageName = packageName;
}
@Override
public boolean checkResidence(final int residence) {
return !ClassRepr.getPackageName(myContext.getValue(residence)).equals(packageName);
}
}
public class InheritanceConstraint extends PackageConstraint {
public final int rootClass;
public InheritanceConstraint(ClassRepr rootClass) {
super(rootClass.getPackageName());
this.rootClass = rootClass.name;
}
public InheritanceConstraint(final int rootClass) {
super(ClassRepr.getPackageName(myContext.getValue(rootClass)));
this.rootClass = rootClass;
}
@Override
public boolean checkResidence(final int residence) {
final Boolean inheritorOf = isInheritorOf(residence, rootClass, null);
return (inheritorOf == null || !inheritorOf) && super.checkResidence(residence);
}
}
}
void affectAll(final int className, @NotNull final File sourceFile, final Collection<File> affectedFiles, final Collection<File> alreadyCompiledFiles, @Nullable final DependentFilesFilter filter) {
final TIntHashSet dependants = myClassToClassDependency.get(className);
if (dependants != null) {
dependants.forEach(depClass -> {
final Collection<File> allSources = myClassToSourceFile.get(depClass);
if (allSources == null || allSources.isEmpty()) {
return true;
}
boolean shouldAffect = false;
for (File depFile : allSources) {
if (FileUtil.filesEqual(depFile, sourceFile)) {
continue; // skipping self-dependencies
}
if (!alreadyCompiledFiles.contains(depFile) && (filter == null || filter.accept(depFile))) {
// if at least one of the source files associated with the class is affected, all other associated sources should be affected as well
shouldAffect = true;
break;
}
}
if (shouldAffect) {
for (File depFile : allSources) {
if (!FileUtil.filesEqual(depFile, sourceFile)) {
affectedFiles.add(depFile);
}
}
}
return true;
});
}
}
private static boolean isVisibleIn(final ClassRepr c, final ProtoMember m, final ClassRepr scope) {
final boolean privacy = m.isPrivate() && c.name != scope.name;
final boolean packageLocality = m.isPackageLocal() && !c.getPackageName().equals(scope.getPackageName());
return !privacy && !packageLocality;
}
private boolean isEmpty(final int s) {
return s == myEmptyName;
}
@NotNull
private TIntHashSet getAllSubclasses(final int root) {
return addAllSubclasses(root, new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR));
}
private TIntHashSet addAllSubclasses(final int root, final TIntHashSet acc) {
if (!acc.add(root)) {
return acc;
}
final TIntHashSet directSubclasses = myClassToSubclasses.get(root);
if (directSubclasses != null) {
directSubclasses.forEach(s -> {
addAllSubclasses(s, acc);
return true;
});
}
return acc;
}
private boolean incrementalDecision(final int owner, final Proto member, final Collection<File> affectedFiles, final Collection<File> currentlyCompiled, @Nullable final DependentFilesFilter filter) {
final boolean isField = member instanceof FieldRepr;
final Util self = new Util();
// Public branch --- hopeless
if (member.isPublic()) {
debug("Public access, switching to a non-incremental mode");
return false;
}
final THashSet<File> toRecompile = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
// Protected branch
if (member.isProtected()) {
debug("Protected access, softening non-incremental decision: adding all relevant subclasses for a recompilation");
debug("Root class: ", owner);
final TIntHashSet propagated = self.propagateFieldAccess(isField ? member.name : myEmptyName, owner);
propagated.forEach(className -> {
final Collection<File> fileNames = myClassToSourceFile.get(className);
if (fileNames != null) {
for (File fileName : fileNames) {
debug("Adding ", fileName);
}
toRecompile.addAll(fileNames);
}
return true;
});
}
final String packageName = ClassRepr.getPackageName(myContext.getValue(isField ? owner : member.name));
debug("Softening non-incremental decision: adding all package classes for a recompilation");
debug("Package name: ", packageName);
// Package-local branch
myClassToSourceFile.forEachEntry(new TIntObjectProcedure<Collection<File>>() {
@Override
public boolean execute(int className, Collection<File> fileNames) {
if (ClassRepr.getPackageName(myContext.getValue(className)).equals(packageName)) {
for (File fileName : fileNames) {
if (filter == null || filter.accept(fileName)) {
debug("Adding: ", fileName);
toRecompile.add(fileName);
}
}
}
return true;
}
});
// filtering already compiled and non-existing paths
toRecompile.removeAll(currentlyCompiled);
for (Iterator<File> it = toRecompile.iterator(); it.hasNext(); ) {
final File file = it.next();
if (!file.exists()) {
it.remove();
}
}
affectedFiles.addAll(toRecompile);
return true;
}
public interface DependentFilesFilter {
boolean accept(File file);
boolean belongsToCurrentTargetChunk(File file);
}
private class Differential {
private static final int DESPERATE_MASK = Opcodes.ACC_FINAL;
final Mappings myDelta;
final Collection<File> myFilesToCompile;
final Collection<File> myCompiledFiles;
final Collection<File> myCompiledWithErrors;
final Collection<File> myAffectedFiles;
@Nullable
final DependentFilesFilter myFilter;
@Nullable final Callbacks.ConstantAffectionResolver myConstantSearch;
final DelayedWorks myDelayedWorks;
final Util myFuture;
final Util myPresent;
final boolean myEasyMode; // true means: no need to search for affected files, only preprocess data for integrate
private final Iterable<AnnotationsChangeTracker> myAnnotationChangeTracker =
JpsServiceManager.getInstance().getExtensions(AnnotationsChangeTracker.class);
private class DelayedWorks {
class Triple {
final int owner;
final FieldRepr field;
@Nullable
final Future<Callbacks.ConstantAffection> affection;
private Triple(final int owner, final FieldRepr field, @Nullable final Future<Callbacks.ConstantAffection> affection) {
this.owner = owner;
this.field = field;
this.affection = affection;
}
Callbacks.ConstantAffection getAffection() {
try {
return affection != null ? affection.get() : Callbacks.ConstantAffection.EMPTY;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
final Collection<Triple> myQueue = new LinkedList<>();
void addConstantWork(final int ownerClass, final FieldRepr changedField, final boolean isRemoved, boolean accessChanged) {
final Future<Callbacks.ConstantAffection> future;
if (myConstantSearch == null) {
future = null;
}
else {
final String className = myContext.getValue(ownerClass);
final String fieldName = myContext.getValue(changedField.name);
future = myConstantSearch.request(className.replace('/', '.'), fieldName, changedField.access, isRemoved, accessChanged);
}
myQueue.add(new Triple(ownerClass, changedField, future));
}
boolean doWork(@NotNull final Collection<File> affectedFiles) {
if (!myQueue.isEmpty()) {
debug("Starting delayed works.");
for (final Triple t : myQueue) {
final Callbacks.ConstantAffection affection = t.getAffection();
debug("Class: ", t.owner);
debug("Field: ", t.field.name);
if (!affection.isKnown()) {
if (myConstantSearch != null) {
debug("No external dependency information available.");
}
else {
debug("Constant search service not available.");
}
debug("Trying to soften non-incremental decision.");
if (!incrementalDecision(t.owner, t.field, affectedFiles, myFilesToCompile, myFilter)) {
debug("No luck.");
debug("End of delayed work, returning false.");
return false;
}
}
else {
debug("External dependency information retrieved.");
final Collection<File> files = affection.getAffectedFiles();
if (myFilter == null) {
affectedFiles.addAll(files);
}
else {
for (File file : files) {
if (myFilter.accept(file)) {
affectedFiles.add(file);
}
}
}
}
}
debug("End of delayed work, returning true.");
}
return true;
}
}
private class FileClasses {
final File myFileName;
final Set<ClassRepr> myFileClasses = new THashSet<>();
final Set<ModuleRepr> myFileModules = new THashSet<>();
FileClasses(File fileName, Collection<ClassFileRepr> fileContent) {
myFileName = fileName;
for (ClassFileRepr repr : fileContent) {
if (repr instanceof ClassRepr) {
myFileClasses.add((ClassRepr)repr);
}
else {
myFileModules.add((ModuleRepr)repr);
}
}
}
}
private class DiffState {
final public TIntHashSet myDependants = new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
final public Set<UsageRepr.Usage> myAffectedUsages = new HashSet<>();
final public Set<UsageRepr.AnnotationUsage> myAnnotationQuery = new HashSet<>();
final public Map<UsageRepr.Usage, UsageConstraint> myUsageConstraints = new HashMap<>();
final Difference.Specifier<ClassRepr, ClassRepr.Diff> myClassDiff;
final Difference.Specifier<ModuleRepr, ModuleRepr.Diff> myModulesDiff;
DiffState(Difference.Specifier<ClassRepr, ClassRepr.Diff> classDiff, Difference.Specifier<ModuleRepr, ModuleRepr.Diff> modulesDiff) {
myClassDiff = classDiff;
myModulesDiff = modulesDiff;
}
}
private Differential(final Mappings delta) {
this.myDelta = delta;
this.myFilesToCompile = null;
this.myCompiledFiles = null;
this.myCompiledWithErrors = null;
this.myAffectedFiles = null;
this.myFilter = null;
this.myConstantSearch = null;
myDelayedWorks = null;
myFuture = null;
myPresent = null;
myEasyMode = true;
delta.myIsRebuild = true;
}
private Differential(final Mappings delta, final Collection<String> removed, final Collection<File> filesToCompile) {
delta.myRemovedFiles = removed;
this.myDelta = delta;
this.myFilesToCompile = filesToCompile;
this.myCompiledFiles = null;
this.myCompiledWithErrors = null;
this.myAffectedFiles = null;
this.myFilter = null;
this.myConstantSearch = null;
myDelayedWorks = null;
myFuture = new Util(delta);
myPresent = new Util();
myEasyMode = true;
}
private Differential(final Mappings delta,
final Collection<String> removed,
final Collection<File> filesToCompile,
final Collection<File> compiledWithErrors,
final Collection<File> compiledFiles,
final Collection<File> affectedFiles,
@NotNull final DependentFilesFilter filter,
@Nullable final Callbacks.ConstantAffectionResolver constantSearch) {
delta.myRemovedFiles = removed;
this.myDelta = delta;
this.myFilesToCompile = filesToCompile;
this.myCompiledFiles = compiledFiles;
this.myCompiledWithErrors = compiledWithErrors;
this.myAffectedFiles = affectedFiles;
this.myFilter = filter;
this.myConstantSearch = constantSearch;
myDelayedWorks = new DelayedWorks();
myFuture = new Util(delta);
myPresent = new Util();
myEasyMode = false;
}
private void processDisappearedClasses() {
if (myFilesToCompile != null) {
myDelta.compensateRemovedContent(
myFilesToCompile, myCompiledWithErrors != null ? myCompiledWithErrors : Collections.emptySet()
);
}
if (!myEasyMode) {
final Collection<String> removed = myDelta.myRemovedFiles;
if (removed != null) {
for (final String file : removed) {
final File sourceFile = new File(file);
final Collection<ClassFileRepr> classes = mySourceFileToClasses.get(sourceFile);
if (classes != null) {
for (ClassFileRepr c : classes) {
debug("Affecting usages of removed class ", c.name);
affectAll(c.name, sourceFile, myAffectedFiles, myCompiledFiles, myFilter);
}
}
}
}
}
}
private void processAddedMethods(final DiffState state, final ClassRepr.Diff diff, final ClassRepr it) {
final Collection<MethodRepr> added = diff.methods().added();
if (added.isEmpty()) {
return;
}
debug("Processing added methods: ");
if (it.isAnnotation()) {
debug("Class is annotation, skipping method analysis");
return;
}
assert myFuture != null;
assert myPresent != null;
assert myAffectedFiles != null;
Ref<ClassRepr> oldItRef = null;
for (final MethodRepr m : added) {
debug("Method: ", m.name);
if (!m.isPrivate() && (it.isInterface() || it.isAbstract() || m.isAbstract())) {
debug("Class is abstract, or is interface, or added non-private method is abstract => affecting all subclasses");
myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles, null);
}
TIntHashSet propagated = null;
if (!m.isPrivate() && m.name != myInitName) {
if (oldItRef == null) {
oldItRef = new Ref<>(getClassReprByName(null, it.name)); // lazy init
}
final ClassRepr oldIt = oldItRef.get();
if (oldIt == null || !myPresent.hasOverriddenMethods(oldIt, MethodRepr.equalByJavaRules(m), null)) {
if (m.myArgumentTypes.length > 0) {
propagated = myFuture.propagateMethodAccess(m, it.name);
debug("Conservative case on overriding methods, affecting method usages");
myFuture.affectMethodUsages(m, propagated, m.createMetaUsage(myContext, it.name), state.myAffectedUsages, state.myDependants);
}
}
}
if (!m.isPrivate()) {
final Collection<Pair<MethodRepr, ClassRepr>> affectedMethods = myFuture.findAllMethodsBySpecificity(m, it);
final MethodRepr.Predicate overrides = MethodRepr.equalByJavaRules(m);
if (propagated == null) {
propagated = myFuture.propagateMethodAccess(m, it.name);
}
final Collection<MethodRepr> lessSpecific = it.findMethods(myFuture.lessSpecific(m));
for (final MethodRepr mm : lessSpecific) {
if (!mm.equals(m)) {
debug("Found less specific method, affecting method usages");
myFuture.affectMethodUsages(mm, propagated, mm.createUsage(myContext, it.name), state.myAffectedUsages, state.myDependants);
}
}
debug("Processing affected by specificity methods");
for (final Pair<MethodRepr, ClassRepr> pair : affectedMethods) {
final MethodRepr method = pair.first;
final ClassRepr methodClass = pair.second;
if (methodClass == MOCK_CLASS) {
continue;
}
final Boolean inheritorOf = myPresent.isInheritorOf(methodClass.name, it.name, null);
final boolean isInheritor = inheritorOf != null && inheritorOf;
debug("Method: ", method.name);
debug("Class : ", methodClass.name);
if (overrides.satisfy(method) && isInheritor) {
debug("Current method overrides that found");
final Collection<File> files = myClassToSourceFile.get(methodClass.name);
if (files != null) {
myAffectedFiles.addAll(files);
for (File file : files) {
debug("Affecting file ", file);
}
}
}
else {
debug("Current method does not override that found");
final TIntHashSet yetPropagated = myPresent.propagateMethodAccess(method, it.name);
if (isInheritor) {
final TIntHashSet deps = myClassToClassDependency.get(methodClass.name);
if (deps != null) {
addAll(state.myDependants, deps);
}
myFuture.affectMethodUsages(method, yetPropagated, method.createUsage(myContext, methodClass.name), state.myAffectedUsages,
state.myDependants);
}
debug("Affecting method usages for that found");
myFuture.affectMethodUsages(method, yetPropagated, method.createUsage(myContext, it.name), state.myAffectedUsages,
state.myDependants);
}
}
final TIntHashSet subClasses = getAllSubclasses(it.name);
subClasses.forEach(subClass -> {
final ClassRepr r = myFuture.classReprByName(subClass);
if (r == null) {
return true;
}
final Collection<File> sourceFileNames = myClassToSourceFile.get(subClass);
if (sourceFileNames != null && !myCompiledFiles.containsAll(sourceFileNames)) {
final int outerClass = r.getOuterClassName();
if (!isEmpty(outerClass)) {
final ClassRepr outerClassRepr = myFuture.classReprByName(outerClass);
if (outerClassRepr != null && (myFuture.isMethodVisible(outerClassRepr, m) || myFuture.extendsLibraryClass(outerClassRepr, null))) {
myAffectedFiles.addAll(sourceFileNames);
for (File sourceFileName : sourceFileNames) {
debug("Affecting file due to local overriding: ", sourceFileName);
}
}
}
}
return true;
});
}
}
debug("End of added methods processing");
}
private void processRemovedMethods(final DiffState state, final ClassRepr.Diff diff, final ClassRepr it) {
final Collection<MethodRepr> removed = diff.methods().removed();
if (removed.isEmpty()) {
return;
}
assert myFuture != null;
assert myAffectedFiles != null;
assert myCompiledFiles != null;
debug("Processing removed methods:");
for (final MethodRepr m : removed) {
debug("Method ", m.name);
final Collection<Pair<MethodRepr, ClassRepr>> overridenMethods = myFuture.findOverriddenMethods(m, it);
final TIntHashSet propagated = myFuture.propagateMethodAccess(m, it.name);
if (overridenMethods.size() == 0) {
debug("No overridden methods found, affecting method usages");
myFuture.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), state.myAffectedUsages, state.myDependants);
}
else {
boolean clear = true;
loop:
for (final Pair<MethodRepr, ClassRepr> overriden : overridenMethods) {
final MethodRepr mm = overriden.first;
if (mm == MOCK_METHOD || !mm.myType.equals(m.myType) || !isEmpty(mm.signature) || !isEmpty(m.signature) || m.isMoreAccessibleThan(mm)) {
clear = false;
break loop;
}
}
if (!clear) {
debug("No clearly overridden methods found, affecting method usages");
myFuture.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), state.myAffectedUsages, state.myDependants);
}
}
final Collection<Pair<MethodRepr, ClassRepr>> overridingMethods = new HashSet<>();
myFuture.addOverridingMethods(m, it, MethodRepr.equalByJavaRules(m), overridingMethods, null);
for (final Pair<MethodRepr, ClassRepr> p : overridingMethods) {
final Collection<File> fNames = myClassToSourceFile.get(p.second.name);
if (fNames != null) {
myAffectedFiles.addAll(fNames);
for (File fName : fNames) {
debug("Affecting file by overriding: ", fName);
}
}
}
if (!m.isAbstract()) {
propagated.forEach(p -> {
if (p != it.name) {
final ClassRepr s = myFuture.classReprByName(p);
if (s != null) {
final Collection<Pair<MethodRepr, ClassRepr>> overridenInS = myFuture.findOverriddenMethods(m, s);
overridenInS.addAll(overridenMethods);
boolean allAbstract = true;
boolean visited = false;
for (final Pair<MethodRepr, ClassRepr> pp : overridenInS) {
final ClassRepr cc = pp.second;
if (cc == MOCK_CLASS) {
visited = true;
continue;
}
if (cc.name == it.name) {
continue;
}
visited = true;
allAbstract = pp.first.isAbstract() || cc.isInterface();
if (!allAbstract) {
break;
}
}
if (allAbstract && visited) {
final Collection<File> sources = myClassToSourceFile.get(p);
if (sources != null && !myCompiledFiles.containsAll(sources)) {
myAffectedFiles.addAll(sources);
debug("Removed method is not abstract & overrides some abstract method which is not then over-overridden in subclass ", p);
for (File source : sources) {
debug("Affecting subclass source file ", source);
}
}
}
}
}
return true;
});
}
}
debug("End of removed methods processing");
}
private void processChangedMethods(final DiffState state, final ClassRepr.Diff diff, final ClassRepr it) {
final Collection<Pair<MethodRepr, MethodRepr.Diff>> changed = diff.methods().changed();
if (changed.isEmpty()) {
return;
}
debug("Processing changed methods:");
assert myFuture != null;
assert myAffectedFiles != null;
for (final Pair<MethodRepr, MethodRepr.Diff> mr : changed) {
final MethodRepr m = mr.first;
final MethodRepr.Diff d = mr.second;
final boolean throwsChanged = !d.exceptions().unchanged();
debug("Method: ", m.name);
if (it.isAnnotation()) {
if (d.defaultRemoved()) {
debug("Class is annotation, default value is removed => adding annotation query");
final TIntHashSet l = new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
l.add(m.name);
final UsageRepr.AnnotationUsage annotationUsage = (UsageRepr.AnnotationUsage)UsageRepr
.createAnnotationUsage(myContext, TypeRepr.createClassType(myContext, it.name), l, null);
state.myAnnotationQuery.add(annotationUsage);
}
}
else if (d.base() != Difference.NONE || throwsChanged) {
final TIntHashSet propagated = myFuture.propagateMethodAccess(m, it.name);
boolean affected = false;
boolean constrained = false;
final Set<UsageRepr.Usage> usages = new THashSet<>();
if (d.packageLocalOn()) {
debug("Method became package-private, affecting method usages outside the package");
myFuture.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), usages, state.myDependants);
for (final UsageRepr.Usage usage : usages) {
state.myUsageConstraints.put(usage, myFuture.new PackageConstraint(it.getPackageName()));
}
state.myAffectedUsages.addAll(usages);
affected = true;
constrained = true;
}
if ((d.base() & Difference.TYPE) != 0 || (d.base() & Difference.SIGNATURE) != 0 || throwsChanged) {
if (!affected) {
debug("Return type, throws list or signature changed --- affecting method usages");
myFuture.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), usages, state.myDependants);
final List<Pair<MethodRepr, ClassRepr>> overridingMethods = new LinkedList<>();
myFuture.addOverridingMethods(m, it, MethodRepr.equalByJavaRules(m), overridingMethods, null);
for(final Pair<MethodRepr, ClassRepr> p : overridingMethods) {
final ClassRepr aClass = p.getSecond();
if (aClass != MOCK_CLASS) {
final Collection<File> fileNames = myClassToSourceFile.get(aClass.name);
if (fileNames != null) {
myAffectedFiles.addAll(fileNames);
}
}
}
state.myAffectedUsages.addAll(usages);
affected = true;
}
}
else if ((d.base() & Difference.ACCESS) != 0) {
if ((d.addedModifiers() & (Opcodes.ACC_STATIC | Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_BRIDGE)) != 0 ||
(d.removedModifiers() & Opcodes.ACC_STATIC) != 0) {
// When synthetic or bridge flags are added, this effectively means that explicitly written in the code
// method with the same signature and return type has been removed and a bridge method has been generated instead.
// In some cases (e.g. using raw types) the presence of such synthetic methods in the bytecode is ignored by the compiler
// so that the code that called such method via raw type reference might not compile anymore => to be on the safe side
// we should recompile all places where the method was used
if (!affected) {
debug("Added {static | private | synthetic | bridge} specifier or removed static specifier --- affecting method usages");
myFuture.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), usages, state.myDependants);
state.myAffectedUsages.addAll(usages);
affected = true;
}
if ((d.addedModifiers() & Opcodes.ACC_STATIC) != 0) {
debug("Added static specifier --- affecting subclasses");
myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles, null);
}
}
else {
if ((d.addedModifiers() & Opcodes.ACC_FINAL) != 0 ||
(d.addedModifiers() & Opcodes.ACC_PUBLIC) != 0 ||
(d.addedModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
debug("Added final, public or abstract specifier --- affecting subclasses");
myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles, null);
}
if ((d.addedModifiers() & Opcodes.ACC_PROTECTED) != 0 && !((d.removedModifiers() & Opcodes.ACC_PRIVATE) != 0)) {
if (!constrained) {
debug("Added public or package-private method became protected --- affect method usages with protected constraint");
if (!affected) {
myFuture.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), usages, state.myDependants);
state.myAffectedUsages.addAll(usages);
affected = true;
}
for (final UsageRepr.Usage usage : usages) {
state.myUsageConstraints.put(usage, myFuture.new InheritanceConstraint(it));
}
constrained = true;
}
}
}
}
if ((d.base() & Difference.ANNOTATIONS) != 0) {
final Set<AnnotationsChangeTracker.Recompile> toRecompile = EnumSet.noneOf(AnnotationsChangeTracker.Recompile.class);
for (AnnotationsChangeTracker extension : myAnnotationChangeTracker) {
if (toRecompile.containsAll(AnnotationsChangeTracker.RECOMPILE_ALL)) {
break;
}
final Set<AnnotationsChangeTracker.Recompile> actions = extension.methodAnnotationsChanged(myContext, m, d.annotations(), d.parameterAnnotations());
if (actions.contains(AnnotationsChangeTracker.Recompile.USAGES)) {
debug("Extension "+extension.getClass().getName()+" requested recompilation because of changes in annotations list --- affecting method usages");
}
if (actions.contains(AnnotationsChangeTracker.Recompile.SUBCLASSES)) {
debug("Extension "+extension.getClass().getName()+" requested recompilation because of changes in method annotations or method parameter annotations list --- affecting subclasses");
}
toRecompile.addAll(actions);
}
if (toRecompile.contains(AnnotationsChangeTracker.Recompile.USAGES)) {
myFuture.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), usages, state.myDependants);
state.myAffectedUsages.addAll(usages);
if (constrained) {
// remove any constraints so that all usages of this method are recompiled
for (UsageRepr.Usage usage : usages) {
state.myUsageConstraints.remove(usage);
}
}
}
if (toRecompile.contains(AnnotationsChangeTracker.Recompile.SUBCLASSES)) {
myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles, null);
}
}
}
}
debug("End of changed methods processing");
}
private boolean processAddedFields(final DiffState state, final ClassRepr.Diff diff, final ClassRepr classRepr) {
final Collection<FieldRepr> added = diff.fields().added();
if (added.isEmpty()) {
return true;
}
debug("Processing added fields");
assert myFuture != null;
assert myPresent != null;
assert myCompiledFiles != null;
assert myAffectedFiles != null;
for (final FieldRepr f : added) {
debug("Field: ", f.name);
if (!f.isPrivate()) {
final TIntHashSet subClasses = getAllSubclasses(classRepr.name);
subClasses.forEach(subClass -> {
final ClassRepr r = myFuture.classReprByName(subClass);
if (r != null) {
final Collection<File> sourceFileNames = myClassToSourceFile.get(subClass);
if (sourceFileNames != null && !myCompiledFiles.containsAll(sourceFileNames)) {
if (r.isLocal()) {
for (File sourceFileName : sourceFileNames) {
debug("Affecting local subclass (introduced field can potentially hide surrounding method parameters/local variables): ", sourceFileName);
}
myAffectedFiles.addAll(sourceFileNames);
}
else {
final int outerClass = r.getOuterClassName();
if (!isEmpty(outerClass) && myFuture.isFieldVisible(outerClass, f)) {
for (File sourceFileName : sourceFileNames) {
debug("Affecting inner subclass (introduced field can potentially hide surrounding class fields): ", sourceFileName);
}
myAffectedFiles.addAll(sourceFileNames);
}
}
}
}
debug("Affecting field usages referenced from subclass ", subClass);
final TIntHashSet propagated = myFuture.propagateFieldAccess(f.name, subClass);
myFuture.affectFieldUsages(f, propagated, f.createUsage(myContext, subClass), state.myAffectedUsages, state.myDependants);
final TIntHashSet deps = myClassToClassDependency.get(subClass);
if (deps != null) {
addAll(state.myDependants, deps);
}
return true;
});
}
final Collection<Pair<FieldRepr, ClassRepr>> overriddenFields = new HashSet<>();
myFuture.addOverriddenFields(f, classRepr, overriddenFields, null);
for (final Pair<FieldRepr, ClassRepr> p : overriddenFields) {
final FieldRepr ff = p.first;
final ClassRepr cc = p.second;
if (ff.isPrivate()) {
continue;
}
final boolean sameKind = f.myType.equals(ff.myType) && f.isStatic() == ff.isStatic() && f.isSynthetic() == ff.isSynthetic() && f.isFinal() == ff.isFinal();
if (!sameKind || Difference.weakerAccess(f.access, ff.access)) {
final TIntHashSet propagated = myPresent.propagateFieldAccess(ff.name, cc.name);
final Set<UsageRepr.Usage> affectedUsages = new HashSet<>();
debug("Affecting usages of overridden field in class ", cc.name);
myFuture.affectFieldUsages(ff, propagated, ff.createUsage(myContext, cc.name), affectedUsages, state.myDependants);
if (sameKind) {
// check if we can reduce the number of usages going to be recompiled
UsageConstraint constraint = null;
if (f.isProtected()) {
// no need to recompile usages in field class' package and hierarchy, since newly added field is accessible in this scope
constraint = myFuture.new InheritanceConstraint(cc);
}
else if (f.isPackageLocal()) {
// no need to recompile usages in field class' package, since newly added field is accessible in this scope
constraint = myFuture.new PackageConstraint(cc.getPackageName());
}
if (constraint != null) {
for (final UsageRepr.Usage usage : affectedUsages) {
state.myUsageConstraints.put(usage, constraint);
}
}
}
state.myAffectedUsages.addAll(affectedUsages);
}
}
}
debug("End of added fields processing");
return true;
}
private boolean processRemovedFields(final DiffState state, final ClassRepr.Diff diff, final ClassRepr it) {
final Collection<FieldRepr> removed = diff.fields().removed();
if (removed.isEmpty()) {
return true;
}
assert myFuture != null;
debug("Processing removed fields:");
for (final FieldRepr f : removed) {
debug("Field: ", f.name);
if (!f.isPrivate() && (f.access & DESPERATE_MASK) == DESPERATE_MASK && f.hasValue()) {
debug("Field had value and was (non-private) final static => a switch to non-incremental mode requested");
if (myConstantSearch != null) {
assert myDelayedWorks != null;
myDelayedWorks.addConstantWork(it.name, f, true, false);
}
else {
if (!incrementalDecision(it.name, f, myAffectedFiles, myFilesToCompile, myFilter)) {
debug("End of Differentiate, returning false");
return false;
}
}
}
final TIntHashSet propagated = myFuture.propagateFieldAccess(f.name, it.name);
myFuture.affectFieldUsages(f, propagated, f.createUsage(myContext, it.name), state.myAffectedUsages, state.myDependants);
}
debug("End of removed fields processing");
return true;
}
private boolean processChangedFields(final DiffState state, final ClassRepr.Diff diff, final ClassRepr it) {
final Collection<Pair<FieldRepr, Difference>> changed = diff.fields().changed();
if (changed.isEmpty()) {
return true;
}
debug("Processing changed fields:");
assert myFuture != null;
for (final Pair<FieldRepr, Difference> f : changed) {
final Difference d = f.second;
final FieldRepr field = f.first;
debug("Field: ", field.name);
// only if the field was a compile-time constant
if (!field.isPrivate() && (field.access & DESPERATE_MASK) == DESPERATE_MASK && d.hadValue()) {
final int changedModifiers = d.addedModifiers() | d.removedModifiers();
final boolean harmful = (changedModifiers & (Opcodes.ACC_STATIC | Opcodes.ACC_FINAL)) != 0;
final boolean accessChanged = (changedModifiers & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) != 0;
final boolean becameLessAccessible = accessChanged && d.accessRestricted();
final boolean valueChanged = (d.base() & Difference.VALUE) != 0;
if (harmful || valueChanged || becameLessAccessible) {
debug("Inline field changed it's access or value => a switch to non-incremental mode requested");
if (myConstantSearch != null) {
assert myDelayedWorks != null;
myDelayedWorks.addConstantWork(it.name, field, false, accessChanged);
}
else {
if (!incrementalDecision(it.name, field, myAffectedFiles, myFilesToCompile, myFilter)) {
debug("End of Differentiate, returning false");
return false;
}
}
}
}
if (d.base() != Difference.NONE) {
final TIntHashSet propagated = myFuture.propagateFieldAccess(field.name, it.name);
if ((d.base() & Difference.TYPE) != 0 || (d.base() & Difference.SIGNATURE) != 0) {
debug("Type or signature changed --- affecting field usages");
myFuture.affectFieldUsages(
field, propagated, field.createUsage(myContext, it.name), state.myAffectedUsages, state.myDependants
);
}
else if ((d.base() & Difference.ACCESS) != 0) {
if ((d.addedModifiers() & Opcodes.ACC_STATIC) != 0 ||
(d.removedModifiers() & Opcodes.ACC_STATIC) != 0 ||
(d.addedModifiers() & Opcodes.ACC_PRIVATE) != 0 ||
(d.addedModifiers() & Opcodes.ACC_VOLATILE) != 0) {
debug("Added/removed static modifier or added private/volatile modifier --- affecting field usages");
myFuture.affectFieldUsages(
field, propagated, field.createUsage(myContext, it.name), state.myAffectedUsages, state.myDependants
);
}
else {
final Set<UsageRepr.Usage> usages = new THashSet<>();
if ((d.addedModifiers() & Opcodes.ACC_FINAL) != 0) {
debug("Added final modifier --- affecting field assign usages");
myFuture.affectFieldUsages(field, propagated, field.createAssignUsage(myContext, it.name), usages, state.myDependants);
state.myAffectedUsages.addAll(usages);
}
if ((d.removedModifiers() & Opcodes.ACC_PUBLIC) != 0) {
debug("Removed public modifier, affecting field usages with appropriate constraint");
myFuture.affectFieldUsages(field, propagated, field.createUsage(myContext, it.name), usages, state.myDependants);
state.myAffectedUsages.addAll(usages);
for (final UsageRepr.Usage usage : usages) {
if ((d.addedModifiers() & Opcodes.ACC_PROTECTED) != 0) {
state.myUsageConstraints.put(usage, myFuture.new InheritanceConstraint(it));
}
else {
state.myUsageConstraints.put(usage, myFuture.new PackageConstraint(it.getPackageName()));
}
}
}
else if ((d.removedModifiers() & Opcodes.ACC_PROTECTED) != 0 && d.accessRestricted()) {
debug("Removed protected modifier and the field became less accessible, affecting field usages with package constraint");
myFuture.affectFieldUsages(field, propagated, field.createUsage(myContext, it.name), usages, state.myDependants);
state.myAffectedUsages.addAll(usages);
for (final UsageRepr.Usage usage : usages) {
state.myUsageConstraints.put(usage, myFuture.new PackageConstraint(it.getPackageName()));
}
}
}
}
if ((d.base() & Difference.ANNOTATIONS) != 0) {
final Set<AnnotationsChangeTracker.Recompile> toRecompile = EnumSet.noneOf(AnnotationsChangeTracker.Recompile.class);
for (AnnotationsChangeTracker extension : myAnnotationChangeTracker) {
if (toRecompile.containsAll(AnnotationsChangeTracker.RECOMPILE_ALL)) {
break;
}
final Set<AnnotationsChangeTracker.Recompile> res = extension.fieldAnnotationsChanged(myContext, field, d.annotations());
if (res.contains(AnnotationsChangeTracker.Recompile.USAGES)) {
debug("Extension "+extension.getClass().getName()+" requested recompilation because of changes in annotations list --- affecting field usages");
}
if (res.contains(AnnotationsChangeTracker.Recompile.SUBCLASSES)) {
debug("Extension "+extension.getClass().getName()+" requested recompilation because of changes in field annotations list --- affecting subclasses");
}
toRecompile.addAll(res);
}
if (toRecompile.contains(AnnotationsChangeTracker.Recompile.USAGES)) {
final Set<UsageRepr.Usage> usages = new THashSet<>();
myFuture.affectFieldUsages(field, propagated, field.createUsage(myContext, it.name), usages, state.myDependants);
state.myAffectedUsages.addAll(usages);
// remove any constraints to ensure all field usages are recompiled
for (UsageRepr.Usage usage : usages) {
state.myUsageConstraints.remove(usage);
}
}
if (toRecompile.contains(AnnotationsChangeTracker.Recompile.SUBCLASSES)) {
myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles, null);
}
}
}
}
debug("End of changed fields processing");
return true;
}
private boolean processChangedClasses(final DiffState state) {
final Collection<Pair<ClassRepr, ClassRepr.Diff>> changedClasses = state.myClassDiff.changed();
if (!changedClasses.isEmpty()) {
debug("Processing changed classes:");
assert myFuture != null;
assert myPresent != null;
final Util.FileFilterConstraint fileFilterConstraint = myFilter != null? myPresent.new FileFilterConstraint(myFilter) : null;
for (final Pair<ClassRepr, ClassRepr.Diff> changed : changedClasses) {
final ClassRepr changedClass = changed.first;
final ClassRepr.Diff diff = changed.second;
myDelta.addChangedClass(changedClass.name);
debug("Changed: ", changedClass.name);
final int addedModifiers = diff.addedModifiers();
final boolean superClassChanged = (diff.base() & Difference.SUPERCLASS) != 0;
final boolean interfacesChanged = !diff.interfaces().unchanged();
final boolean signatureChanged = (diff.base() & Difference.SIGNATURE) != 0;
if (superClassChanged) {
myDelta.registerRemovedSuperClass(changedClass.name, changedClass.getSuperClass().className);
final ClassRepr newClass = myDelta.getClassReprByName(null, changedClass.name);
assert (newClass != null);
myDelta.registerAddedSuperClass(changedClass.name, newClass.getSuperClass().className);
}
if (interfacesChanged) {
for (final TypeRepr.AbstractType typ : diff.interfaces().removed()) {
myDelta.registerRemovedSuperClass(changedClass.name, ((TypeRepr.ClassType)typ).className);
}
for (final TypeRepr.AbstractType typ : diff.interfaces().added()) {
myDelta.registerAddedSuperClass(changedClass.name, ((TypeRepr.ClassType)typ).className);
}
}
if (myEasyMode) {
continue;
}
myPresent.appendDependents(changedClass, state.myDependants);
if (superClassChanged || interfacesChanged || signatureChanged) {
debug("Superclass changed: ", superClassChanged);
debug("Interfaces changed: ", interfacesChanged);
debug("Signature changed ", signatureChanged);
final boolean extendsChanged = superClassChanged && !diff.extendsAdded();
final boolean interfacesRemoved = interfacesChanged && !diff.interfaces().removed().isEmpty();
debug("Extends changed: ", extendsChanged);
debug("Interfaces removed: ", interfacesRemoved);
myFuture.affectSubclasses(changedClass.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, extendsChanged || interfacesRemoved || signatureChanged, myCompiledFiles, null);
if (!changedClass.isAnonymous()) {
final TIntHashSet parents = new TIntHashSet();
myPresent.collectSupersRecursively(changedClass.name, parents);
final TIntHashSet futureParents = new TIntHashSet();
myFuture.collectSupersRecursively(changedClass.name, futureParents);
parents.removeAll(futureParents.toArray());
parents.remove(myObjectClassName);
if (!parents.isEmpty()) {
parents.forEach(className -> {
debug("Affecting usages in generic type parameter bounds of class: ", className);
final UsageRepr.Usage usage = UsageRepr.createClassAsGenericBoundUsage(myContext, className);
state.myAffectedUsages.add(usage);
if (fileFilterConstraint != null) {
state.myUsageConstraints.put(usage, fileFilterConstraint);
}
final TIntHashSet depClasses = myClassToClassDependency.get(className);
if (depClasses != null) {
addAll(state.myDependants, depClasses);
}
return true;
});
}
}
}
if ((diff.addedModifiers() & Opcodes.ACC_INTERFACE) != 0 || (diff.removedModifiers() & Opcodes.ACC_INTERFACE) != 0) {
debug("Class-to-interface or interface-to-class conversion detected, added class usage to affected usages");
state.myAffectedUsages.add(changedClass.createUsage());
}
if (changedClass.isAnnotation() && changedClass.getRetentionPolicy() == RetentionPolicy.SOURCE) {
debug("Annotation, retention policy = SOURCE => a switch to non-incremental mode requested");
if (!incrementalDecision(changedClass.getOuterClassName(), changedClass, myAffectedFiles, myFilesToCompile, myFilter)) {
debug("End of Differentiate, returning false");
return false;
}
}
if ((addedModifiers & Opcodes.ACC_PROTECTED) != 0) {
debug("Introduction of 'protected' modifier detected, adding class usage + inheritance constraint to affected usages");
final UsageRepr.Usage usage = changedClass.createUsage();
state.myAffectedUsages.add(usage);
state.myUsageConstraints.put(usage, myFuture.new InheritanceConstraint(changedClass));
}
if (diff.packageLocalOn()) {
debug("Introduction of 'package-private' access detected, adding class usage + package constraint to affected usages");
final UsageRepr.Usage usage = changedClass.createUsage();
state.myAffectedUsages.add(usage);
state.myUsageConstraints.put(usage, myFuture.new PackageConstraint(changedClass.getPackageName()));
}
if ((addedModifiers & Opcodes.ACC_FINAL) != 0 || (addedModifiers & Opcodes.ACC_PRIVATE) != 0) {
debug("Introduction of 'private' or 'final' modifier(s) detected, adding class usage to affected usages");
state.myAffectedUsages.add(changedClass.createUsage());
}
if ((addedModifiers & Opcodes.ACC_ABSTRACT) != 0 || (addedModifiers & Opcodes.ACC_STATIC) != 0) {
debug("Introduction of 'abstract' or 'static' modifier(s) detected, adding class new usage to affected usages");
state.myAffectedUsages.add(UsageRepr.createClassNewUsage(myContext, changedClass.name));
}
if (!changedClass.isAnonymous() && !isEmpty(changedClass.getOuterClassName()) && !changedClass.isPrivate()) {
if (addedModifiers != 0 || diff.removedModifiers() != 0) {
debug("Some modifiers (access flags) were changed for non-private inner class, adding class usage to affected usages");
state.myAffectedUsages.add(changedClass.createUsage());
}
}
if (changedClass.isAnnotation()) {
debug("Class is annotation, performing annotation-specific analysis");
if (diff.retentionChanged()) {
debug("Retention policy change detected, adding class usage to affected usages");
state.myAffectedUsages.add(changedClass.createUsage());
}
else if (diff.targetAttributeCategoryMightChange()) {
debug("Annotation's attribute category in bytecode might be affected because of TYPE_USE target, adding class usage to affected usages");
state.myAffectedUsages.add(changedClass.createUsage());
}
else {
final Collection<ElemType> removedtargets = diff.targets().removed();
if (removedtargets.contains(ElemType.LOCAL_VARIABLE)) {
debug("Removed target contains LOCAL_VARIABLE => a switch to non-incremental mode requested");
if (!incrementalDecision(changedClass.getOuterClassName(), changedClass, myAffectedFiles, myFilesToCompile, myFilter)) {
debug("End of Differentiate, returning false");
return false;
}
}
if (!removedtargets.isEmpty()) {
debug("Removed some annotation targets, adding annotation query");
state.myAnnotationQuery.add((UsageRepr.AnnotationUsage)UsageRepr.createAnnotationUsage(
myContext, TypeRepr.createClassType(myContext, changedClass.name), null, EnumSet.copyOf(removedtargets)
));
}
for (final MethodRepr m : diff.methods().added()) {
if (!m.hasValue()) {
debug("Added method with no default value: ", m.name);
debug("Adding class usage to affected usages");
state.myAffectedUsages.add(changedClass.createUsage());
}
}
}
debug("End of annotation-specific analysis");
}
processAddedMethods(state, diff, changedClass);
processRemovedMethods(state, diff, changedClass);
processChangedMethods(state, diff, changedClass);
if (!processAddedFields(state, diff, changedClass)) {
return false;
}
if (!processRemovedFields(state, diff, changedClass)) {
return false;
}
if (!processChangedFields(state, diff, changedClass)) {
return false;
}
if ((diff.base() & Difference.ANNOTATIONS) != 0) {
final Set<AnnotationsChangeTracker.Recompile> toRecompile = EnumSet.noneOf(AnnotationsChangeTracker.Recompile.class);
for (AnnotationsChangeTracker extension : myAnnotationChangeTracker) {
if (toRecompile.containsAll(AnnotationsChangeTracker.RECOMPILE_ALL)) {
break;
}
final Set<AnnotationsChangeTracker.Recompile> res = extension.classAnnotationsChanged(myContext, changedClass, diff.annotations());
if (res.contains(AnnotationsChangeTracker.Recompile.USAGES)) {
debug("Extension "+extension.getClass().getName()+" requested class usages recompilation because of changes in annotations list --- adding class usage to affected usages");
}
if (res.contains(AnnotationsChangeTracker.Recompile.SUBCLASSES)) {
debug("Extension "+extension.getClass().getName()+" requested subclasses recompilation because of changes in annotations list --- adding subclasses to affected usages");
}
toRecompile.addAll(res);
}
final boolean recompileUsages = toRecompile.contains(AnnotationsChangeTracker.Recompile.USAGES);
if (recompileUsages) {
state.myAffectedUsages.add(changedClass.createUsage());
}
if (toRecompile.contains(AnnotationsChangeTracker.Recompile.SUBCLASSES)) {
myFuture.affectSubclasses(changedClass.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, recompileUsages, myCompiledFiles, null);
}
}
}
debug("End of changed classes processing");
}
return !myEasyMode;
}
private void processRemovedClases(final DiffState state, @NotNull File fileName) {
final Collection<ClassRepr> removed = state.myClassDiff.removed();
if (removed.isEmpty()) {
return;
}
assert myPresent != null;
assert myDelta.myChangedFiles != null;
myDelta.myChangedFiles.add(fileName);
debug("Processing removed classes:");
for (final ClassRepr c : removed) {
myDelta.addDeletedClass(c, fileName);
if (!myEasyMode) {
myPresent.appendDependents(c, state.myDependants);
debug("Adding usages of class ", c.name);
state.myAffectedUsages.add(c.createUsage());
debug("Affecting usages of removed class ", c.name);
affectAll(c.name, fileName, myAffectedFiles, myCompiledFiles, myFilter);
}
}
debug("End of removed classes processing.");
}
private void processAddedClasses(final DiffState state, File srcFile) {
final Collection<ClassRepr> addedClasses = state.myClassDiff.added();
if (addedClasses.isEmpty()) {
return;
}
debug("Processing added classes:");
if (!myEasyMode && myFilter != null) {
// checking if this newly added class duplicates already existing one
assert myCompiledFiles != null;
assert myAffectedFiles != null;
for (ClassRepr c : addedClasses) {
if (!c.isLocal() && !c.isAnonymous() && isEmpty(c.getOuterClassName())) {
final Set<File> candidates = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
final Collection<File> currentlyMapped = myClassToSourceFile.get(c.name);
if (currentlyMapped != null) {
candidates.addAll(currentlyMapped);
}
candidates.removeAll(myCompiledFiles);
final Collection<File> newSources = myDelta.myClassToSourceFile.get(c.name);
if (newSources != null) {
candidates.removeAll(newSources);
}
final Set<File> nonExistentOrOutOfScope = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
for (final File candidate : candidates) {
if (!candidate.exists() || !myFilter.belongsToCurrentTargetChunk(candidate)) {
nonExistentOrOutOfScope.add(candidate);
}
}
candidates.removeAll(nonExistentOrOutOfScope);
if (!candidates.isEmpty()) {
// Possibly duplicate classes from different sets of source files
// Schedule for recompilation both to make possible 'duplicate sources' error evident
candidates.clear(); // just reusing the container
if (currentlyMapped != null) {
candidates.addAll(currentlyMapped);
}
if (newSources != null) {
candidates.addAll(newSources);
}
candidates.removeAll(nonExistentOrOutOfScope);
if (myDebugS.isDebugEnabled()) {
final StringBuilder msg = new StringBuilder();
msg.append("Possibly duplicated classes; Scheduling for recompilation sources: ");
for (File file : candidates) {
msg.append(file.getPath()).append("; ");
}
debug(msg.toString());
}
myAffectedFiles.addAll(candidates);
return; // do not process this file because it should not be integrated
}
}
}
}
for (final ClassRepr c : addedClasses) {
debug("Class name: ", c.name);
myDelta.addAddedClass(c);
for (final int sup : c.getSupers()) {
myDelta.registerAddedSuperClass(c.name, sup);
}
if (!myEasyMode && !c.isAnonymous() && !c.isLocal()) {
final TIntHashSet toAffect = new TIntHashSet();
toAffect.add(c.name);
final TIntHashSet classes = myShortClassNameIndex.get(myContext.get(c.getShortName()));
if (classes != null) {
// affecting dependencies on all other classes with the same short name
toAffect.addAll(classes.toArray());
}
toAffect.forEach(qName -> {
final TIntHashSet depClasses = myClassToClassDependency.get(qName);
if (depClasses != null) {
affectCorrespondingSourceFiles(depClasses);
}
return true;
});
}
}
debug("End of added classes processing.");
}
private void affectCorrespondingSourceFiles(TIntHashSet toAffect) {
assert myAffectedFiles != null;
toAffect.forEach(depClass -> {
final Collection<File> fNames = myClassToSourceFile.get(depClass);
if (fNames != null) {
for (File fName : fNames) {
if (myFilter == null || myFilter.accept(fName)) {
debug("Adding dependent file ", fName);
myAffectedFiles.add(fName);
}
}
}
return true;
});
}
private void calculateAffectedFiles(final DiffState state) {
debug("Checking dependent classes:");
assert myAffectedFiles != null;
assert myCompiledFiles != null;
state.myDependants.forEach(new TIntProcedure() {
@Override
public boolean execute(final int depClass) {
final Collection<File> depFiles = myClassToSourceFile.get(depClass);
if (depFiles != null) {
for (File depFile : depFiles) {
processDependentFile(depClass, depFile);
}
}
return true;
}
private void processDependentFile(int depClass, @NotNull File depFile) {
if (myAffectedFiles.contains(depFile) || myCompiledFiles.contains(depFile)) {
return;
}
debug("Dependent class: ", depClass);
final ClassFileRepr repr = getReprByName(depFile, depClass);
if (repr == null) {
return;
}
final Set<UsageRepr.Usage> depUsages = repr.getUsages();
if (depUsages == null || depUsages.isEmpty()) {
return;
}
for (UsageRepr.Usage usage : depUsages) {
if (usage instanceof UsageRepr.AnnotationUsage) {
final UsageRepr.AnnotationUsage annotationUsage = (UsageRepr.AnnotationUsage)usage;
for (final UsageRepr.AnnotationUsage query : state.myAnnotationQuery) {
if (query.satisfies(annotationUsage)) {
debug("Added file due to annotation query");
myAffectedFiles.add(depFile);
return;
}
}
}
else if (state.myAffectedUsages.contains(usage)) {
final UsageConstraint constraint = state.myUsageConstraints.get(usage);
if (constraint == null) {
debug("Added file with no constraints");
myAffectedFiles.add(depFile);
return;
}
if (constraint.checkResidence(depClass)) {
debug("Added file with satisfied constraint");
myAffectedFiles.add(depFile);
return;
}
}
}
}
});
}
boolean differentiate() {
synchronized (myLock) {
myDelta.myIsDifferentiated = true;
if (myDelta.myIsRebuild) {
return true;
}
debug("Begin of Differentiate:");
debug("Easy mode: ", myEasyMode);
try {
processDisappearedClasses();
final List<FileClasses> newClasses = new ArrayList<>();
myDelta.mySourceFileToClasses.forEachEntry(new TObjectObjectProcedure<File, Collection<ClassFileRepr>>() {
@Override
public boolean execute(File fileName, Collection<ClassFileRepr> content) {
if (myFilesToCompile == null || myFilesToCompile.contains(fileName)) {
// Consider only files actually compiled in this round.
// For other sources the list of classes taken from this map will be possibly incomplete.
newClasses.add(new FileClasses(fileName, content));
}
return true;
}
});
for (final FileClasses compiledFile : newClasses) {
final File fileName = compiledFile.myFileName;
final Set<ClassRepr> pastClasses = new THashSet<>();
final Set<ModuleRepr> pastModules = new THashSet<>();
final Collection<ClassFileRepr> past = mySourceFileToClasses.get(fileName);
if (past != null) {
for (ClassFileRepr repr : past) {
if (repr instanceof ClassRepr) {
pastClasses.add((ClassRepr)repr);
}
else {
pastModules.add((ModuleRepr)repr);
}
}
}
final DiffState state = new DiffState(
Difference.make(pastClasses, compiledFile.myFileClasses),
Difference.make(pastModules, compiledFile.myFileModules)
);
if (!myEasyMode) {
processModules(state, fileName);
}
if (!processChangedClasses(state)) {
if (!myEasyMode) {
// turning non-incremental
return false;
}
}
processRemovedClases(state, fileName);
processAddedClasses(state, fileName);
if (!myEasyMode) {
calculateAffectedFiles(state);
}
}
// Now that the list of added classes is complete,
// check that super-classes of compiled classes are among newly added ones.
// Even if compiled class did not change, we should register 'added' superclass
// Consider situation for class B extends A:
// 1. file A is removed, make fails with error in file B
// 2. A is added back, B and A are compiled together in the second make session
// 3. Even if B did not change, A is considered as newly added and should be registered again in ClassToSubclasses dependencies
// Without this code such registration will not happen because list of B's parents did not change
final Set<ClassRepr> addedClasses = myDelta.getAddedClasses();
if (!addedClasses.isEmpty()) {
final TIntHashSet addedNames = new TIntHashSet();
for (ClassRepr repr : addedClasses) {
addedNames.add(repr.name);
}
for (FileClasses compiledFile : newClasses) {
for (ClassRepr aClass : compiledFile.myFileClasses) {
for (int parent : aClass.getSupers()) {
if (addedNames.contains(parent)) {
myDelta.registerAddedSuperClass(aClass.name, parent);
}
}
}
}
}
debug("End of Differentiate.");
if (myEasyMode) {
return false;
}
assert myAffectedFiles != null;
assert myDelayedWorks != null;
final Collection<String> removed = myDelta.myRemovedFiles;
if (removed != null) {
for (final String r : removed) {
myAffectedFiles.remove(new File(r));
}
}
return myDelayedWorks.doWork(myAffectedFiles);
}
finally {
if (myFilesToCompile != null) {
assert myDelta.myChangedFiles != null;
// if some class is associated with several sources,
// some of them may not have been compiled in this round, so such files should be considered unchanged
myDelta.myChangedFiles.retainAll(myFilesToCompile);
}
}
}
}
private void processModules(final DiffState state, File fileName) {
final Difference.Specifier<ModuleRepr, ModuleRepr.Diff> modulesDiff = state.myModulesDiff;
if (modulesDiff.unchanged()) {
return;
}
for (ModuleRepr moduleRepr : modulesDiff.added()) {
myDelta.addChangedClass(moduleRepr.name); // need this for integrate
// after module has been added, the whole target should be rebuilt
// because necessary 'require' directives may be missing from the newly added module-info file
myFuture.affectModule(moduleRepr, myAffectedFiles);
}
for (ModuleRepr removedModule : modulesDiff.removed()) {
myDelta.addDeletedClass(removedModule, fileName); // need this for integrate
myPresent.affectDependentModules(state, removedModule.name, null, true);
}
for (Pair<ModuleRepr, ModuleRepr.Diff> pair : modulesDiff.changed()) {
final ModuleRepr moduleRepr = pair.first;
final ModuleRepr.Diff d = pair.second;
boolean affectSelf = false;
boolean affectDeps = false;
UsageConstraint constraint = null;
myDelta.addChangedClass(moduleRepr.name); // need this for integrate
if (d.versionChanged()) {
final int version = moduleRepr.getVersion();
myPresent.affectDependentModules(state, moduleRepr.name, new UsageConstraint() {
@Override
public boolean checkResidence(int dep) {
final ModuleRepr depModule = myPresent.moduleReprByName(dep);
if (depModule != null) {
for (ModuleRequiresRepr requires : depModule.getRequires()) {
if (requires.name == moduleRepr.name && requires.getVersion() == version) {
return true;
}
}
}
return false;
}
}, false);
}
final Difference.Specifier<ModuleRequiresRepr, ModuleRequiresRepr.Diff> requiresDiff = d.requires();
for (ModuleRequiresRepr removed : requiresDiff.removed()) {
affectSelf = true;
if (removed.isTransitive()) {
affectDeps = true;
constraint = UsageConstraint.ANY;
break;
}
}
for (Pair<ModuleRequiresRepr, ModuleRequiresRepr.Diff> changed : requiresDiff.changed()) {
affectSelf |= changed.second.versionChanged();
if (changed.second.becameNonTransitive()) {
affectDeps = true;
// we could have created more precise constraint here: analyze if required module (recursively)
// has only qualified exports that include given module's name. But this seems to be excessive since
// in most cases module's exports are unqualified, so that any other module can access the exported API.
constraint = UsageConstraint.ANY;
}
}
final Difference.Specifier<ModulePackageRepr, ModulePackageRepr.Diff> exportsDiff = d.exports();
if (!affectDeps) {
for (ModulePackageRepr removedPackage : exportsDiff.removed()) {
affectDeps = true;
if (!removedPackage.isQualified()) {
constraint = UsageConstraint.ANY;
break;
}
for (Integer name : removedPackage.getModuleNames()) {
final UsageConstraint matchName = UsageConstraint.exactMatch(name);
if (constraint == null) {
constraint = matchName;
}
else {
constraint = constraint.or(matchName);
}
}
}
}
if (!affectDeps || constraint != UsageConstraint.ANY) {
for (Pair<ModulePackageRepr, ModulePackageRepr.Diff> p : exportsDiff.changed()) {
final Collection<Integer> removedModuleNames = p.second.targetModules().removed();
affectDeps |= !removedModuleNames.isEmpty();
if (!removedModuleNames.isEmpty()) {
affectDeps = true;
for (Integer name : removedModuleNames) {
final UsageConstraint matchName = UsageConstraint.exactMatch(name);
if (constraint == null) {
constraint = matchName;
}
else {
constraint = constraint.or(matchName);
}
}
}
}
}
if (affectSelf) {
myPresent.affectModule(moduleRepr, myAffectedFiles);
}
if (affectDeps) {
myPresent.affectDependentModules(state, moduleRepr.name, constraint, true);
}
}
}
}
public void differentiateOnRebuild(final Mappings delta) {
new Differential(delta).differentiate();
}
public void differentiateOnNonIncrementalMake(final Mappings delta,
final Collection<String> removed,
final Collection<File> filesToCompile) {
new Differential(delta, removed, filesToCompile).differentiate();
}
public boolean differentiateOnIncrementalMake
(final Mappings delta,
final Collection<String> removed,
final Collection<File> filesToCompile,
final Collection<File> compiledWithErrors,
final Collection<File> compiledFiles,
final Collection<File> affectedFiles,
@NotNull final DependentFilesFilter filter,
@Nullable final Callbacks.ConstantAffectionResolver constantSearch) {
return new Differential(delta, removed, filesToCompile, compiledWithErrors, compiledFiles, affectedFiles, filter, constantSearch).differentiate();
}
private void cleanupBackDependency(final int className, @Nullable Set<UsageRepr.Usage> usages, final IntIntMultiMaplet buffer) {
if (usages == null) {
final ClassFileRepr repr = getReprByName(null, className);
if (repr != null) {
usages = repr.getUsages();
}
}
if (usages != null) {
for (final UsageRepr.Usage u : usages) {
buffer.put(u.getOwner(), className);
}
}
}
private void cleanupRemovedClass(final Mappings delta, @NotNull final ClassFileRepr cr, File sourceFile, final Set<UsageRepr.Usage> usages, final IntIntMultiMaplet dependenciesTrashBin) {
final int className = cr.name;
// it is safe to cleanup class information if it is mapped to non-existing files only
final Collection<File> currentlyMapped = myClassToSourceFile.get(className);
if (currentlyMapped == null || currentlyMapped.isEmpty()) {
return;
}
if (currentlyMapped.size() == 1) {
if (!FileUtil.filesEqual(sourceFile, currentlyMapped.iterator().next())) {
// if classname is already mapped to a different source, the class with such FQ name exists elsewhere, so
// we cannot destroy all these links
return;
}
}
else {
// many files
for (File file : currentlyMapped) {
if (!FileUtil.filesEqual(sourceFile, file) && file.exists()) {
return;
}
}
}
if (cr instanceof ClassRepr) {
for (final int superSomething : ((ClassRepr)cr).getSupers()) {
delta.registerRemovedSuperClass(className, superSomething);
}
}
cleanupBackDependency(className, usages, dependenciesTrashBin);
myClassToClassDependency.remove(className);
myClassToSubclasses.remove(className);
myClassToSourceFile.remove(className);
if (cr instanceof ClassRepr) {
final ClassRepr _cr = (ClassRepr)cr;
if (!_cr.isLocal() && !_cr.isAnonymous()) {
myShortClassNameIndex.removeFrom(myContext.get(_cr.getShortName()), className);
}
}
}
public void integrate(final Mappings delta) {
synchronized (myLock) {
try {
assert (delta.isDifferentiated());
final Collection<String> removed = delta.myRemovedFiles;
delta.runPostPasses();
final IntIntMultiMaplet dependenciesTrashBin = new IntIntTransientMultiMaplet();
if (removed != null) {
for (final String file : removed) {
final File deletedFile = new File(file);
final Set<ClassFileRepr> fileClasses = (Set<ClassFileRepr>)mySourceFileToClasses.get(deletedFile);
if (fileClasses != null) {
for (final ClassFileRepr aClass : fileClasses) {
cleanupRemovedClass(delta, aClass, deletedFile, aClass.getUsages(), dependenciesTrashBin);
}
mySourceFileToClasses.remove(deletedFile);
}
}
}
if (!delta.isRebuild()) {
for (final Pair<ClassFileRepr, File> pair : delta.getDeletedClasses()) {
final ClassFileRepr deletedClass = pair.first;
cleanupRemovedClass(delta, deletedClass, pair.second, deletedClass.getUsages(), dependenciesTrashBin);
}
for (ClassRepr repr : delta.getAddedClasses()) {
if (!repr.isAnonymous() && !repr.isLocal()) {
myShortClassNameIndex.put(myContext.get(repr.getShortName()), repr.name);
}
}
final TIntHashSet superClasses = new TIntHashSet();
final IntIntTransientMultiMaplet addedSuperClasses = delta.getAddedSuperClasses();
final IntIntTransientMultiMaplet removedSuperClasses = delta.getRemovedSuperClasses();
addAllKeys(superClasses, addedSuperClasses);
addAllKeys(superClasses, removedSuperClasses);
superClasses.forEach(superClass -> {
final TIntHashSet added = addedSuperClasses.get(superClass);
TIntHashSet removed12 = removedSuperClasses.get(superClass);
final TIntHashSet old = myClassToSubclasses.get(superClass);
if (old == null) {
if (added != null && !added.isEmpty()) {
myClassToSubclasses.replace(superClass, added);
}
}
else {
boolean changed = false;
final int[] addedAsArray = added != null && !added.isEmpty()? added.toArray() : null;
if (removed12 != null && !removed12.isEmpty()) {
if (addedAsArray != null) {
// optimization: avoid unnecessary changes in the set
removed12 = (TIntHashSet)removed12.clone();
removed12.removeAll(addedAsArray);
}
if (!removed12.isEmpty()) {
changed = old.removeAll(removed12.toArray());
}
}
if (addedAsArray != null) {
changed |= old.addAll(addedAsArray);
}
if (changed) {
myClassToSubclasses.replace(superClass, old);
}
}
return true;
});
delta.getChangedClasses().forEach(className -> {
final Collection<File> sourceFiles = delta.myClassToSourceFile.get(className);
myClassToSourceFile.replace(className, sourceFiles);
cleanupBackDependency(className, null, dependenciesTrashBin);
return true;
});
delta.getChangedFiles().forEach(fileName -> {
final Collection<ClassFileRepr> classes = delta.mySourceFileToClasses.get(fileName);
mySourceFileToClasses.replace(fileName, classes);
return true;
});
// some classes may be associated with multiple sources.
// In case some of these sources was not compiled, but the class was changed, we need to update
// sourceToClasses mapping for such sources to include the updated ClassRepr version of the changed class
final THashSet<File> unchangedSources = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
delta.mySourceFileToClasses.forEachEntry(new TObjectObjectProcedure<File, Collection<ClassFileRepr>>() {
@Override
public boolean execute(File source, Collection<ClassFileRepr> b) {
unchangedSources.add(source);
return true;
}
});
unchangedSources.removeAll(delta.getChangedFiles());
if (!unchangedSources.isEmpty()) {
unchangedSources.forEach(unchangedSource -> {
final Collection<ClassFileRepr> updatedClasses = delta.mySourceFileToClasses.get(unchangedSource);
if (updatedClasses != null && !updatedClasses.isEmpty()) {
final List<ClassFileRepr> classesToPut = new ArrayList<>();
final TIntHashSet updatedClassNames = new TIntHashSet();
for (ClassFileRepr aClass : updatedClasses) {
// from all generated classes on this round consider only 'differentiated' ones, for
// which we can reliably say that the class has changed. Keep classes, for which no such checks were made,
// to make it possible to create a diff and compare changes on next compilation rounds.
if (delta.getChangedClasses().contains(aClass.name)) {
classesToPut.add(aClass);
updatedClassNames.add(aClass.name);
}
}
final Collection<ClassFileRepr> currentClasses = mySourceFileToClasses.get(unchangedSource);
if (currentClasses != null) {
for (ClassFileRepr aClass : currentClasses) {
if (!updatedClassNames.contains(aClass.name)) {
classesToPut.add(aClass);
}
}
}
mySourceFileToClasses.replace(unchangedSource, classesToPut);
}
return true;
});
}
}
else {
myClassToSubclasses.putAll(delta.myClassToSubclasses);
myClassToSourceFile.replaceAll(delta.myClassToSourceFile);
mySourceFileToClasses.replaceAll(delta.mySourceFileToClasses);
delta.mySourceFileToClasses.forEachEntry(new TObjectObjectProcedure<File, Collection<ClassFileRepr>>() {
@Override
public boolean execute(File src, Collection<ClassFileRepr> classes) {
for (ClassFileRepr repr : classes) {
if (repr instanceof ClassRepr) {
final ClassRepr clsRepr = (ClassRepr)repr;
if (!clsRepr.isAnonymous() && !clsRepr.isLocal()) {
myShortClassNameIndex.put(myContext.get(clsRepr.getShortName()), repr.name);
}
}
}
return true;
}
});
}
// updating classToClass dependencies
final TIntHashSet affectedClasses = new TIntHashSet();
addAllKeys(affectedClasses, dependenciesTrashBin);
addAllKeys(affectedClasses, delta.myClassToClassDependency);
affectedClasses.forEach(aClass -> {
final TIntHashSet now = delta.myClassToClassDependency.get(aClass);
final TIntHashSet toRemove = dependenciesTrashBin.get(aClass);
final boolean hasDataToAdd = now != null && !now.isEmpty();
if (toRemove != null && !toRemove.isEmpty()) {
final TIntHashSet current = myClassToClassDependency.get(aClass);
if (current != null && !current.isEmpty()) {
final TIntHashSet before = new TIntHashSet();
addAll(before, current);
final boolean removed1 = current.removeAll(toRemove.toArray());
final boolean added = hasDataToAdd && current.addAll(now.toArray());
if ((removed1 && !added) || (!removed1 && added) || !before.equals(current)) {
myClassToClassDependency.replace(aClass, current);
}
}
else {
if (hasDataToAdd) {
myClassToClassDependency.put(aClass, now);
}
}
}
else {
// nothing to remove for this class
if (hasDataToAdd) {
myClassToClassDependency.put(aClass, now);
}
}
return true;
});
}
finally {
delta.close();
}
}
}
public Callbacks.Backend getCallback() {
return new Callbacks.Backend() {
@Override
public void associate(String classFileName, Collection<String> sources, ClassReader cr) {
synchronized (myLock) {
final int classFileNameS = myContext.get(classFileName);
final ClassFileRepr result = new ClassfileAnalyzer(myContext).analyze(classFileNameS, cr);
if (result != null) {
// since java9 'repr' can represent either a class or a compiled module-info.java
final int className = result.name;
for (String sourceFileName : sources) {
final File sourceFile = new File(sourceFileName);
myClassToSourceFile.put(className, sourceFile);
mySourceFileToClasses.put(sourceFile, result);
}
if (result instanceof ClassRepr) {
for (final int s : ((ClassRepr)result).getSupers()) {
myClassToSubclasses.put(s, className);
}
}
for (final UsageRepr.Usage u : result.getUsages()) {
final int owner = u.getOwner();
if (owner != className) {
myClassToClassDependency.put(owner, className);
}
}
}
}
}
@Override
public void associate(final String classFileName, final String sourceFileName, final ClassReader cr) {
associate(classFileName, Collections.singleton(sourceFileName), cr);
}
@Override
public void registerImports(final String className, final Collection<String> imports, Collection<String> staticImports) {
final List<String> allImports = new ArrayList<>();
for (String anImport : imports) {
if (!anImport.endsWith("*")) {
allImports.add(anImport); // filter out wildcard imports
}
}
for (final String s : staticImports) {
int i = s.length() - 1;
while (s.charAt(i) != '.') {
i--;
}
final String anImport = s.substring(0, i);
if (!anImport.endsWith("*")) {
allImports.add(anImport); // filter out wildcard imports
}
}
if (!allImports.isEmpty()) {
myPostPasses.offer(() -> {
final int rootClassName = myContext.get(className.replace(".", "/"));
final Collection<File> fileNames = myClassToSourceFile.get(rootClassName);
final ClassRepr repr = fileNames != null && !fileNames.isEmpty()? getClassReprByName(fileNames.iterator().next(), rootClassName) : null;
for (final String i : allImports) {
final int iname = myContext.get(i.replace('.', '/'));
myClassToClassDependency.put(iname, rootClassName);
if (repr != null && repr.addUsage(UsageRepr.createClassUsage(myContext, iname))) {
for (File fileName : fileNames) {
mySourceFileToClasses.put(fileName, repr);
}
}
}
});
}
}
};
}
@Nullable
public Set<ClassRepr> getClasses(final String sourceFileName) {
final File f = new File(sourceFileName);
synchronized (myLock) {
final Collection<ClassFileRepr> reprs = mySourceFileToClasses.get(f);
if (reprs == null || reprs.isEmpty()) {
return null;
}
final Set<ClassRepr> result = new THashSet<>();
for (ClassFileRepr repr : reprs) {
if (repr instanceof ClassRepr) {
result.add((ClassRepr)repr);
}
}
return result;
}
}
@Nullable
public Collection<File> getClassSources(int className) {
synchronized (myLock) {
return myClassToSourceFile.get(className);
}
}
public void close() {
synchronized (myLock) {
myClassToSubclasses.close();
myClassToClassDependency.close();
mySourceFileToClasses.close();
myClassToSourceFile.close();
if (!myIsDelta) {
myShortClassNameIndex.close();
// only close if you own the context
final DependencyContext context = myContext;
if (context != null) {
context.close();
myContext = null;
}
}
else {
if (!myDeltaIsTransient) {
FileUtil.delete(myRootDir);
}
}
}
}
public void flush(final boolean memoryCachesOnly) {
synchronized (myLock) {
myClassToSubclasses.flush(memoryCachesOnly);
myClassToClassDependency.flush(memoryCachesOnly);
mySourceFileToClasses.flush(memoryCachesOnly);
myClassToSourceFile.flush(memoryCachesOnly);
if (!myIsDelta) {
myShortClassNameIndex.flush(memoryCachesOnly);
// flush if you own the context
final DependencyContext context = myContext;
if (context != null) {
context.clearMemoryCaches();
if (!memoryCachesOnly) {
context.flush();
}
}
}
}
}
private static boolean addAll(final TIntHashSet whereToAdd, TIntHashSet whatToAdd) {
if (whatToAdd.isEmpty()) {
return false;
}
final Ref<Boolean> changed = new Ref<>(Boolean.FALSE);
whatToAdd.forEach(value -> {
if (whereToAdd.add(value)) {
changed.set(Boolean.TRUE);
}
return true;
});
return changed.get();
}
private static void addAllKeys(final TIntHashSet whereToAdd, final IntIntMultiMaplet maplet) {
maplet.forEachEntry(new TIntObjectProcedure<TIntHashSet>() {
@Override
public boolean execute(int key, TIntHashSet b) {
whereToAdd.add(key);
return true;
}
});
}
private void registerAddedSuperClass(final int aClass, final int superClass) {
assert (myAddedSuperClasses != null);
myAddedSuperClasses.put(superClass, aClass);
}
private void registerRemovedSuperClass(final int aClass, final int superClass) {
assert (myRemovedSuperClasses != null);
myRemovedSuperClasses.put(superClass, aClass);
}
private boolean isDifferentiated() {
return myIsDifferentiated;
}
private boolean isRebuild() {
return myIsRebuild;
}
private void addDeletedClass(final ClassFileRepr cr, File fileName) {
assert (myDeletedClasses != null);
myDeletedClasses.add(Pair.create(cr, fileName));
addChangedClass(cr.name);
}
private void addAddedClass(final ClassRepr cr) {
assert (myAddedClasses != null);
myAddedClasses.add(cr);
addChangedClass(cr.name);
}
private void addChangedClass(final int it) {
assert (myChangedClasses != null && myChangedFiles != null);
myChangedClasses.add(it);
final Collection<File> files = myClassToSourceFile.get(it);
if (files != null) {
myChangedFiles.addAll(files);
}
}
@NotNull
private Set<Pair<ClassFileRepr, File>> getDeletedClasses() {
return myDeletedClasses == null ? Collections.emptySet() : Collections.unmodifiableSet(myDeletedClasses);
}
@NotNull
private Set<ClassRepr> getAddedClasses() {
return myAddedClasses == null ? Collections.emptySet() : Collections.unmodifiableSet(myAddedClasses);
}
private TIntHashSet getChangedClasses() {
return myChangedClasses;
}
private THashSet<File> getChangedFiles() {
return myChangedFiles;
}
private static void debug(final String s) {
LOG.debug(s);
}
private void debug(final String comment, final int s) {
myDebugS.debug(comment, s);
}
private void debug(final String comment, final File f) {
debug(comment, f.getPath());
}
private void debug(final String comment, final String s) {
myDebugS.debug(comment, s);
}
private void debug(final String comment, final boolean s) {
myDebugS.debug(comment, s);
}
public void toStream(final PrintStream stream) {
final Streamable[] data = {
myClassToSubclasses,
myClassToClassDependency,
mySourceFileToClasses,
myClassToSourceFile,
};
final String[] info = {
"ClassToSubclasses",
"ClassToClassDependency",
"SourceFileToClasses",
"ClassToSourceFile",
"SourceFileToAnnotationUsages",
"SourceFileToUsages"
};
for (int i = 0; i < data.length; i++) {
stream.print("Begin Of ");
stream.println(info[i]);
data[i].toStream(myContext, stream);
stream.print("End Of ");
stream.println(info[i]);
}
}
public void toStream(File outputRoot) {
final Streamable[] data = {
myClassToSubclasses,
myClassToClassDependency,
mySourceFileToClasses,
myClassToSourceFile,
myShortClassNameIndex
};
final String[] info = {
"ClassToSubclasses",
"ClassToClassDependency",
"SourceFileToClasses",
"ClassToSourceFile",
"ShortClassNameIndex"
};
for (int i = 0; i < data.length; i++) {
final File file = new File(outputRoot, info[i]);
FileUtil.createIfDoesntExist(file);
try {
final PrintStream stream = new PrintStream(file);
try {
data[i].toStream(myContext, stream);
}
finally {
stream.close();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
|
goodwinnk/intellij-community
|
jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java
|
Java
|
apache-2.0
| 120,339
|
layui.define(['layer', 'carousel'], function (exports) {
var $ = layui.jquery;
var layer = layui.layer;
var carousel = layui.carousel;
// 添加步骤条dom节点
var renderDom = function (elem, stepItems, postion) {
var stepDiv = '<div class="lay-step">';
for (var i = 0; i < stepItems.length; i++) {
stepDiv += '<div class="step-item">';
// 线
if (i < (stepItems.length - 1)) {
if (i < postion) {
stepDiv += '<div class="step-item-tail"><i class="step-item-tail-done"></i></div>';
} else {
stepDiv += '<div class="step-item-tail"><i class=""></i></div>';
}
}
// 数字
var number = stepItems[i].number;
if (!number) {
number = i + 1;
}
if (i == postion) {
stepDiv += '<div class="step-item-head step-item-head-active"><i class="layui-icon">' + number + '</i></div>';
} else if (i < postion) {
stepDiv += '<div class="step-item-head"><i class="layui-icon layui-icon-ok"></i></div>';
} else {
stepDiv += '<div class="step-item-head "><i class="layui-icon">' + number + '</i></div>';
}
// 标题和描述
var title = stepItems[i].title;
var desc = stepItems[i].desc;
if (title || desc) {
stepDiv += '<div class="step-item-main">';
if (title) {
stepDiv += '<div class="step-item-main-title">' + title + '</div>';
}
if (desc) {
stepDiv += '<div class="step-item-main-desc">' + desc + '</div>';
}
stepDiv += '</div>';
}
stepDiv += '</div>';
}
stepDiv += '</div>';
$(elem).prepend(stepDiv);
// 计算每一个条目的宽度
var bfb = 100 / stepItems.length;
$('.step-item').css('width', bfb + '%');
};
var step = {
// 渲染步骤条
render: function (param) {
param.indicator = 'none'; // 不显示指示器
param.arrow = 'always'; // 始终显示箭头
param.autoplay = false; // 关闭自动播放
if (!param.stepWidth) {
param.stepWidth = '400px';
}
// 渲染轮播图
carousel.render(param);
// 渲染步骤条
var stepItems = param.stepItems;
renderDom(param.elem, stepItems, 0);
$('.lay-step').css('width', param.stepWidth);
//监听轮播切换事件
carousel.on('change(' + param.filter + ')', function (obj) {
$(param.elem).find('.lay-step').remove();
renderDom(param.elem, stepItems, obj.index);
$('.lay-step').css('width', param.stepWidth);
});
// 隐藏左右箭头按钮
$(param.elem).find('.layui-carousel-arrow').css('display', 'none');
// 去掉轮播图的背景颜色
$(param.elem).css('background-color', 'transparent');
},
// 下一步
next: function (elem) {
$(elem).find('.layui-carousel-arrow[lay-type=add]').trigger('click');
},
// 上一步
pre: function (elem) {
$(elem).find('.layui-carousel-arrow[lay-type=sub]').trigger('click');
}
};
layui.link(layui.cache.base + 'step-lay/step.css');
exports('step', step);
});
|
chenghao/haoAdmin
|
static/assets/module/step-lay/step.js
|
JavaScript
|
apache-2.0
| 3,640
|
Ext.define('PF.view.PizzaShopMap', {
extend:'PF.view.EsriMap',
xtype:'pizzashopmap',
config:{
// Override some config which the base EsriMap will use...
basemapLayer:"http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
mapHeight:"140px",
// And provide a bit of our own.
pizzaShop:null
},
pizzaShopGraphicsLayer: null,
initialize: function() {
this.callParent();
var pizzaShopSymbol = new esri.symbol.PictureMarkerSymbol(
{
"angle":0,
"xoffset":0,"yoffset":11,"type":"esriPMS",
"url":"http://static.arcgis.com/images/Symbols/Shapes/RedPin1LargeB.png","contentType":"image/png",
"width":28,"height":28
});
this.pizzaShopGraphicsLayer = new esri.layers.GraphicsLayer();
var pizzaShopRenderer = new esri.renderer.SimpleRenderer(pizzaShopSymbol);
this.pizzaShopGraphicsLayer.setRenderer(pizzaShopRenderer);
},
// Inherit from EsriMap, and implement this function to add config to your map beyond the basemap.
initMap:function () {
var map = this.getMap();
map.addLayer(this.pizzaShopGraphicsLayer);
var me = this;
dojo.connect(map, 'onLoad', function (e) {
map.disablePan();
me.zoomToPizzaShop();
});
},
applyPizzaShop: function (pizzaShop) {
this.pizzaShopGraphicsLayer.clear();
if (pizzaShop != null)
{
this.pizzaShopGraphicsLayer.add(new esri.Graphic(pizzaShop.geometry));
this.zoomToPizzaShop();
}
return pizzaShop;
},
zoomToPizzaShop: function() {
var map = this.getMap();
if (map)
{
var pizzaShop = this.getPizzaShop();
if (pizzaShop)
{
map.centerAndZoom(pizzaShop.geometry, 17);
}
}
}
});
|
Esri/sencha-touch-map-checkin-js
|
app/view/PizzaShopMap.js
|
JavaScript
|
apache-2.0
| 1,651
|
/**
* Health and Metrics specific code.
*/
package org.sanjeevenutan.marklogic.tradebrowser.config.metrics;
|
sanj2sanj/marklogic-trade-browser
|
src/main/java/org/sanjeevenutan/marklogic/tradebrowser/config/metrics/package-info.java
|
Java
|
apache-2.0
| 111
|
/**
*Licensed to the Apache Software Foundation (ASF) under one
*or more contributor license agreements. See the NOTICE file
*distributed with this work for additional information
*regarding copyright ownership. The ASF licenses this file
*to you under the Apache License, Version 2.0 (the"
*License"); you may not use this file except in compliance
*with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/
package org.apache.gora.examples.generated;
public class TokenDatum extends org.apache.gora.persistency.impl.PersistentBase implements org.apache.avro.specific.SpecificRecord, org.apache.gora.persistency.Persistent {
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"TokenDatum\",\"namespace\":\"org.apache.gora.examples.generated\",\"fields\":[{\"name\":\"count\",\"type\":\"int\",\"default\":0}]}");
private static final long serialVersionUID = -4481652577902636424L;
/** Enum containing all data bean's fields. */
public static enum Field {
COUNT(0, "count"),
;
/**
* Field's index.
*/
private int index;
/**
* Field's name.
*/
private String name;
/**
* Field's constructor
* @param index field's index.
* @param name field's name.
*/
Field(int index, String name) {this.index=index;this.name=name;}
/**
* Gets field's index.
* @return int field's index.
*/
public int getIndex() {return index;}
/**
* Gets field's name.
* @return String field's name.
*/
public String getName() {return name;}
/**
* Gets field's attributes to string.
* @return String field's attributes to string.
*/
public String toString() {return name;}
};
public static final String[] _ALL_FIELDS = {
"count",
};
/**
* Gets the total field count.
* @return int field count
*/
public int getFieldsCount() {
return TokenDatum._ALL_FIELDS.length;
}
private int count;
public org.apache.avro.Schema getSchema() { return SCHEMA$; }
// Used by DatumWriter. Applications should not call.
public java.lang.Object get(int field$) {
switch (field$) {
case 0: return count;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
// Used by DatumReader. Applications should not call.
@SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value) {
switch (field$) {
case 0: count = (java.lang.Integer)(value); break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
}
/**
* Gets the value of the 'count' field.
*/
public java.lang.Integer getCount() {
return count;
}
/**
* Sets the value of the 'count' field.
* @param value the value to set.
*/
public void setCount(java.lang.Integer value) {
this.count = value;
setDirty(0);
}
/**
* Checks the dirty status of the 'count' field. A field is dirty if it represents a change that has not yet been written to the database.
* @param value the value to set.
*/
public boolean isCountDirty() {
return isDirty(0);
}
/** Creates a new TokenDatum RecordBuilder */
public static org.apache.gora.examples.generated.TokenDatum.Builder newBuilder() {
return new org.apache.gora.examples.generated.TokenDatum.Builder();
}
/** Creates a new TokenDatum RecordBuilder by copying an existing Builder */
public static org.apache.gora.examples.generated.TokenDatum.Builder newBuilder(org.apache.gora.examples.generated.TokenDatum.Builder other) {
return new org.apache.gora.examples.generated.TokenDatum.Builder(other);
}
/** Creates a new TokenDatum RecordBuilder by copying an existing TokenDatum instance */
public static org.apache.gora.examples.generated.TokenDatum.Builder newBuilder(org.apache.gora.examples.generated.TokenDatum other) {
return new org.apache.gora.examples.generated.TokenDatum.Builder(other);
}
@Override
public org.apache.gora.examples.generated.TokenDatum clone() {
return newBuilder(this).build();
}
private static java.nio.ByteBuffer deepCopyToReadOnlyBuffer(
java.nio.ByteBuffer input) {
java.nio.ByteBuffer copy = java.nio.ByteBuffer.allocate(input.capacity());
int position = input.position();
input.reset();
int mark = input.position();
int limit = input.limit();
input.rewind();
input.limit(input.capacity());
copy.put(input);
input.rewind();
copy.rewind();
input.position(mark);
input.mark();
copy.position(mark);
copy.mark();
input.position(position);
copy.position(position);
input.limit(limit);
copy.limit(limit);
return copy.asReadOnlyBuffer();
}
/**
* RecordBuilder for TokenDatum instances.
*/
public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<TokenDatum>
implements org.apache.avro.data.RecordBuilder<TokenDatum> {
private int count;
/** Creates a new Builder */
private Builder() {
super(org.apache.gora.examples.generated.TokenDatum.SCHEMA$);
}
/** Creates a Builder by copying an existing Builder */
private Builder(org.apache.gora.examples.generated.TokenDatum.Builder other) {
super(other);
}
/** Creates a Builder by copying an existing TokenDatum instance */
private Builder(org.apache.gora.examples.generated.TokenDatum other) {
super(org.apache.gora.examples.generated.TokenDatum.SCHEMA$);
if (isValidValue(fields()[0], other.count)) {
this.count = (java.lang.Integer) data().deepCopy(fields()[0].schema(), other.count);
fieldSetFlags()[0] = true;
}
}
/** Gets the value of the 'count' field */
public java.lang.Integer getCount() {
return count;
}
/** Sets the value of the 'count' field */
public org.apache.gora.examples.generated.TokenDatum.Builder setCount(int value) {
validate(fields()[0], value);
this.count = value;
fieldSetFlags()[0] = true;
return this;
}
/** Checks whether the 'count' field has been set */
public boolean hasCount() {
return fieldSetFlags()[0];
}
/** Clears the value of the 'count' field */
public org.apache.gora.examples.generated.TokenDatum.Builder clearCount() {
fieldSetFlags()[0] = false;
return this;
}
@Override
public TokenDatum build() {
try {
TokenDatum record = new TokenDatum();
record.count = fieldSetFlags()[0] ? this.count : (java.lang.Integer) defaultValue(fields()[0]);
return record;
} catch (Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
}
public TokenDatum.Tombstone getTombstone(){
return TOMBSTONE;
}
public TokenDatum newInstance(){
return newBuilder().build();
}
private static final Tombstone TOMBSTONE = new Tombstone();
public static final class Tombstone extends TokenDatum implements org.apache.gora.persistency.Tombstone {
private Tombstone() { }
/**
* Gets the value of the 'count' field.
*/
public java.lang.Integer getCount() {
throw new java.lang.UnsupportedOperationException("Get is not supported on tombstones");
}
/**
* Sets the value of the 'count' field.
* @param value the value to set.
*/
public void setCount(java.lang.Integer value) {
throw new java.lang.UnsupportedOperationException("Set is not supported on tombstones");
}
/**
* Checks the dirty status of the 'count' field. A field is dirty if it represents a change that has not yet been written to the database.
* @param value the value to set.
*/
public boolean isCountDirty() {
throw new java.lang.UnsupportedOperationException("IsDirty is not supported on tombstones");
}
}
private static final org.apache.avro.io.DatumWriter
DATUM_WRITER$ = new org.apache.avro.specific.SpecificDatumWriter(SCHEMA$);
private static final org.apache.avro.io.DatumReader
DATUM_READER$ = new org.apache.avro.specific.SpecificDatumReader(SCHEMA$);
/**
* Writes AVRO data bean to output stream in the form of AVRO Binary encoding format. This will transform
* AVRO data bean from its Java object form to it s serializable form.
*
* @param out java.io.ObjectOutput output stream to write data bean in serializable form
*/
@Override
public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
out.write(super.getDirtyBytes().array());
DATUM_WRITER$.write(this, org.apache.avro.io.EncoderFactory.get()
.directBinaryEncoder((java.io.OutputStream) out,
null));
}
/**
* Reads AVRO data bean from input stream in it s AVRO Binary encoding format to Java object format.
* This will transform AVRO data bean from it s serializable form to deserialized Java object form.
*
* @param in java.io.ObjectOutput input stream to read data bean in serializable form
*/
@Override
public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
byte[] __g__dirty = new byte[getFieldsCount()];
in.read(__g__dirty);
super.setDirtyBytes(java.nio.ByteBuffer.wrap(__g__dirty));
DATUM_READER$.read(this, org.apache.avro.io.DecoderFactory.get()
.directBinaryDecoder((java.io.InputStream) in,
null));
}
}
|
kamaci/gora
|
gora-core/src/examples/java/org/apache/gora/examples/generated/TokenDatum.java
|
Java
|
apache-2.0
| 9,947
|
#!/usr/bin/env perl
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
## script to create a table of HGVS stings and variation_ids for search index building
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<helpdesk.org>.
=cut
use strict;
use warnings;
use FileHandle;
use Getopt::Long;
my $config = {};
GetOptions(
$config,
'version=i',
'script_dir=s',
'vep_input=s',
'cache_dir=s',
'no_cleanup',
'help!',
) or die "Error: Failed to parse command line arguments\n";
if ($config->{help}) {
usage();
exit(0);
}
if (!$config->{version}) {
die "Version is missing. Set version with --version.";
}
my $version = $config->{version};
my @assemblies = ('GRCh37', 'GRCh38');
my $cache_dirs = {
'homo_sapiens' => '',
'homo_sapiens_merged' => '--merged',
'homo_sapiens_refseq' => '--refseq',
};
foreach my $dir_name (qw/script_dir cache_dir/) {
if (! $config->{$dir_name}) {
die "Parameter ($dir_name) is not set.";
}
if (!(-d $config->{$dir_name})) {
die "$dir_name: ", $config->{$dir_name}, " is not a directory.";
}
}
my $script_dir = $config->{script_dir};
die "script_dir is missing file variant_effect_predictor.pl" unless (-f "$script_dir/variant_effect_predictor.pl");
$config->{vep_input} ||= "$script_dir/t/testdata/test_vep_input.txt.gz";
die "vep_input: ", $config->{vep_input}, " is not a file." unless (-f $config->{vep_input});
$config->{cache_dir} ||= $ENV{HOME} . '/.vep';
#all_cache_files_are_installed($config);
run_vep($config);
tests($config);
cleanup($config) unless($config->{no_cleanup});
sub all_cache_files_are_installed {
my $config = shift;
my $root_cache_dir = $config->{cache_dir};
foreach my $cache_dir (keys %$cache_dirs) {
foreach my $assembly (@assemblies) {
my $dir = "$root_cache_dir/$cache_dir/$version\_$assembly";
if (!(-d $dir)) {
die "$dir is not a directory. Cache files for $cache_dir/$version\_$assembly are missing.";
}
}
}
return 1;
}
sub run_vep {
my $config = shift;
my $script_dir = $config->{script_dir};
my $input = $config->{vep_input};
my $root_cache_dir = $config->{cache_dir};
my $output_files = {};
foreach my $cache_dir (keys %$cache_dirs) {
foreach my $assembly (@assemblies) {
my $vep_run_name = "$cache_dir\_$version\_$assembly";
my $params = $cache_dirs->{$cache_dir} . " --assembly $assembly";
my $output = "$script_dir/test_vep_output_$vep_run_name";
my $err_file = "$script_dir/err_$vep_run_name";
my $out_file = "$script_dir/out_$vep_run_name";
$output_files->{$vep_run_name}->{vep_output} = $output;
$output_files->{$vep_run_name}->{err} = $err_file;
$output_files->{$vep_run_name}->{out} = $out_file;
# -cache_version
my $cmd = "perl $script_dir/variant_effect_predictor.pl --cache --offline --dir $root_cache_dir -i $input -o $output --force_overwrite --no_stats --regulatory --sift b --polyphen b $params";
run_cmd("$cmd 1>$out_file 2>$err_file");
}
}
$config->{output_files} = $output_files;
}
sub tests {
my $config = shift;
my $output_files = $config->{output_files};
my @annotations = qw/SIFT PolyPhen MotifFeature RegulatoryFeature/;
foreach my $vep_run_name (keys %$output_files) {
my $vep_out_file = $output_files->{$vep_run_name}->{vep_output};
my $fh = FileHandle->new($vep_out_file, 'r');
my $covered_chroms = {};
my $has_annotation = {};
while (<$fh>) {
chomp;
next if /^#/;
my ($name, $location, $rest) = split("\t", $_, 3);
my ($chrom, $position) = split(':', $location);
$covered_chroms->{$chrom} = 1;
foreach my $annotation (@annotations) {
if ($rest =~ /$annotation/) {
$has_annotation->{$annotation} = 1;
}
}
}
$fh->close();
foreach my $chrom (1..22, 'X', 'Y', 'MT') {
if (!$covered_chroms->{$chrom}) {
die "Chrom $chrom is missing from VEP output $vep_out_file. Need to check cache files are dumped correctly.";
}
}
print STDOUT "All chromosomes are covered in $vep_out_file\n";
foreach my $annotation (@annotations) {
if (!$has_annotation->{$annotation}) {
die "Annotation: $annotation is missing from VEP output $vep_out_file. Need to check cache files are dumped correctly.";
}
}
print STDOUT "Annotations (", join(', ', @annotations), ") are contained in $vep_out_file\n";
}
return 1;
}
sub run_cmd {
my $cmd = shift;
if (my $return_value = system($cmd)) {
$return_value >>= 8;
die "system($cmd) failed: $return_value";
}
}
sub cleanup {
my $config = shift;
my $output_files = $config->{output_files};
foreach my $vep_run_name (keys %$output_files) {
foreach my $file_type (qw/vep_output err out/) {
my $file = $output_files->{$vep_run_name}->{$file_type};
run_cmd("rm $file");
}
}
}
sub usage {
my $usage =<<END;
Usage:
perl test_chrom_coverage_in_cache_files.pl [arguments]
The script runs for human only. It checks that all human chromosomes have been dumped to the
cache files (default, refseq, merged) for GRCh37 and GRCh38.
The script should be run after the cache file generation. Copy and unpack all the human cache files
to the cache file directory (--cache_dir).
bsub -J test_chrom_coverage -o out -e err -R"select[mem>2500] rusage[mem=2500]" -M2500 perl test_chrom_coverage_in_cache_files.pl -version 78 -cache_dir /lustre/scratch110/ensembl/at7/vep/ -script_dir ~/DEV/ensembl-tools/scripts/variant_effect_predictor/
Options
=======
--help Display this message and quit
--version Set the version for the new release
--script_dir Location of variant_effect_predictor.pl script
--cache_dir Cache file directory
--no_cleanup Don't clean up err, out, vep_output files
END
print $usage;
}
|
dbolser/ensembl-variation
|
scripts/misc/test_chrom_coverage_in_cache_files.pl
|
Perl
|
apache-2.0
| 6,591
|
'use strict';
/**
* Vertex segment.
* @exception {Error} Messages.CONSTRUCT_ERROR
*
* @class VtxSegment
*
* @param {Vertex} startVertex Optional. start vertex.
* @param {Vertex} endVertex Optional. end vertex.
*/
var VtxSegment = function(startVertex, endVertex)
{
if (!(this instanceof VtxSegment))
{
throw new Error(Messages.CONSTRUCT_ERROR);
}
/**
* start vertex.
* @type {Vertex}
*/
this.startVertex;
/**
* end vertex.
* @type {Vertex}
*/
this.endVertex;
if (startVertex)
{ this.startVertex = startVertex; }
if (endVertex)
{ this.endVertex = endVertex; }
};
/**
* set start, end vertex.
* @param {Vertex} startVertex
* @param {Vertex} endVertex
*/
VtxSegment.prototype.setVertices = function(startVertex, endVertex)
{
this.startVertex = startVertex;
this.endVertex = endVertex;
};
/**
* get direction between start vertex and end vertex.
* @param {Point3d} resultDirection if undefined , set new Point3D instance.
* @returns {Point3d} resultDirection
*/
VtxSegment.prototype.getDirection = function(resultDirection)
{
// the direction is an unitary vector.
var resultDirection = this.getVector();
if (resultDirection === undefined)
{ return undefined; }
resultDirection.unitary();
return resultDirection;
};
/**
* get vector point between start vertex and end vertex.
* @param {Point3d} resultVector if undefined , set new Point3D instance.
* @returns {Point3d} resultVector
*/
VtxSegment.prototype.getVector = function(resultVector)
{
if (this.startVertex === undefined || this.endVertex === undefined)
{ return undefined; }
var startPoint = this.startVertex.point3d;
var endPoint = this.endVertex.point3d;
if (startPoint === undefined || endPoint === undefined)
{ return undefined; }
resultVector = startPoint.getVectorToPoint(endPoint, resultVector);
return resultVector;
};
/**
* get line between start vertex and end vertex.
* @param {Line} resultLine if undefined , set new Line instance.
* @returns {Line} resultLine
*/
VtxSegment.prototype.getLine = function(resultLine)
{
if (resultLine === undefined)
{ resultLine = new Line(); }
var dir = this.getDirection(); // unitary direction.
var strPoint = this.startVertex.point3d;
resultLine.setPointAndDir(strPoint.x, strPoint.y, strPoint.z, dir.x, dir.y, dir.z);
return resultLine;
};
/**
* get squared length.
* @returns {Number} squared length
*
* @see Point3D#squareDistToPoint
*/
VtxSegment.prototype.getSquaredLength = function()
{
return this.startVertex.point3d.squareDistToPoint(this.endVertex.point3d);
};
/**
* get length.
* @returns {Number} square root of squared length
*/
VtxSegment.prototype.getLength = function()
{
return Math.sqrt(this.getSquaredLength());
};
/**
* get intersection info with point.
* @param {Point3D} point
* @param {Number} error default is 10E-8.
* @returns {Number} Constant.INTERSECTION_*
* Constant.INTERSECTION_OUTSIDE = 0
* Constant.INTERSECTION_INTERSECT= 1
* Constant.INTERSECTION_INSIDE = 2
* Constant.INTERSECTION_POINT_A = 3
* Constant.INTERSECTION_POINT_B = 4
*
* @see Constant
* @see Line#isCoincidentPoint
* @see Point3D#distToPoint
*/
VtxSegment.prototype.intersectionWithPoint = function(point, error)
{
// check if the point intersects the vtxSegment's line.
var line = this.getLine();
if (error === undefined)
{ error = 10E-8; }
if (!line.isCoincidentPoint(point, error))
{ return Constant.INTERSECTION_OUTSIDE; } // no intersection.
// now, check if is inside of the segment or if is coincident with any vertex of segment.
var distA = this.startVertex.point3d.distToPoint(point);
var distB = this.endVertex.point3d.distToPoint(point);
var distTotal = this.getLength();
if (distA < error)
{ return Constant.INTERSECTION_POINT_A; }
if (distB < error)
{ return Constant.INTERSECTION_POINT_B; }
if (distA> distTotal || distB> distTotal)
{
return Constant.INTERSECTION_OUTSIDE;
}
if (Math.abs(distA + distB - distTotal) < error)
{ return Constant.INTERSECTION_INSIDE; }
};
|
Gaia3D/mago3djs
|
src/mago3d/geometry/VtxSegment.js
|
JavaScript
|
apache-2.0
| 4,096
|
from functools import update_wrapper
from django.http import Http404, HttpResponseRedirect
from django.contrib.admin import ModelAdmin, actions
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME
from django.contrib.contenttypes import views as contenttype_views
from django.views.decorators.csrf import csrf_protect
from django.db.models.base import ModelBase
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse, NoReverseMatch
from django.template.response import TemplateResponse
from django.utils import six
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from django.views.decorators.cache import never_cache
from django.conf import settings
LOGIN_FORM_KEY = 'this_is_the_login_form'
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class AdminSite(object):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLconf. Models are registered with the AdminSite using the
register() method, and the get_urls() method can then be used to access Django view
functions that present a full admin interface for the collection of registered
models.
"""
login_form = None
index_template = None
app_index_template = None
login_template = None
logout_template = None
password_change_template = None
password_change_done_template = None
def __init__(self, name='admin', app_name='admin'):
self._registry = {} # model_class class -> admin_class instance
self.name = name
self.app_name = app_name
self._actions = {'delete_selected': actions.delete_selected}
self._global_actions = self._actions.copy()
def register(self, model_or_iterable, admin_class=None, **options):
"""
Registers the given model(s) with the given admin class.
The model(s) should be Model classes, not instances.
If an admin class isn't given, it will use ModelAdmin (the default
admin options). If keyword arguments are given -- e.g., list_display --
they'll be applied as options to the admin class.
If a model is already registered, this will raise AlreadyRegistered.
If a model is abstract, this will raise ImproperlyConfigured.
"""
if not admin_class:
admin_class = ModelAdmin
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model._meta.abstract:
raise ImproperlyConfigured('The model %s is abstract, so it '
'cannot be registered with admin.' % model.__name__)
if model in self._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **options then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes issues later on.
options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
if admin_class is not ModelAdmin and settings.DEBUG:
admin_class.validate(model)
# Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self)
def unregister(self, model_or_iterable):
"""
Unregisters the given model(s).
If a model isn't already registered, this will raise NotRegistered.
"""
if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable]
for model in model_or_iterable:
if model not in self._registry:
raise NotRegistered('The model %s is not registered' % model.__name__)
del self._registry[model]
def add_action(self, action, name=None):
"""
Register an action to be available globally.
"""
name = name or action.__name__
self._actions[name] = action
self._global_actions[name] = action
def disable_action(self, name):
"""
Disable a globally-registered action. Raises KeyError for invalid names.
"""
del self._actions[name]
def get_action(self, name):
"""
Explicitly get a registered global action whether it's enabled or
not. Raises KeyError for invalid names.
"""
return self._global_actions[name]
@property
def actions(self):
"""
Get all the enabled actions as an iterable of (name, func).
"""
return six.iteritems(self._actions)
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
return request.user.is_active and request.user.is_staff
def check_dependencies(self):
"""
Check that all things needed to run the admin have been correctly installed.
The default implementation checks that LogEntry, ContentType and the
auth context processor are installed.
"""
from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.models import ContentType
if not LogEntry._meta.installed:
raise ImproperlyConfigured("Put 'django.contrib.admin' in your "
"INSTALLED_APPS setting in order to use the admin application.")
if not ContentType._meta.installed:
raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in "
"your INSTALLED_APPS setting in order to use the admin application.")
if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or
'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS):
raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' "
"in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application.")
def admin_view(self, view, cacheable=False):
"""
Decorator to create an admin view attached to this ``AdminSite``. This
wraps the view and provides permission checking by calling
``self.has_permission``.
You'll want to use this from within ``AdminSite.get_urls()``:
class MyAdminSite(AdminSite):
def get_urls(self):
from django.conf.urls import patterns, url
urls = super(MyAdminSite, self).get_urls()
urls += patterns('',
url(r'^my_view/$', self.admin_view(some_view))
)
return urls
By default, admin_views are marked non-cacheable using the
``never_cache`` decorator. If the view can be safely cached, set
cacheable=True.
"""
def inner(request, *args, **kwargs):
if LOGIN_FORM_KEY in request.POST and request.user.is_authenticated():
auth_logout(request)
if not self.has_permission(request):
if request.path == reverse('admin:logout',
current_app=self.name):
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
return self.login(request)
return view(request, *args, **kwargs)
if not cacheable:
inner = never_cache(inner)
# We add csrf_protect here so this function can be used as a utility
# function for any view, without having to repeat 'csrf_protect'.
if not getattr(view, 'csrf_exempt', False):
inner = csrf_protect(inner)
return update_wrapper(inner, view)
def get_urls(self):
from django.conf.urls import patterns, url, include
if settings.DEBUG:
self.check_dependencies()
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
return self.admin_view(view, cacheable)(*args, **kwargs)
return update_wrapper(wrapper, view)
# Admin-site-wide views.
urlpatterns = patterns('',
url(r'^$',
wrap(self.index),
name='index'),
url(r'^logout/$',
wrap(self.logout),
name='logout'),
url(r'^password_change/$',
wrap(self.password_change, cacheable=True),
name='password_change'),
url(r'^password_change/done/$',
wrap(self.password_change_done, cacheable=True),
name='password_change_done'),
url(r'^jsi18n/$',
wrap(self.i18n_javascript, cacheable=True),
name='jsi18n'),
url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$',
wrap(contenttype_views.shortcut),
name='view_on_site'),
url(r'^(?P<app_label>\w+)/$',
wrap(self.app_index),
name='app_list')
)
# Add in each model's views.
for model, model_admin in six.iteritems(self._registry):
urlpatterns += patterns('',
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name),
include(model_admin.urls))
)
return urlpatterns
@property
def urls(self):
return self.get_urls(), self.app_name, self.name
def password_change(self, request):
"""
Handles the "change password" task -- both form display and validation.
"""
from django.contrib.auth.views import password_change
url = reverse('admin:password_change_done', current_app=self.name)
defaults = {
'current_app': self.name,
'post_change_redirect': url
}
if self.password_change_template is not None:
defaults['template_name'] = self.password_change_template
return password_change(request, **defaults)
def password_change_done(self, request, extra_context=None):
"""
Displays the "success" page after a password change.
"""
from django.contrib.auth.views import password_change_done
defaults = {
'current_app': self.name,
'extra_context': extra_context or {},
}
if self.password_change_done_template is not None:
defaults['template_name'] = self.password_change_done_template
return password_change_done(request, **defaults)
def i18n_javascript(self, request):
"""
Displays the i18n JavaScript that the Django admin requires.
This takes into account the USE_I18N setting. If it's set to False, the
generated JavaScript will be leaner and faster.
"""
if settings.USE_I18N:
from django.views.i18n import javascript_catalog
else:
from django.views.i18n import null_javascript_catalog as javascript_catalog
return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
@never_cache
def logout(self, request, extra_context=None):
"""
Logs out the user for the given HttpRequest.
This should *not* assume the user is already logged in.
"""
from django.contrib.auth.views import logout
defaults = {
'current_app': self.name,
'extra_context': extra_context or {},
}
if self.logout_template is not None:
defaults['template_name'] = self.logout_template
return logout(request, **defaults)
@never_cache
def login(self, request, extra_context=None):
"""
Displays the login form for the given HttpRequest.
"""
from django.contrib.auth.views import login
context = {
'title': _('Log in'),
'app_path': request.get_full_path(),
REDIRECT_FIELD_NAME: request.get_full_path(),
}
context.update(extra_context or {})
defaults = {
'extra_context': context,
'current_app': self.name,
'authentication_form': self.login_form or AdminAuthenticationForm,
'template_name': self.login_template or 'admin/login.html',
}
return login(request, **defaults)
@never_cache
def index(self, request, extra_context=None):
"""
Displays the main admin index page, which lists all of the installed
apps that have been registered in this site.
"""
app_dict = {}
user = request.user
for model, model_admin in self._registry.items():
app_label = model._meta.app_label
has_module_perms = user.has_module_perms(app_label)
if has_module_perms:
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True in perms.values():
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change', False):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add', False):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': app_label.title(),
'app_label': app_label,
'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
# Sort the apps alphabetically.
app_list = list(six.itervalues(app_dict))
app_list.sort(key=lambda x: x['name'])
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
context = {
'title': _('Site administration'),
'app_list': app_list,
}
context.update(extra_context or {})
return TemplateResponse(request,self.index_template or
'admin/index.html', context,
current_app=self.name)
def app_index(self, request, app_label, extra_context=None):
user = request.user
has_module_perms = user.has_module_perms(app_label)
app_dict = {}
for model, model_admin in self._registry.items():
if app_label == model._meta.app_label:
if has_module_perms:
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True in perms.values():
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change', False):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)
except NoReverseMatch:
pass
if perms.get('add', False):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)
except NoReverseMatch:
pass
if app_dict:
app_dict['models'].append(model_dict),
else:
# First time around, now that we know there's
# something to display, add in the necessary meta
# information.
app_dict = {
'name': app_label.title(),
'app_label': app_label,
'app_url': '',
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if not app_dict:
raise Http404('The requested admin page does not exist.')
# Sort the models alphabetically within each app.
app_dict['models'].sort(key=lambda x: x['name'])
context = {
'title': _('%s administration') % capfirst(app_label),
'app_list': [app_dict],
}
context.update(extra_context or {})
return TemplateResponse(request, self.app_index_template or [
'admin/%s/app_index.html' % app_label,
'admin/app_index.html'
], context, current_app=self.name)
# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site.
site = AdminSite()
|
edisonlz/fruit
|
web_project/base/site-packages/django/contrib/admin/sites.py
|
Python
|
apache-2.0
| 18,705
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.oozie.command.bundle;
import java.io.IOException;
import java.io.StringReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.hadoop.conf.Configuration;
import org.apache.oozie.BundleActionBean;
import org.apache.oozie.BundleJobBean;
import org.apache.oozie.ErrorCode;
import org.apache.oozie.XException;
import org.apache.oozie.action.hadoop.OozieJobInfo;
import org.apache.oozie.client.Job;
import org.apache.oozie.client.OozieClient;
import org.apache.oozie.client.rest.JsonBean;
import org.apache.oozie.command.CommandException;
import org.apache.oozie.command.PreconditionException;
import org.apache.oozie.command.StartTransitionXCommand;
import org.apache.oozie.executor.jpa.BatchQueryExecutor;
import org.apache.oozie.executor.jpa.BundleJobQueryExecutor;
import org.apache.oozie.executor.jpa.BundleJobQueryExecutor.BundleJobQuery;
import org.apache.oozie.executor.jpa.JPAExecutorException;
import org.apache.oozie.executor.jpa.BatchQueryExecutor.UpdateEntry;
import org.apache.oozie.util.ELUtils;
import org.apache.oozie.util.JobUtils;
import org.apache.oozie.util.LogUtils;
import org.apache.oozie.util.ParamChecker;
import org.apache.oozie.util.XConfiguration;
import org.apache.oozie.util.XmlUtils;
import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.JDOMException;
/**
* The command to start Bundle job
*/
public class BundleStartXCommand extends StartTransitionXCommand {
private final String jobId;
private BundleJobBean bundleJob;
/**
* The constructor for class {@link BundleStartXCommand}
*
* @param jobId the bundle job id
*/
public BundleStartXCommand(String jobId) {
super("bundle_start", "bundle_start", 1);
this.jobId = ParamChecker.notEmpty(jobId, "jobId");
}
/**
* The constructor for class {@link BundleStartXCommand}
*
* @param jobId the bundle job id
* @param dryrun true if dryrun is enable
*/
public BundleStartXCommand(String jobId, boolean dryrun) {
super("bundle_start", "bundle_start", 1, dryrun);
this.jobId = ParamChecker.notEmpty(jobId, "jobId");
}
/* (non-Javadoc)
* @see org.apache.oozie.command.XCommand#getEntityKey()
*/
@Override
public String getEntityKey() {
return jobId;
}
@Override
public String getKey() {
return getName() + "_" + jobId;
}
/* (non-Javadoc)
* @see org.apache.oozie.command.XCommand#isLockRequired()
*/
@Override
protected boolean isLockRequired() {
return true;
}
@Override
protected void verifyPrecondition() throws CommandException, PreconditionException {
if (bundleJob.getStatus() != Job.Status.PREP) {
String msg = "Bundle " + bundleJob.getId() + " is not in PREP status. It is in : " + bundleJob.getStatus();
LOG.info(msg);
throw new PreconditionException(ErrorCode.E1100, msg);
}
}
@Override
public void loadState() throws CommandException {
try {
this.bundleJob = BundleJobQueryExecutor.getInstance().get(BundleJobQuery.GET_BUNDLE_JOB, jobId);
LogUtils.setLogInfo(bundleJob);
super.setJob(bundleJob);
}
catch (XException ex) {
throw new CommandException(ex);
}
}
/* (non-Javadoc)
* @see org.apache.oozie.command.StartTransitionXCommand#StartChildren()
*/
@Override
public void StartChildren() throws CommandException {
LOG.debug("Started coord jobs for the bundle=[{0}]", jobId);
insertBundleActions();
startCoordJobs();
LOG.debug("Ended coord jobs for the bundle=[{0}]", jobId);
}
/* (non-Javadoc)
* @see org.apache.oozie.command.TransitionXCommand#notifyParent()
*/
@Override
public void notifyParent() {
}
/* (non-Javadoc)
* @see org.apache.oozie.command.StartTransitionXCommand#performWrites()
*/
@Override
public void performWrites() throws CommandException {
try {
BatchQueryExecutor.getInstance().executeBatchInsertUpdateDelete(insertList, updateList, null);
}
catch (JPAExecutorException e) {
throw new CommandException(e);
}
}
/**
* Insert bundle actions
*
* @throws CommandException thrown if failed to create bundle actions
*/
@SuppressWarnings("unchecked")
private void insertBundleActions() throws CommandException {
if (bundleJob != null) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
try {
Element bAppXml = XmlUtils.parseXml(bundleJob.getJobXml());
List<Element> coordElems = bAppXml.getChildren("coordinator", bAppXml.getNamespace());
for (Element elem : coordElems) {
Attribute name = elem.getAttribute("name");
Attribute critical = elem.getAttribute("critical");
if (name != null) {
if (map.containsKey(name.getValue())) {
throw new CommandException(ErrorCode.E1304, name);
}
Configuration coordConf = mergeConfig(elem);
// skip coord job if it is not enabled
if (!isEnabled(elem, coordConf)) {
continue;
}
boolean isCritical = false;
if (critical != null && Boolean.parseBoolean(critical.getValue())) {
isCritical = true;
}
map.put(name.getValue(), isCritical);
}
else {
throw new CommandException(ErrorCode.E1305);
}
}
}
catch (JDOMException jex) {
throw new CommandException(ErrorCode.E1301, jex.getMessage(), jex);
}
// if there is no coordinator for this bundle, failed it.
if (map.isEmpty()) {
bundleJob.setStatus(Job.Status.FAILED);
bundleJob.resetPending();
try {
BundleJobQueryExecutor.getInstance().executeUpdate(BundleJobQuery.UPDATE_BUNDLE_JOB_STATUS_PENDING, bundleJob);
}
catch (JPAExecutorException jex) {
throw new CommandException(jex);
}
LOG.debug("No coord jobs for the bundle=[{0}], failed it!!", jobId);
throw new CommandException(ErrorCode.E1318, jobId);
}
for (Entry<String, Boolean> coordName : map.entrySet()) {
BundleActionBean action = createBundleAction(jobId, coordName.getKey(), coordName.getValue());
insertList.add(action);
}
}
else {
throw new CommandException(ErrorCode.E0604, jobId);
}
}
private BundleActionBean createBundleAction(String jobId, String coordName, boolean isCritical) {
BundleActionBean action = new BundleActionBean();
action.setBundleActionId(jobId + "_" + coordName);
action.setBundleId(jobId);
action.setCoordName(coordName);
action.setStatus(Job.Status.PREP);
action.setLastModifiedTime(new Date());
if (isCritical) {
action.setCritical();
}
else {
action.resetCritical();
}
return action;
}
/**
* Start Coord Jobs
*
* @throws CommandException thrown if failed to start coord jobs
*/
@SuppressWarnings("unchecked")
private void startCoordJobs() throws CommandException {
if (bundleJob != null) {
try {
Element bAppXml = XmlUtils.parseXml(bundleJob.getJobXml());
List<Element> coordElems = bAppXml.getChildren("coordinator", bAppXml.getNamespace());
for (Element coordElem : coordElems) {
Attribute name = coordElem.getAttribute("name");
Configuration coordConf = mergeConfig(coordElem);
coordConf.set(OozieClient.BUNDLE_ID, jobId);
if (OozieJobInfo.isJobInfoEnabled()) {
coordConf.set(OozieJobInfo.BUNDLE_NAME, bundleJob.getAppName());
}
// skip coord job if it is not enabled
if (!isEnabled(coordElem, coordConf)) {
continue;
}
String coordName=name.getValue();
try {
coordName = ELUtils.resolveAppName(coordName, coordConf);
}
catch (Exception e) {
throw new CommandException(ErrorCode.E1321, e.getMessage(), e);
}
queue(new BundleCoordSubmitXCommand(coordConf, bundleJob.getId(), name.getValue()));
}
updateBundleAction();
}
catch (JDOMException jex) {
throw new CommandException(ErrorCode.E1301, jex.getMessage(), jex);
}
catch (JPAExecutorException je) {
throw new CommandException(je);
}
}
else {
throw new CommandException(ErrorCode.E0604, jobId);
}
}
private void updateBundleAction() throws JPAExecutorException {
for(JsonBean bAction : insertList) {
BundleActionBean action = (BundleActionBean) bAction;
action.incrementAndGetPending();
action.setLastModifiedTime(new Date());
}
}
/**
* Merge Bundle job config and the configuration from the coord job to pass
* to Coord Engine
*
* @param coordElem the coordinator configuration
* @return Configuration merged configuration
* @throws CommandException thrown if failed to merge configuration
*/
private Configuration mergeConfig(Element coordElem) throws CommandException {
String jobConf = bundleJob.getConf();
// Step 1: runConf = jobConf
Configuration runConf = null;
try {
runConf = new XConfiguration(new StringReader(jobConf));
}
catch (IOException e1) {
LOG.warn("Configuration parse error in:" + jobConf);
throw new CommandException(ErrorCode.E1306, e1.getMessage(), e1);
}
// Step 2: Merge local properties into runConf
// extract 'property' tags under 'configuration' block in the coordElem
// convert Element to XConfiguration
Element localConfigElement = coordElem.getChild("configuration", coordElem.getNamespace());
if (localConfigElement != null) {
String strConfig = XmlUtils.prettyPrint(localConfigElement).toString();
Configuration localConf;
try {
localConf = new XConfiguration(new StringReader(strConfig));
}
catch (IOException e1) {
LOG.warn("Configuration parse error in:" + strConfig);
throw new CommandException(ErrorCode.E1307, e1.getMessage(), e1);
}
// copy configuration properties in the coordElem to the runConf
XConfiguration.copy(localConf, runConf);
}
// Step 3: Extract value of 'app-path' in coordElem, save it as a
// new property called 'oozie.coord.application.path', and normalize.
String appPath = coordElem.getChild("app-path", coordElem.getNamespace()).getValue();
runConf.set(OozieClient.COORDINATOR_APP_PATH, appPath);
// Normalize coordinator appPath here;
try {
JobUtils.normalizeAppPath(runConf.get(OozieClient.USER_NAME), runConf.get(OozieClient.GROUP_NAME), runConf);
}
catch (IOException e) {
throw new CommandException(ErrorCode.E1001, runConf.get(OozieClient.COORDINATOR_APP_PATH));
}
return runConf;
}
/* (non-Javadoc)
* @see org.apache.oozie.command.TransitionXCommand#getJob()
*/
@Override
public Job getJob() {
return bundleJob;
}
/* (non-Javadoc)
* @see org.apache.oozie.command.TransitionXCommand#updateJob()
*/
@Override
public void updateJob() throws CommandException {
updateList.add(new UpdateEntry<BundleJobQuery>(BundleJobQuery.UPDATE_BUNDLE_JOB_STATUS_PENDING, bundleJob));
}
/**
* Checks whether the coordinator is enabled
*
* @param coordElem
* @param coordConf
* @return true if coordinator is enabled, otherwise false.
* @throws CommandException
*/
private boolean isEnabled(Element coordElem, Configuration coordConf) throws CommandException {
Attribute enabled = coordElem.getAttribute("enabled");
if (enabled == null) {
// default is true
return true;
}
String isEnabled = enabled.getValue();
try {
isEnabled = ELUtils.resolveAppName(isEnabled, coordConf);
}
catch (Exception e) {
throw new CommandException(ErrorCode.E1321, e.getMessage(), e);
}
return Boolean.parseBoolean(isEnabled);
}
}
|
cbaenziger/oozie
|
core/src/main/java/org/apache/oozie/command/bundle/BundleStartXCommand.java
|
Java
|
apache-2.0
| 14,311
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ThemeItem.cs" company="--">
// Copyright © -- 2010. All Rights Reserved.
// </copyright>
// <summary>
// ThemeItem encapsulates the items of Theme list.
// Uses IComparable interface to allow sorting by name.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Appleseed.Framework.Design
{
using System;
/// <summary>
/// ThemeItem encapsulates the items of Theme list.
/// Uses IComparable interface to allow sorting by name.
/// </summary>
public class ThemeItem : IComparable, ICloneable
{
#region Properties
/// <summary>
/// Gets or sets the name of the theme.
/// </summary>
/// <value>The name of the theme.</value>
public string Name { get; set; }
#endregion
#region Implemented Interfaces
#region IComparable
/// <summary>
/// Compares to.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// An integer value...
/// </returns>
public int CompareTo(object value)
{
return this.CompareTo(this.Name);
}
#endregion
#endregion
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
/// <filterpriority>2</filterpriority>
public object Clone()
{
return new ThemeItem { Name = this.Name };
}
}
}
|
Appleseed/portal
|
Master/Appleseed/Projects/Appleseed.Framework.Core/Design/ThemeItem.cs
|
C#
|
apache-2.0
| 1,821
|
/**
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export default ['src1', 'src2'].map(src => ({
input: src + '/index.js',
output: {
entryFileNames: '[name]-[hash].js',
dir: 'build/' + src,
format: 'esm',
},
}));
|
GoogleChromeLabs/tooling.report
|
tests/hashing/subtests/hash-ignores-parent-dirs/rollup/rollup.config.js
|
JavaScript
|
apache-2.0
| 788
|
# Ramaria linearioides R.H. Petersen & M. Zang, 1989 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Acta bot. Yunn. 11(4): 385 (1989)
#### Original name
Ramaria linearioides R.H. Petersen & M. Zang, 1989
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Gomphales/Gomphaceae/Ramaria/Ramaria linearioides/README.md
|
Markdown
|
apache-2.0
| 283
|
# Copyright 2016 Rackspace Australia
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import
import fixtures
import jsonschema
import os
import requests
from oslo_serialization import jsonutils
from oslo_utils import uuidutils
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional import fixtures as func_fixtures
from nova.tests.functional import integrated_helpers
from nova.tests.unit.image import fake as fake_image
class fake_result(object):
def __init__(self, result):
self.status_code = 200
self.text = jsonutils.dumps(result)
real_request = requests.request
def fake_request(obj, url, method, **kwargs):
if url.startswith('http://127.0.0.1:123'):
return fake_result({'a': 1, 'b': 'foo'})
if url.startswith('http://127.0.0.1:124'):
return fake_result({'c': 3})
if url.startswith('http://127.0.0.1:125'):
return fake_result(jsonutils.loads(kwargs.get('data', '{}')))
return real_request(method, url, **kwargs)
class MetadataTest(test.TestCase, integrated_helpers.InstanceHelperMixin):
def setUp(self):
super(MetadataTest, self).setUp()
fake_image.stub_out_image_service(self)
self.addCleanup(fake_image.FakeImageService_reset)
self.useFixture(nova_fixtures.NeutronFixture(self))
self.useFixture(func_fixtures.PlacementFixture())
self.start_service('conductor')
self.start_service('scheduler')
self.api = self.useFixture(
nova_fixtures.OSAPIFixture(api_version='v2.1')).api
self.start_service('compute')
# create a server for the tests
server = self._build_server(name='test')
server = self.api.post_server({'server': server})
self.server = self._wait_for_state_change(server, 'ACTIVE')
self.api_fixture = self.useFixture(nova_fixtures.OSMetadataServer())
self.md_url = self.api_fixture.md_url
# make sure that the metadata service returns information about the
# server we created above
def fake_get_fixed_ip_by_address(self, ctxt, address):
return {'instance_uuid': server['id']}
self.useFixture(
fixtures.MonkeyPatch(
'nova.network.neutron.API.get_fixed_ip_by_address',
fake_get_fixed_ip_by_address))
def test_lookup_metadata_root_url(self):
res = requests.request('GET', self.md_url, timeout=5)
self.assertEqual(200, res.status_code)
def test_lookup_metadata_openstack_url(self):
url = '%sopenstack' % self.md_url
res = requests.request('GET', url, timeout=5,
headers={'X-Forwarded-For': '127.0.0.2'})
self.assertEqual(200, res.status_code)
def test_lookup_metadata_data_url(self):
url = '%sopenstack/latest/meta_data.json' % self.md_url
res = requests.request('GET', url, timeout=5)
self.assertEqual(200, res.status_code)
j = jsonutils.loads(res.text)
self.assertIn('hostname', j)
self.assertEqual('test.novalocal', j['hostname'])
def test_lookup_external_service(self):
self.flags(
vendordata_providers=['StaticJSON', 'DynamicJSON'],
vendordata_dynamic_targets=[
'testing@http://127.0.0.1:123',
'hamster@http://127.0.0.1:123'
],
group='api'
)
self.useFixture(fixtures.MonkeyPatch(
'keystoneauth1.session.Session.request', fake_request))
url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url
res = requests.request('GET', url, timeout=5)
self.assertEqual(200, res.status_code)
j = jsonutils.loads(res.text)
self.assertEqual({}, j['static'])
self.assertEqual(1, j['testing']['a'])
self.assertEqual('foo', j['testing']['b'])
self.assertEqual(1, j['hamster']['a'])
self.assertEqual('foo', j['hamster']['b'])
def test_lookup_external_service_no_overwrite(self):
self.flags(
vendordata_providers=['DynamicJSON'],
vendordata_dynamic_targets=[
'testing@http://127.0.0.1:123',
'testing@http://127.0.0.1:124'
],
group='api'
)
self.useFixture(fixtures.MonkeyPatch(
'keystoneauth1.session.Session.request', fake_request))
url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url
res = requests.request('GET', url, timeout=5)
self.assertEqual(200, res.status_code)
j = jsonutils.loads(res.text)
self.assertNotIn('static', j)
self.assertEqual(1, j['testing']['a'])
self.assertEqual('foo', j['testing']['b'])
self.assertNotIn('c', j['testing'])
def test_lookup_external_service_passes_data(self):
# Much of the data we pass to the REST service is missing because of
# the way we've created the fake instance, but we should at least try
# and ensure we're passing _some_ data through to the external REST
# service.
self.flags(
vendordata_providers=['DynamicJSON'],
vendordata_dynamic_targets=[
'testing@http://127.0.0.1:125'
],
group='api'
)
self.useFixture(fixtures.MonkeyPatch(
'keystoneauth1.session.Session.request', fake_request))
url = '%sopenstack/2016-10-06/vendor_data2.json' % self.md_url
res = requests.request('GET', url, timeout=5)
self.assertEqual(200, res.status_code)
j = jsonutils.loads(res.text)
self.assertIn('instance-id', j['testing'])
self.assertTrue(uuidutils.is_uuid_like(j['testing']['instance-id']))
self.assertIn('hostname', j['testing'])
self.assertEqual(self.server['tenant_id'], j['testing']['project-id'])
self.assertIn('metadata', j['testing'])
self.assertIn('image-id', j['testing'])
self.assertIn('user-data', j['testing'])
def test_network_data_matches_schema(self):
self.useFixture(fixtures.MonkeyPatch(
'keystoneauth1.session.Session.request', fake_request))
url = '%sopenstack/latest/network_data.json' % self.md_url
res = requests.request('GET', url, timeout=5)
self.assertEqual(200, res.status_code)
# load the jsonschema for network_data
schema_file = os.path.normpath(os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"../../../doc/api_schemas/network_data.json"))
with open(schema_file, 'rb') as f:
schema = jsonutils.load(f)
jsonschema.validate(res.json(), schema)
|
rahulunair/nova
|
nova/tests/functional/test_metadata.py
|
Python
|
apache-2.0
| 7,360
|
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia at 2014-09-28
| Rendered using Apache Maven Fluido Skin 1.3.1
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20140928" />
<meta http-equiv="Content-Language" content="en" />
<title>SBT Runner Maven Plugin – Plugin Documentation</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.3.1.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.3.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="./css/site.css"/>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left">
<div id="bannerLeft">
<h2>SBT Runner Maven Plugin</h2>
</div>
</div>
<div class="pull-right"> </div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2014-09-28
<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 1.0.0-beta1
</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Parent Project</li>
<li>
<a href="../index.html" title="SBT Runner">
<i class="none"></i>
SBT Runner</a>
</li>
<li class="nav-header">Overview</li>
<li>
<a href="index.html" title="Introduction">
<i class="none"></i>
Introduction</a>
</li>
<li class="active">
<a href="#"><i class="none"></i>Goals</a>
</li>
<li>
<a href="apidocs/index.html" title="JavaDocs">
<i class="none"></i>
JavaDocs</a>
</li>
<li class="nav-header">Project Documentation</li>
<li>
<a href="project-info.html" title="Project Information">
<i class="icon-chevron-right"></i>
Project Information</a>
</li>
<li>
<a href="project-reports.html" title="Project Reports">
<i class="icon-chevron-down"></i>
Project Reports</a>
<ul class="nav nav-list">
<li>
<a href="apidocs/index.html" title="JavaDocs">
<i class="none"></i>
JavaDocs</a>
</li>
<li>
<a href="xref/index.html" title="Source Xref">
<i class="none"></i>
Source Xref</a>
</li>
<li class="active">
<a href="#"><i class="none"></i>Plugin Documentation</a>
</li>
</ul>
</li>
</ul>
<hr />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" />
</a>
</div>
</div>
</div>
<div id="bodyColumn" class="span9" >
<div class="section">
<h2><a name="Plugin_Documentation"></a>Plugin Documentation</h2><a name="Plugin_Documentation"></a>
<p>Goals available for this plugin:</p>
<table border="0" class="table table-striped">
<tr class="a">
<th>Goal</th>
<th>Description</th></tr>
<tr class="b">
<td><a href="help-mojo.html">sbtrun:help</a></td>
<td>Display help information on sbtrun-maven-plugin.<br />
Call <code>mvn sbtrun:help -Ddetail=true
-Dgoal=<goal-name></code> to display parameter details.</td></tr>
<tr class="a">
<td><a href="run-mojo.html">sbtrun:run</a></td>
<td>Run SBT</td></tr></table>
<div class="section">
<h3><a name="System_Requirements"></a>System Requirements</h3><a name="System_Requirements"></a>
<p>The following specifies the minimum requirements to run this Maven plugin:</p>
<table border="0" class="table table-striped">
<tr class="a">
<td>Maven</td>
<td>2.2.1</td></tr>
<tr class="b">
<td>JDK</td>
<td>1.6</td></tr>
<tr class="a">
<td>Memory</td>
<td>No minimum requirement.</td></tr>
<tr class="b">
<td>Disk Space</td>
<td>No minimum requirement.</td></tr></table></div>
<div class="section">
<h3><a name="Usage"></a>Usage</h3><a name="Usage"></a>
<p>You should specify the version in your project's plugin configuration:</p>
<div class="source">
<pre><project>
...
<build>
<!-- To define the plugin version in your parent POM -->
<pluginManagement>
<plugins>
<plugin>
<groupId>com.google.code.sbtrun-maven-plugin</groupId>
<artifactId>sbtrun-maven-plugin</artifactId>
<version>1.0.0-beta1</version>
</plugin>
...
</plugins>
</pluginManagement>
<!-- To use the plugin goals in your POM or parent POM -->
<plugins>
<plugin>
<groupId>com.google.code.sbtrun-maven-plugin</groupId>
<artifactId>sbtrun-maven-plugin</artifactId>
<version>1.0.0-beta1</version>
</plugin>
...
</plugins>
</build>
...
</project>
</pre></div>
<p>For more information, see <a class="externalLink" href="http://maven.apache.org/guides/mini/guide-configuring-plugins.html">"Guide to Configuring Plug-ins"</a></p></div></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<p >Copyright © 2014.
All rights reserved.
</p>
</div>
</div>
</footer>
</body>
</html>
|
sbtrun-maven-plugin/sbtrun-maven-plugin.github.io
|
sbtrun-maven-plugin/1.0.0-beta1/sbtrun-maven-plugin/plugin-info.html
|
HTML
|
apache-2.0
| 7,733
|
local fs = {}
-- see if the file exists
function fs.exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
function fs.read(path)
local file = io.open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
end
return fs
|
witheve/lueve
|
src/fs.lua
|
Lua
|
apache-2.0
| 397
|
# Pocillaria sajor-caju (Fr.) Kuntze, 1891 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Revis. gen. pl. (Leipzig) 2: 866 (1891)
#### Original name
Agaricus sajor-caju Fr., 1821
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Lentinus/Lentinus sajor-caju/ Syn. Pocillaria sajor-caju/README.md
|
Markdown
|
apache-2.0
| 257
|
package com.c4soft.hadoop;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import com.c4soft.util.CsvRecord;
import com.c4soft.util.hadoop.PostcodeUtil;
/**
* @author Ch4mp
*
*/
public class CsvFieldCountMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
private static final LongWritable ONE = new LongWritable(1L);
public static final String CSV_FIELD_IDX = "com.c4soft.hadoop.CsvFieldCountMapper.idx";
public static final String FILTER_CACHE_FILE_NAME = "com.c4soft.hadoop.CsvFieldCountMapper.filter.cache";
private static final Text URBAN = new Text("urban");
private static final Text RURAL = new Text("rural");
private Integer idx = null;
private Collection<Pattern> patterns;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
String filterCacheFileName = conf.get(FILTER_CACHE_FILE_NAME);
URI[] cachedFilesUris = context.getCacheFiles();
for (URI cachedFile : cachedFilesUris) {
String cachedFileStr = cachedFile.toString();
if (cachedFileStr.contains(filterCacheFileName)) {
FileSystem fs = FileSystem.get(cachedFile, conf);
patterns = PostcodeUtil.cacheMatchers(fs, new Path(cachedFile), "FR");
break;
}
}
super.setup(context);
}
@Override
protected void map(LongWritable kIn, Text vIn, Context context) throws IOException, InterruptedException {
if (idx == null) {
idx = context.getConfiguration().getInt(CSV_FIELD_IDX, 0);
}
String line = vIn.toString();
CsvRecord record = new CsvRecord(line);
String postCode = record.get(idx);
if (PostcodeUtil.matches(postCode, patterns)) {
context.write(URBAN, ONE);
} else {
context.write(RURAL, ONE);
}
}
}
|
ch4mpy/hadoop2
|
labs/complete/lab3-jobconf-cache-etc-complete/src/main/java/com/c4soft/hadoop/CsvFieldCountMapper.java
|
Java
|
apache-2.0
| 2,262
|
package com.sun.corba.se.spi.activation;
/**
* com/sun/corba/se/spi/activation/ServerManagerOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u72/5732/corba/src/share/classes/com/sun/corba/se/spi/activation/activation.idl
* Tuesday, December 22, 2015 7:17:37 PM PST
*/
public interface ServerManagerOperations extends com.sun.corba.se.spi.activation.ActivatorOperations, com.sun.corba.se.spi.activation.LocatorOperations
{
} // interface ServerManagerOperations
|
itgeeker/jdk
|
src/com/sun/corba/se/spi/activation/ServerManagerOperations.java
|
Java
|
apache-2.0
| 558
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>numpy.digitize — NumPy v1.8 Manual</title>
<link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../',
VERSION: '1.8.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: false
};
</script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/underscore.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<link rel="author" title="About these documents" href="../../about.html" />
<link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
<link rel="up" title="Statistics" href="../routines.statistics.html" />
<link rel="next" title="Test Support (numpy.testing)" href="../routines.testing.html" />
<link rel="prev" title="numpy.bincount" href="numpy.bincount.html" />
<link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
<meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">
<script type="text/javascript">
var getTextForSample = function(i) {
codeBlock = document.getElementsByClassName('highlight-python')[i];
return codeBlock.innerText;
}
var copySample = function (i) {
window.location.href = '/__pythonista_copy__/' + encodeURI(getTextForSample(i));
}
var openSample = function (i) {
window.location.href = '/__pythonista_open__/' + encodeURI(getTextForSample(i));
}
//Source: http://ejohn.org/blog/partial-functions-in-javascript/
Function.prototype.partial = function() {
var fn = this,
args = Array.prototype.slice.call(arguments);
return function() {
var arg = 0;
for (var i = 0; i < args.length && arg < arguments.length; i++)
if (args[i] === undefined) args[i] = arguments[arg++];
return fn.apply(this, args);
};
};
window.onload=function() {
//Add "Copy" and "Open in Editor" buttons for code samples:
var inApp = navigator.userAgent.match(/AppleWebKit/i) != null && navigator.userAgent.match(/Safari/i) == null;
if (inApp) {
codeBlocks = document.getElementsByClassName('highlight-python');
for (var i = 0; i < codeBlocks.length; i++) {
codeBlock = codeBlocks[i];
if (codeBlock.innerText.indexOf('>>>') == 0) {
//Don't add header for interactive sessions
continue;
}
var codeHeader = document.createElement('div');
codeHeader.className = 'pythonista-code-header';
var copyButton = document.createElement('button');
copyButton.className = 'pythonista-button';
copyButton.innerText = 'Copy';
copyButton.addEventListener('click', copySample.partial(i));
codeHeader.appendChild(copyButton);
var openButton = document.createElement('button');
openButton.className = 'pythonista-button';
openButton.innerText = 'Open in Editor';
openButton.addEventListener('click', openSample.partial(i));
codeHeader.appendChild(openButton);
codeBlock.parentElement.insertBefore(codeHeader, codeBlock);
}
}
}
</script>
</head>
<body ontouchstart="">
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../routines.testing.html" title="Test Support (numpy.testing)"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="numpy.bincount.html" title="numpy.bincount"
accesskey="P">previous</a> |</li>
<li><a href="../../index.html">NumPy v1.8 Manual</a> »</li>
<li><a href="../index.html" >NumPy Reference</a> »</li>
<li><a href="../routines.html" >Routines</a> »</li>
<li><a href="../routines.statistics.html" accesskey="U">Statistics</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="body">
<div class="section" id="numpy-digitize">
<h1>numpy.digitize<a class="headerlink" href="#numpy-digitize" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="numpy.digitize">
<tt class="descclassname">numpy.</tt><tt class="descname">digitize</tt><big>(</big><em>x</em>, <em>bins</em>, <em>right=False</em><big>)</big><a class="headerlink" href="#numpy.digitize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the indices of the bins to which each value in input array belongs.</p>
<p>Each index <tt class="docutils literal"><span class="pre">i</span></tt> returned is such that <tt class="docutils literal"><span class="pre">bins[i-1]</span> <span class="pre"><=</span> <span class="pre">x</span> <span class="pre"><</span> <span class="pre">bins[i]</span></tt> if
<em class="xref py py-obj">bins</em> is monotonically increasing, or <tt class="docutils literal"><span class="pre">bins[i-1]</span> <span class="pre">></span> <span class="pre">x</span> <span class="pre">>=</span> <span class="pre">bins[i]</span></tt> if
<em class="xref py py-obj">bins</em> is monotonically decreasing. If values in <em class="xref py py-obj">x</em> are beyond the
bounds of <em class="xref py py-obj">bins</em>, 0 or <tt class="docutils literal"><span class="pre">len(bins)</span></tt> is returned as appropriate. If right
is True, then the right bin is closed so that the index <tt class="docutils literal"><span class="pre">i</span></tt> is such
that <tt class="docutils literal"><span class="pre">bins[i-1]</span> <span class="pre"><</span> <span class="pre">x</span> <span class="pre"><=</span> <span class="pre">bins[i]</span></tt> or bins[i-1] >= x > bins[i]`` if <em class="xref py py-obj">bins</em>
is monotonically increasing or decreasing, respectively.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>x</strong> : array_like</p>
<blockquote>
<div><p>Input array to be binned. It has to be 1-dimensional.</p>
</div></blockquote>
<p><strong>bins</strong> : array_like</p>
<blockquote>
<div><p>Array of bins. It has to be 1-dimensional and monotonic.</p>
</div></blockquote>
<p><strong>right</strong> : bool, optional</p>
<blockquote>
<div><p>Indicating whether the intervals include the right or the left bin
edge. Default behavior is (right==False) indicating that the interval
does not include the right edge. The left bin and is open in this
case. Ie., bins[i-1] <= x < bins[i] is the default behavior for
monotonically increasing bins.</p>
</div></blockquote>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>out</strong> : ndarray of ints</p>
<blockquote>
<div><p>Output array of indices, of same shape as <em class="xref py py-obj">x</em>.</p>
</div></blockquote>
</td>
</tr>
<tr class="field-odd field"><th class="field-name">Raises:</th><td class="field-body"><p class="first"><strong>ValueError</strong> :</p>
<blockquote>
<div><p>If the input is not 1-dimensional, or if <em class="xref py py-obj">bins</em> is not monotonic.</p>
</div></blockquote>
<p><strong>TypeError</strong> :</p>
<blockquote class="last">
<div><p>If the type of the input is complex.</p>
</div></blockquote>
</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="numpy.bincount.html#numpy.bincount" title="numpy.bincount"><tt class="xref py py-obj docutils literal"><span class="pre">bincount</span></tt></a>, <a class="reference internal" href="numpy.histogram.html#numpy.histogram" title="numpy.histogram"><tt class="xref py py-obj docutils literal"><span class="pre">histogram</span></tt></a>, <a class="reference internal" href="numpy.unique.html#numpy.unique" title="numpy.unique"><tt class="xref py py-obj docutils literal"><span class="pre">unique</span></tt></a></p>
</div>
<p class="rubric">Notes</p>
<p>If values in <em class="xref py py-obj">x</em> are such that they fall outside the bin range,
attempting to index <em class="xref py py-obj">bins</em> with the indices that <a class="reference internal" href="#numpy.digitize" title="numpy.digitize"><tt class="xref py py-obj docutils literal"><span class="pre">digitize</span></tt></a> returns
will result in an IndexError.</p>
<p class="rubric">Examples</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.2</span><span class="p">,</span> <span class="mf">6.4</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">,</span> <span class="mf">1.6</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">bins</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">0.0</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.5</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">,</span> <span class="mf">10.0</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">inds</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">digitize</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">bins</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">inds</span>
<span class="go">array([1, 4, 3, 2])</span>
<span class="gp">>>> </span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">size</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">print</span> <span class="n">bins</span><span class="p">[</span><span class="n">inds</span><span class="p">[</span><span class="n">n</span><span class="p">]</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="s">"<="</span><span class="p">,</span> <span class="n">x</span><span class="p">[</span><span class="n">n</span><span class="p">],</span> <span class="s">"<"</span><span class="p">,</span> <span class="n">bins</span><span class="p">[</span><span class="n">inds</span><span class="p">[</span><span class="n">n</span><span class="p">]]</span>
<span class="gp">...</span>
<span class="go">0.0 <= 0.2 < 1.0</span>
<span class="go">4.0 <= 6.4 < 10.0</span>
<span class="go">2.5 <= 3.0 < 4.0</span>
<span class="go">1.0 <= 1.6 < 2.5</span>
</pre></div>
</div>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">1.2</span><span class="p">,</span> <span class="mf">10.0</span><span class="p">,</span> <span class="mf">12.4</span><span class="p">,</span> <span class="mf">15.5</span><span class="p">,</span> <span class="mf">20.</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">bins</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">10</span><span class="p">,</span><span class="mi">15</span><span class="p">,</span><span class="mi">20</span><span class="p">])</span>
<span class="gp">>>> </span><span class="n">np</span><span class="o">.</span><span class="n">digitize</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">bins</span><span class="p">,</span><span class="n">right</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">array([1, 2, 3, 4, 4])</span>
<span class="gp">>>> </span><span class="n">np</span><span class="o">.</span><span class="n">digitize</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">bins</span><span class="p">,</span><span class="n">right</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="go">array([1, 3, 3, 4, 5])</span>
</pre></div>
</div>
</dd></dl>
</div>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
© <a href="../../copyright.html">Copyright</a> 2008-2009, The Scipy community.
<br />
The Python Software Foundation is a non-profit corporation.
<a href="http://www.python.org/psf/donations/">Please donate.</a>
<br />
Last updated on May 03, 2016.
<a href="../../bugs.html">Found a bug</a>?
<br />
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.1.
</div>
</body>
</html>
|
leesavide/pythonista-docs
|
Documentation/numpy/reference/generated/numpy.digitize.html
|
HTML
|
apache-2.0
| 14,449
|
great_rsd(v1,ii1).
great_rsd(hh1,dd1).
great_rsd(v1,w1).
great_rsd(cc1,q1).
great_rsd(kk1,ii1).
great_rsd(w1,ff1).
great_rsd(u1,ii1).
great_rsd(e1,l1).
great_rsd(ee1,hh1).
great_rsd(aa1,z1).
great_rsd(a1,x1).
great_rsd(hh1,jj1).
great_rsd(cc1,ii1).
great_rsd(t1,z1).
great_rsd(w1,kk1).
great_rsd(aa1,h1).
great_rsd(v1,ff1).
great_rsd(ee1,m1).
great_rsd(f1,t1).
|
manoelfranca/cilppp
|
foldsCreator/files/datasets/alzheimer_scopolamine_noiseless/incremental6/test5.f
|
FORTRAN
|
apache-2.0
| 361
|
# Archidendropsis xanthoxylon (C.T.White & W.D.Francis) I.C.Nielsen SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Albizia xanthoxylon C.T.White & W.D.Francis
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Archidendropsis/Archidendropsis xanthoxylon/README.md
|
Markdown
|
apache-2.0
| 262
|
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>"stats/base/dists/normal/mean/docs/types/index.d" | stdlib</title>
<meta name="description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
<meta name="author" content="stdlib">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- Icons -->
<link rel="apple-touch-icon" sizes="180x180" href="../apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png">
<link rel="manifest" href="../manifest.json">
<link rel="mask-icon" href="../safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<!-- Facebook Open Graph -->
<meta property="og:type" content="website">
<meta property="og:site_name" content="stdlib">
<meta property="og:url" content="https://stdlib.io/">
<meta property="og:title" content="A standard library for JavaScript and Node.js.">
<meta property="og:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="">
<!-- Twitter -->
<meta name="twitter:card" content="A standard library for JavaScript and Node.js.">
<meta name="twitter:site" content="@stdlibjs">
<meta name="twitter:url" content="https://stdlib.io/">
<meta name="twitter:title" content="stdlib">
<meta name="twitter:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
<meta name="twitter:image" content="">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/theme.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title"><img src="../logo_white.svg" alt="stdlib"></a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="_stats_base_dists_normal_mean_docs_types_index_d_.html">"stats/base/dists/normal/mean/docs/types/index.d"</a>
</li>
</ul>
<h1>External module "stats/base/dists/normal/mean/docs/types/index.d"</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-not-exported">
<h3>Functions</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported"><a href="_stats_base_dists_normal_mean_docs_types_index_d_.html#mean" class="tsd-kind-icon">mean</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-not-exported">
<h2>Functions</h2>
<section class="tsd-panel tsd-member tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a name="mean" class="tsd-anchor"></a>
<h3>mean</h3>
<ul class="tsd-signatures tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<li class="tsd-signature tsd-kind-icon">mean<span class="tsd-signature-symbol">(</span>mu<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span>, sigma<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">number</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/stdlib-js/stdlib/blob/61b1a8a068/lib/node_modules/@stdlib/stats/base/dists/normal/mean/docs/types/index.d.ts#L52">lib/node_modules/@stdlib/stats/base/dists/normal/mean/docs/types/index.d.ts:52</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Returns the expected value for a normal distribution with mean <code>mu</code> and standard deviation <code>sigma</code>.</p>
</div>
<a href="#notes" id="notes" style="color: inherit; text-decoration: none;">
<h2>Notes</h2>
</a>
<ul>
<li>If provided <code>sigma <= 0</code>, the function returns <code>NaN</code>.</li>
</ul>
</div>
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>mu: <span class="tsd-signature-type">number</span></h5>
<div class="tsd-comment tsd-typography">
<p>mean</p>
</div>
</li>
<li>
<h5>sigma: <span class="tsd-signature-type">number</span></h5>
<div class="tsd-comment tsd-typography">
<p>standard deviation</p>
</div>
</li>
</ul>
<h4 class="tsd-returns-title">Returns
<span class="tsd-signature-type">number</span>
</h4>
<p>expected value</p>
<h4 class="tsd-example-title">Example</h4>
<div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = mean( <span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span> );
<span class="hljs-comment">// returns 0.0</span></code></pre>
</div>
<h4 class="tsd-example-title">Example</h4>
<div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = mean( <span class="hljs-number">5.0</span>, <span class="hljs-number">2.0</span> );
<span class="hljs-comment">// returns 5.0</span></code></pre>
</div>
<h4 class="tsd-example-title">Example</h4>
<div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = mean( <span class="hljs-literal">NaN</span>, <span class="hljs-number">1.0</span> );
<span class="hljs-comment">// returns NaN</span></code></pre>
</div>
<h4 class="tsd-example-title">Example</h4>
<div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = mean( <span class="hljs-number">0.0</span>, <span class="hljs-literal">NaN</span> );
<span class="hljs-comment">// returns NaN</span></code></pre>
</div>
<h4 class="tsd-example-title">Example</h4>
<div><pre><code class="language-javascript"><span class="hljs-keyword">var</span> y = mean( <span class="hljs-number">0.0</span>, <span class="hljs-number">0.0</span> );
<span class="hljs-comment">// returns NaN</span></code></pre>
</div>
</li>
</ul>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Packages</em></a>
</li>
<li class="current tsd-kind-external-module">
<a href="_stats_base_dists_normal_mean_docs_types_index_d_.html">"stats/base/dists/normal/mean/docs/types/index.d"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="_stats_base_dists_normal_mean_docs_types_index_d_.html#mean" class="tsd-kind-icon">mean</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer>
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
<li class="tsd-kind-type-alias tsd-has-type-parameter"><span class="tsd-kind-icon">Type alias with type parameter</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
<div class="bottom-nav center border-top">
<a href="https://www.patreon.com/athan">Donate</a>
/
<a href="/docs/api/">Docs</a>
/
<a href="https://gitter.im/stdlib-js/stdlib">Chat</a>
/
<a href="https://twitter.com/stdlibjs">Twitter</a>
/
<a href="https://github.com/stdlib-js/stdlib">Contribute</a>
</div>
</footer>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script src="../assets/js/theme.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-105890493-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
|
stdlib-js/www
|
public/docs/ts/latest/modules/_stats_base_dists_normal_mean_docs_types_index_d_.html
|
HTML
|
apache-2.0
| 15,035
|
<div class="cls-content">
<div class="cls-content-sm panel">
<div class="panel-head">
<div class="app-logo">
<img class="logo" src="images/logo-ristekdikti.png" alt="">
</div>
<div class="login msg">
<h1 class="login-box-msg">Login</h1>
</div>
</div>
<div class="panel-body">
<form name="loginForm" ng-submit="$ctrl.login(loginForm, $event)" novalidate>
<div class="form-group" ng-class="{'bad': loginForm.email.$invalid && (loginForm.password.$dirty || $ctrl.formSubmitted)}">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user"></i></div>
<input type="email" class="form-control" ng-model="$ctrl.auth.email" name="email" placeholder="Username" ng-required="true">
</div>
</div>
<div class="form-group" ng-class="{'bad': loginForm.password.$invalid && (loginForm.password.$dirty || $ctrl.formSubmitted)}">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-asterisk"></i></div>
<input type="password" class="form-control" ng-model="$ctrl.auth.password" name="password" placeholder="Password" ng-required="true">
</div>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-8">
<div class="text-right">
<button class="btn btn-primary" type="submit">Masuk</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
|
onolinus/AdminSurveyOnline
|
client/app/components/login/login.html
|
HTML
|
apache-2.0
| 1,611
|
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging
import os
import re
import time
from datetime import datetime
from django.forms.formsets import formset_factory
from django.http import HttpResponse
from django.utils.functional import wraps
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from desktop.conf import TIME_ZONE
from desktop.lib.django_util import JsonResponse, render
from desktop.lib.json_utils import JSONEncoderForHTML
from desktop.lib.exceptions_renderable import PopupException
from desktop.lib.i18n import smart_str, smart_unicode
from desktop.lib.rest.http_client import RestException
from desktop.lib.view_util import format_duration_in_millis
from desktop.log.access import access_warn
from desktop.models import Document, Document2
from hadoop.fs.hadoopfs import Hdfs
from liboozie.oozie_api import get_oozie
from liboozie.credentials import Credentials
from liboozie.submission2 import Submission
from oozie.conf import OOZIE_JOBS_COUNT, ENABLE_CRON_SCHEDULING, ENABLE_V2
from oozie.forms import RerunForm, ParameterForm, RerunCoordForm, RerunBundleForm, UpdateCoordinatorForm
from oozie.models import Workflow as OldWorkflow, Job, utc_datetime_format, Bundle, Coordinator, get_link, History as OldHistory
from oozie.models2 import History, Workflow, WORKFLOW_NODE_PROPERTIES
from oozie.settings import DJANGO_APPS
from oozie.utils import convert_to_server_timezone
def get_history():
if ENABLE_V2.get():
return History
else:
return OldHistory
def get_workflow():
if ENABLE_V2.get():
return Workflow
else:
return OldWorkflow
LOG = logging.getLogger(__name__)
"""
Permissions:
A Workflow/Coordinator/Bundle can:
* be accessed only by its owner or a superuser or by a user with 'dashboard_jobs_access' permissions
* be submitted/modified only by its owner or a superuser
Permissions checking happens by calling:
* check_job_access_permission()
* check_job_edition_permission()
"""
def _get_workflows(user):
return [{
'name': workflow.name,
'owner': workflow.owner.username,
'value': workflow.uuid,
'id': workflow.id
} for workflow in [d.content_object for d in Document.objects.get_docs(user, Document2, extra='workflow2')]
]
def manage_oozie_jobs(request, job_id, action):
if request.method != 'POST':
raise PopupException(_('Use a POST request to manage an Oozie job.'))
job = check_job_access_permission(request, job_id)
check_job_edition_permission(job, request.user)
response = {'status': -1, 'data': ''}
try:
oozie_api = get_oozie(request.user)
params = None
if action == 'change':
pause_time_val = request.POST.get('pause_time')
if request.POST.get('clear_pause_time') == 'true':
pause_time_val = ''
end_time_val = request.POST.get('end_time')
if end_time_val:
end_time_val = convert_to_server_timezone(end_time_val, TIME_ZONE.get())
if pause_time_val:
pause_time_val = convert_to_server_timezone(pause_time_val, TIME_ZONE.get())
params = {'value': 'endtime=%s' % (end_time_val) + ';'
'pausetime=%s' % (pause_time_val) + ';'
'concurrency=%s' % (request.POST.get('concurrency'))}
elif action == 'ignore':
oozie_api = get_oozie(request.user, api_version="v2")
params = {
'type': 'action',
'scope': ','.join(job.aggreate(request.POST.get('actions').split())),
}
response['data'] = oozie_api.job_control(job_id, action, parameters=params)
response['status'] = 0
if 'notification' in request.POST:
request.info(_(request.POST.get('notification')))
except RestException, ex:
ex_message = ex.message
if ex._headers.get('oozie-error-message'):
ex_message = ex._headers.get('oozie-error-message')
msg = "Error performing %s on Oozie job %s: %s." % (action, job_id, ex_message)
LOG.exception(msg)
response['data'] = _(msg)
return JsonResponse(response)
def bulk_manage_oozie_jobs(request):
if request.method != 'POST':
raise PopupException(_('Use a POST request to manage the Oozie jobs.'))
response = {'status': -1, 'data': ''}
if 'job_ids' in request.POST and 'action' in request.POST:
jobs = request.POST.get('job_ids').split()
response = {'totalRequests': len(jobs), 'totalErrors': 0, 'messages': ''}
oozie_api = get_oozie(request.user)
for job_id in jobs:
job = check_job_access_permission(request, job_id)
check_job_edition_permission(job, request.user)
try:
oozie_api.job_control(job_id, request.POST.get('action'))
except RestException, ex:
LOG.exception("Error performing bulk operation for job_id=%s", job_id)
response['totalErrors'] = response['totalErrors'] + 1
response['messages'] += str(ex)
return JsonResponse(response)
def show_oozie_error(view_func):
def decorate(request, *args, **kwargs):
try:
return view_func(request, *args, **kwargs)
except RestException, ex:
LOG.exception("Error communicating with Oozie in %s", view_func.__name__)
detail = ex._headers.get('oozie-error-message', ex)
if 'Max retries exceeded with url' in str(detail) or 'Connection refused' in str(detail):
detail = _('The Oozie server is not running')
raise PopupException(_('An error occurred with Oozie.'), detail=detail)
return wraps(view_func)(decorate)
@show_oozie_error
def list_oozie_workflows(request):
kwargs = {'cnt': OOZIE_JOBS_COUNT.get(), 'filters': []}
if not has_dashboard_jobs_access(request.user):
kwargs['filters'].append(('user', request.user.username))
oozie_api = get_oozie(request.user)
if request.GET.get('format') == 'json':
just_sla = request.GET.get('justsla') == 'true'
if request.GET.get('startcreatedtime'):
kwargs['filters'].extend([('startcreatedtime', request.GET.get('startcreatedtime'))])
if request.GET.get('offset'):
kwargs['offset'] = request.GET.get('offset')
json_jobs = []
total_jobs = 0
if request.GET.getlist('status'):
kwargs['filters'].extend([('status', status) for status in request.GET.getlist('status')])
wf_list = oozie_api.get_workflows(**kwargs)
json_jobs = wf_list.jobs
total_jobs = wf_list.total
if request.GET.get('type') == 'progress':
json_jobs = [oozie_api.get_job(job.id) for job in json_jobs]
response = massaged_oozie_jobs_for_json(json_jobs, request.user, just_sla)
response['total_jobs'] = total_jobs
return JsonResponse(response, encoder=JSONEncoderForHTML)
return render('dashboard/list_oozie_workflows.mako', request, {
'user': request.user,
'jobs': [],
'has_job_edition_permission': has_job_edition_permission,
})
@show_oozie_error
def list_oozie_coordinators(request):
kwargs = {'cnt': OOZIE_JOBS_COUNT.get(), 'filters': []}
if not has_dashboard_jobs_access(request.user):
kwargs['filters'].append(('user', request.user.username))
oozie_api = get_oozie(request.user)
enable_cron_scheduling = ENABLE_CRON_SCHEDULING.get()
if request.GET.get('format') == 'json':
if request.GET.get('offset'):
kwargs['offset'] = request.GET.get('offset')
json_jobs = []
total_jobs = 0
if request.GET.getlist('status'):
kwargs['filters'].extend([('status', status) for status in request.GET.getlist('status')])
co_list = oozie_api.get_coordinators(**kwargs)
json_jobs = co_list.jobs
total_jobs = co_list.total
if request.GET.get('type') == 'progress':
json_jobs = [oozie_api.get_coordinator(job.id) for job in json_jobs]
response = massaged_oozie_jobs_for_json(json_jobs, request.user)
response['total_jobs'] = total_jobs
return JsonResponse(response, encoder=JSONEncoderForHTML)
return render('dashboard/list_oozie_coordinators.mako', request, {
'jobs': [],
'has_job_edition_permission': has_job_edition_permission,
'enable_cron_scheduling': enable_cron_scheduling,
})
@show_oozie_error
def list_oozie_bundles(request):
kwargs = {'cnt': OOZIE_JOBS_COUNT.get(), 'filters': []}
if not has_dashboard_jobs_access(request.user):
kwargs['filters'].append(('user', request.user.username))
oozie_api = get_oozie(request.user)
if request.GET.get('format') == 'json':
if request.GET.get('offset'):
kwargs['offset'] = request.GET.get('offset')
json_jobs = []
total_jobs = 0
if request.GET.getlist('status'):
kwargs['filters'].extend([('status', status) for status in request.GET.getlist('status')])
bundle_list = oozie_api.get_bundles(**kwargs)
json_jobs = bundle_list.jobs
total_jobs = bundle_list.total
if request.GET.get('type') == 'progress':
json_jobs = [oozie_api.get_coordinator(job.id) for job in json_jobs]
response = massaged_oozie_jobs_for_json(json_jobs, request.user)
response['total_jobs'] = total_jobs
return JsonResponse(response, encoder=JSONEncoderForHTML)
return render('dashboard/list_oozie_bundles.mako', request, {
'jobs': [],
'has_job_edition_permission': has_job_edition_permission,
})
@show_oozie_error
def list_oozie_workflow(request, job_id):
oozie_workflow = check_job_access_permission(request, job_id)
oozie_coordinator = None
if request.GET.get('coordinator_job_id'):
oozie_coordinator = check_job_access_permission(request, request.GET.get('coordinator_job_id'))
oozie_bundle = None
if request.GET.get('bundle_job_id'):
oozie_bundle = check_job_access_permission(request, request.GET.get('bundle_job_id'))
if oozie_coordinator is not None:
setattr(oozie_workflow, 'oozie_coordinator', oozie_coordinator)
if oozie_bundle is not None:
setattr(oozie_workflow, 'oozie_bundle', oozie_bundle)
oozie_parent = oozie_workflow.get_parent_job_id()
if oozie_parent:
oozie_parent = check_job_access_permission(request, oozie_parent)
workflow_data = None
credentials = None
doc = None
hue_workflow = None
workflow_graph = 'MISSING' # default to prevent loading the graph tab for deleted workflows
full_node_list = None
if ENABLE_V2.get():
try:
# To update with the new History document model
hue_coord = get_history().get_coordinator_from_config(oozie_workflow.conf_dict)
hue_workflow = (hue_coord and hue_coord.workflow) or get_history().get_workflow_from_config(oozie_workflow.conf_dict)
if hue_coord and hue_coord.workflow: hue_coord.workflow.document.doc.get().can_read_or_exception(request.user)
if hue_workflow: hue_workflow.document.doc.get().can_read_or_exception(request.user)
if hue_workflow:
full_node_list = hue_workflow.nodes
workflow_id = hue_workflow.id
wid = {
'id': workflow_id
}
doc = Document2.objects.get(type='oozie-workflow2', **wid)
new_workflow = get_workflow()(document=doc)
workflow_data = new_workflow.get_data()
else:
try:
workflow_data = Workflow.gen_workflow_data_from_xml(request.user, oozie_workflow)
except Exception, e:
LOG.exception('Graph data could not be generated from Workflow %s: %s' % (oozie_workflow.id, e))
workflow_graph = ''
credentials = Credentials()
except:
LOG.exception("Error generating full page for running workflow %s" % job_id)
else:
history = get_history().cross_reference_submission_history(request.user, job_id)
hue_coord = history and history.get_coordinator() or get_history().get_coordinator_from_config(oozie_workflow.conf_dict)
hue_workflow = (hue_coord and hue_coord.workflow) or (history and history.get_workflow()) or get_history().get_workflow_from_config(oozie_workflow.conf_dict)
if hue_coord and hue_coord.workflow: Job.objects.can_read_or_exception(request, hue_coord.workflow.id)
if hue_workflow: Job.objects.can_read_or_exception(request, hue_workflow.id)
if hue_workflow:
workflow_graph = hue_workflow.gen_status_graph(oozie_workflow)
full_node_list = hue_workflow.node_list
else:
workflow_graph, full_node_list = get_workflow().gen_status_graph_from_xml(request.user, oozie_workflow)
parameters = oozie_workflow.conf_dict.copy()
for action in oozie_workflow.actions:
action.oozie_coordinator = oozie_coordinator
action.oozie_bundle = oozie_bundle
if request.GET.get('format') == 'json':
return_obj = {
'id': oozie_workflow.id,
'status': oozie_workflow.status,
'progress': oozie_workflow.get_progress(full_node_list),
'graph': workflow_graph,
'actions': massaged_workflow_actions_for_json(oozie_workflow.get_working_actions(), oozie_coordinator, oozie_bundle)
}
return JsonResponse(return_obj, encoder=JSONEncoderForHTML)
oozie_slas = []
if oozie_workflow.has_sla:
oozie_api = get_oozie(request.user, api_version="v2")
params = {
'id': oozie_workflow.id,
'parent_id': oozie_workflow.id
}
oozie_slas = oozie_api.get_oozie_slas(**params)
return render('dashboard/list_oozie_workflow.mako', request, {
'oozie_workflow': oozie_workflow,
'oozie_coordinator': oozie_coordinator,
'oozie_bundle': oozie_bundle,
'oozie_parent': oozie_parent,
'oozie_slas': oozie_slas,
'hue_workflow': hue_workflow,
'hue_coord': hue_coord,
'parameters': parameters,
'has_job_edition_permission': has_job_edition_permission,
'workflow_graph': workflow_graph,
'layout_json': json.dumps(workflow_data['layout'], cls=JSONEncoderForHTML) if workflow_data else '',
'workflow_json': json.dumps(workflow_data['workflow'], cls=JSONEncoderForHTML) if workflow_data else '',
'credentials_json': json.dumps(credentials.credentials.keys(), cls=JSONEncoderForHTML) if credentials else '',
'workflow_properties_json': json.dumps(WORKFLOW_NODE_PROPERTIES, cls=JSONEncoderForHTML),
'doc1_id': doc.doc.get().id if doc else -1,
'subworkflows_json': json.dumps(_get_workflows(request.user), cls=JSONEncoderForHTML),
'can_edit_json': json.dumps(doc is None or doc.doc.get().is_editable(request.user))
})
@show_oozie_error
def list_oozie_coordinator(request, job_id):
kwargs = {'cnt': 50, 'filters': []}
kwargs['offset'] = request.GET.get('offset', 1)
if request.GET.getlist('status'):
kwargs['filters'].extend([('status', status) for status in request.GET.getlist('status')])
oozie_coordinator = check_job_access_permission(request, job_id, **kwargs)
# Cross reference the submission history (if any)
coordinator = get_history().get_coordinator_from_config(oozie_coordinator.conf_dict)
try:
if not ENABLE_V2.get():
coordinator = get_history().objects.get(oozie_job_id=job_id).job.get_full_node()
except:
LOG.exception("Ignoring error getting oozie job coordinator for job_id=%s", job_id)
oozie_bundle = None
if request.GET.get('bundle_job_id'):
try:
oozie_bundle = check_job_access_permission(request, request.GET.get('bundle_job_id'))
except:
LOG.exception("Ignoring error getting oozie bundle for job_id=%s", job_id)
if request.GET.get('format') == 'json':
actions = massaged_coordinator_actions_for_json(oozie_coordinator, oozie_bundle)
return_obj = {
'id': oozie_coordinator.id,
'status': oozie_coordinator.status,
'progress': oozie_coordinator.get_progress(),
'nextTime': format_time(oozie_coordinator.nextMaterializedTime),
'endTime': format_time(oozie_coordinator.endTime),
'actions': actions,
'total_actions': oozie_coordinator.total
}
return JsonResponse(return_obj, encoder=JSONEncoderForHTML)
oozie_slas = []
if oozie_coordinator.has_sla:
oozie_api = get_oozie(request.user, api_version="v2")
params = {
'id': oozie_coordinator.id,
'parent_id': oozie_coordinator.id
}
oozie_slas = oozie_api.get_oozie_slas(**params)
enable_cron_scheduling = ENABLE_CRON_SCHEDULING.get()
update_coord_form = UpdateCoordinatorForm(oozie_coordinator=oozie_coordinator)
return render('dashboard/list_oozie_coordinator.mako', request, {
'oozie_coordinator': oozie_coordinator,
'oozie_slas': oozie_slas,
'coordinator': coordinator,
'oozie_bundle': oozie_bundle,
'has_job_edition_permission': has_job_edition_permission,
'enable_cron_scheduling': enable_cron_scheduling,
'update_coord_form': update_coord_form,
})
@show_oozie_error
def list_oozie_bundle(request, job_id):
oozie_bundle = check_job_access_permission(request, job_id)
# Cross reference the submission history (if any)
bundle = None
try:
if ENABLE_V2.get():
bundle = get_history().get_bundle_from_config(oozie_bundle.conf_dict)
else:
bundle = get_history().objects.get(oozie_job_id=job_id).job.get_full_node()
except:
LOG.exception("Ignoring error getting oozie job bundle for job_id=%s", job_id)
if request.GET.get('format') == 'json':
return_obj = {
'id': oozie_bundle.id,
'status': oozie_bundle.status,
'progress': oozie_bundle.get_progress(),
'endTime': format_time(oozie_bundle.endTime),
'actions': massaged_bundle_actions_for_json(oozie_bundle)
}
return HttpResponse(json.dumps(return_obj).replace('\\\\', '\\'), content_type="application/json")
return render('dashboard/list_oozie_bundle.mako', request, {
'oozie_bundle': oozie_bundle,
'bundle': bundle,
'has_job_edition_permission': has_job_edition_permission,
})
@show_oozie_error
def list_oozie_workflow_action(request, action):
try:
action = get_oozie(request.user).get_action(action)
workflow = check_job_access_permission(request, action.id.split('@')[0])
except RestException, ex:
msg = _("Error accessing Oozie action %s.") % (action,)
LOG.exception(msg)
raise PopupException(msg, detail=ex.message)
oozie_coordinator = None
if request.GET.get('coordinator_job_id'):
oozie_coordinator = check_job_access_permission(request, request.GET.get('coordinator_job_id'))
oozie_bundle = None
if request.GET.get('bundle_job_id'):
oozie_bundle = check_job_access_permission(request, request.GET.get('bundle_job_id'))
workflow.oozie_coordinator = oozie_coordinator
workflow.oozie_bundle = oozie_bundle
oozie_parent = workflow.get_parent_job_id()
if oozie_parent:
oozie_parent = check_job_access_permission(request, oozie_parent)
return render('dashboard/list_oozie_workflow_action.mako', request, {
'action': action,
'workflow': workflow,
'oozie_coordinator': oozie_coordinator,
'oozie_bundle': oozie_bundle,
'oozie_parent': oozie_parent,
})
@show_oozie_error
def get_oozie_job_log(request, job_id):
oozie_api = get_oozie(request.user, api_version="v2")
check_job_access_permission(request, job_id)
kwargs = {'logfilter' : []}
if request.GET.get('format') == 'json':
if request.GET.get('recent'):
kwargs['logfilter'].extend([('recent', val) for val in request.GET.get('recent').split(':')])
if request.GET.get('limit'):
kwargs['logfilter'].extend([('limit', request.GET.get('limit'))])
if request.GET.get('loglevel'):
kwargs['logfilter'].extend([('loglevel', request.GET.get('loglevel'))])
if request.GET.get('text'):
kwargs['logfilter'].extend([('text', request.GET.get('text'))])
status_resp = oozie_api.get_job_status(job_id)
log = oozie_api.get_job_log(job_id, **kwargs)
return_obj = {
'id': job_id,
'status': status_resp['status'],
'log': log,
}
return JsonResponse(return_obj, encoder=JSONEncoderForHTML)
@show_oozie_error
def list_oozie_info(request):
api = get_oozie(request.user)
configuration = api.get_configuration()
oozie_status = api.get_oozie_status()
instrumentation = {}
metrics = {}
if 'org.apache.oozie.service.MetricsInstrumentationService' in [c.strip() for c in configuration.get('oozie.services.ext', '').split(',')]:
api2 = get_oozie(request.user, api_version="v2")
metrics = api2.get_metrics()
else:
instrumentation = api.get_instrumentation()
return render('dashboard/list_oozie_info.mako', request, {
'instrumentation': instrumentation,
'metrics': metrics,
'configuration': configuration,
'oozie_status': oozie_status,
})
@show_oozie_error
def list_oozie_sla(request):
oozie_api = get_oozie(request.user, api_version="v2")
if request.method == 'POST':
params = {}
job_name = request.POST.get('job_name')
if re.match('.*-oozie-oozi-[WCB]', job_name):
params['id'] = job_name
params['parent_id'] = job_name
else:
params['app_name'] = job_name
if 'useDates' in request.POST:
if request.POST.get('start'):
params['nominal_start'] = request.POST.get('start')
if request.POST.get('end'):
params['nominal_end'] = request.POST.get('end')
oozie_slas = oozie_api.get_oozie_slas(**params)
else:
oozie_slas = [] # or get latest?
if request.REQUEST.get('format') == 'json':
massaged_slas = []
for sla in oozie_slas:
massaged_slas.append(massaged_sla_for_json(sla, request))
return HttpResponse(json.dumps({'oozie_slas': massaged_slas}), content_type="text/json")
configuration = oozie_api.get_configuration()
show_slas_hint = 'org.apache.oozie.sla.service.SLAService' not in configuration.get('oozie.services.ext', '')
return render('dashboard/list_oozie_sla.mako', request, {
'oozie_slas': oozie_slas,
'show_slas_hint': show_slas_hint
})
def massaged_sla_for_json(sla, request):
massaged_sla = {
'slaStatus': sla['slaStatus'],
'id': sla['id'],
'appType': sla['appType'],
'appName': sla['appName'],
'appUrl': get_link(sla['id']),
'user': sla['user'],
'nominalTime': sla['nominalTime'],
'expectedStart': sla['expectedStart'],
'actualStart': sla['actualStart'],
'expectedEnd': sla['expectedEnd'],
'actualEnd': sla['actualEnd'],
'jobStatus': sla['jobStatus'],
'expectedDuration': sla['expectedDuration'],
'actualDuration': sla['actualDuration'],
'lastModified': sla['lastModified']
}
return massaged_sla
@show_oozie_error
def sync_coord_workflow(request, job_id):
ParametersFormSet = formset_factory(ParameterForm, extra=0)
job = check_job_access_permission(request, job_id)
check_job_edition_permission(job, request.user)
hue_coord = get_history().get_coordinator_from_config(job.conf_dict)
hue_wf = (hue_coord and hue_coord.workflow) or get_history().get_workflow_from_config(job.conf_dict)
wf_application_path = job.conf_dict.get('wf_application_path') and Hdfs.urlsplit(job.conf_dict['wf_application_path'])[2] or ''
coord_application_path = job.conf_dict.get('oozie.coord.application.path') and Hdfs.urlsplit(job.conf_dict['oozie.coord.application.path'])[2] or ''
properties = hue_coord and hue_coord.properties and dict([(param['name'], param['value']) for param in hue_coord.properties]) or None
if request.method == 'POST':
params_form = ParametersFormSet(request.POST)
if params_form.is_valid():
mapping = dict([(param['name'], param['value']) for param in params_form.cleaned_data])
# Update workflow params in coordinator
hue_coord.clear_workflow_params()
properties = dict([(param['name'], param['value']) for param in hue_coord.properties])
# Deploy WF XML
submission = Submission(user=request.user, job=hue_wf, fs=request.fs, jt=request.jt, properties=properties)
submission._create_file(wf_application_path, hue_wf.XML_FILE_NAME, hue_wf.to_xml(mapping=properties), do_as=True)
# Deploy Coordinator XML
job.conf_dict.update(mapping)
submission = Submission(user=request.user, job=hue_coord, fs=request.fs, jt=request.jt, properties=job.conf_dict, oozie_id=job.id)
submission._create_file(coord_application_path, hue_coord.XML_FILE_NAME, hue_coord.to_xml(mapping=job.conf_dict), do_as=True)
# Server picks up deployed Coordinator XML changes after running 'update' action
submission.update_coord()
request.info(_('Successfully updated Workflow definition'))
return redirect(reverse('oozie:list_oozie_coordinator', kwargs={'job_id': job_id}))
else:
request.error(_('Invalid submission form: %s' % params_form.errors))
else:
new_params = hue_wf and hue_wf.find_all_parameters() or []
new_params = dict([(param['name'], param['value']) for param in new_params])
# Set previous values
if properties:
new_params = dict([(key, properties[key]) if key in properties.keys() else (key, new_params[key]) for key, value in new_params.iteritems()])
initial_params = ParameterForm.get_initial_params(new_params)
params_form = ParametersFormSet(initial=initial_params)
popup = render('editor2/submit_job_popup.mako', request, {
'params_form': params_form,
'name': _('Job'),
'header': _('Sync Workflow definition?'),
'action': reverse('oozie:sync_coord_workflow', kwargs={'job_id': job_id})
}, force_template=True).content
return JsonResponse(popup, safe=False)
@show_oozie_error
def rerun_oozie_job(request, job_id, app_path):
ParametersFormSet = formset_factory(ParameterForm, extra=0)
oozie_workflow = check_job_access_permission(request, job_id)
check_job_edition_permission(oozie_workflow, request.user)
if request.method == 'POST':
rerun_form = RerunForm(request.POST, oozie_workflow=oozie_workflow)
params_form = ParametersFormSet(request.POST)
if sum([rerun_form.is_valid(), params_form.is_valid()]) == 2:
args = {}
if request.POST['rerun_form_choice'] == 'fail_nodes':
args['fail_nodes'] = 'true'
else:
args['skip_nodes'] = ','.join(rerun_form.cleaned_data['skip_nodes'])
args['deployment_dir'] = app_path
mapping = dict([(param['name'], param['value']) for param in params_form.cleaned_data])
_rerun_workflow(request, job_id, args, mapping)
request.info(_('Workflow re-running.'))
return redirect(reverse('oozie:list_oozie_workflow', kwargs={'job_id': job_id}))
else:
request.error(_('Invalid submission form: %s %s' % (rerun_form.errors, params_form.errors)))
else:
rerun_form = RerunForm(oozie_workflow=oozie_workflow)
initial_params = ParameterForm.get_initial_params(oozie_workflow.conf_dict)
params_form = ParametersFormSet(initial=initial_params)
popup = render('dashboard/rerun_job_popup.mako', request, {
'rerun_form': rerun_form,
'params_form': params_form,
'action': reverse('oozie:rerun_oozie_job', kwargs={'job_id': job_id, 'app_path': app_path}),
}, force_template=True).content
return JsonResponse(popup, safe=False)
def _rerun_workflow(request, oozie_id, run_args, mapping):
try:
submission = Submission(user=request.user, fs=request.fs, jt=request.jt, properties=mapping, oozie_id=oozie_id)
job_id = submission.rerun(**run_args)
return job_id
except RestException, ex:
msg = _("Error re-running workflow %s.") % (oozie_id,)
LOG.exception(msg)
raise PopupException(msg, detail=ex._headers.get('oozie-error-message', ex))
@show_oozie_error
def rerun_oozie_coordinator(request, job_id, app_path):
oozie_coordinator = check_job_access_permission(request, job_id)
check_job_edition_permission(oozie_coordinator, request.user)
ParametersFormSet = formset_factory(ParameterForm, extra=0)
if request.method == 'POST':
params_form = ParametersFormSet(request.POST)
rerun_form = RerunCoordForm(request.POST, oozie_coordinator=oozie_coordinator)
if sum([rerun_form.is_valid(), params_form.is_valid()]) == 2:
args = {}
args['deployment_dir'] = app_path
params = {
'type': 'action',
'scope': ','.join(oozie_coordinator.aggreate(rerun_form.cleaned_data['actions'])),
'refresh': rerun_form.cleaned_data['refresh'],
'nocleanup': rerun_form.cleaned_data['nocleanup'],
}
properties = dict([(param['name'], param['value']) for param in params_form.cleaned_data])
_rerun_coordinator(request, job_id, args, params, properties)
request.info(_('Coordinator re-running.'))
return redirect(reverse('oozie:list_oozie_coordinator', kwargs={'job_id': job_id}))
else:
request.error(_('Invalid submission form: %s') % smart_unicode(rerun_form.errors))
return list_oozie_coordinator(request, job_id)
else:
rerun_form = RerunCoordForm(oozie_coordinator=oozie_coordinator)
initial_params = ParameterForm.get_initial_params(oozie_coordinator.conf_dict)
params_form = ParametersFormSet(initial=initial_params)
popup = render('dashboard/rerun_coord_popup.mako', request, {
'rerun_form': rerun_form,
'params_form': params_form,
'action': reverse('oozie:rerun_oozie_coord', kwargs={'job_id': job_id, 'app_path': app_path}),
}, force_template=True).content
return JsonResponse(popup, safe=False)
def _rerun_coordinator(request, oozie_id, args, params, properties):
try:
submission = Submission(user=request.user, fs=request.fs, jt=request.jt, oozie_id=oozie_id, properties=properties)
job_id = submission.rerun_coord(params=params, **args)
return job_id
except RestException, ex:
msg = _("Error re-running coordinator %s.") % (oozie_id,)
LOG.exception(msg)
raise PopupException(msg, detail=ex._headers.get('oozie-error-message', ex))
@show_oozie_error
def rerun_oozie_bundle(request, job_id, app_path):
oozie_bundle = check_job_access_permission(request, job_id)
check_job_edition_permission(oozie_bundle, request.user)
ParametersFormSet = formset_factory(ParameterForm, extra=0)
if request.method == 'POST':
params_form = ParametersFormSet(request.POST)
rerun_form = RerunBundleForm(request.POST, oozie_bundle=oozie_bundle)
if sum([rerun_form.is_valid(), params_form.is_valid()]) == 2:
args = {}
args['deployment_dir'] = app_path
params = {
'coord-scope': ','.join(rerun_form.cleaned_data['coordinators']),
'refresh': rerun_form.cleaned_data['refresh'],
'nocleanup': rerun_form.cleaned_data['nocleanup'],
}
if rerun_form.cleaned_data['start'] and rerun_form.cleaned_data['end']:
date = {
'date-scope':
'%(start)s::%(end)s' % {
'start': utc_datetime_format(rerun_form.cleaned_data['start']),
'end': utc_datetime_format(rerun_form.cleaned_data['end'])
}
}
params.update(date)
properties = dict([(param['name'], param['value']) for param in params_form.cleaned_data])
_rerun_bundle(request, job_id, args, params, properties)
request.info(_('Bundle re-running.'))
return redirect(reverse('oozie:list_oozie_bundle', kwargs={'job_id': job_id}))
else:
request.error(_('Invalid submission form: %s' % (rerun_form.errors,)))
return list_oozie_bundle(request, job_id)
else:
rerun_form = RerunBundleForm(oozie_bundle=oozie_bundle)
initial_params = ParameterForm.get_initial_params(oozie_bundle.conf_dict)
params_form = ParametersFormSet(initial=initial_params)
popup = render('dashboard/rerun_bundle_popup.mako', request, {
'rerun_form': rerun_form,
'params_form': params_form,
'action': reverse('oozie:rerun_oozie_bundle', kwargs={'job_id': job_id, 'app_path': app_path}),
}, force_template=True).content
return JsonResponse(popup, safe=False)
def _rerun_bundle(request, oozie_id, args, params, properties):
try:
submission = Submission(user=request.user, fs=request.fs, jt=request.jt, oozie_id=oozie_id, properties=properties)
job_id = submission.rerun_bundle(params=params, **args)
return job_id
except RestException, ex:
msg = _("Error re-running bundle %s.") % (oozie_id,)
LOG.exception(msg)
raise PopupException(msg, detail=ex._headers.get('oozie-error-message', ex))
def submit_external_job(request, application_path):
ParametersFormSet = formset_factory(ParameterForm, extra=0)
if request.method == 'POST':
params_form = ParametersFormSet(request.POST)
if params_form.is_valid():
mapping = dict([(param['name'], param['value']) for param in params_form.cleaned_data])
mapping['dryrun'] = request.POST.get('dryrun_checkbox') == 'on'
application_name = os.path.basename(application_path)
application_class = Bundle if application_name == 'bundle.xml' else Coordinator if application_name == 'coordinator.xml' else get_workflow()
mapping[application_class.get_application_path_key()] = application_path
try:
submission = Submission(request.user, fs=request.fs, jt=request.jt, properties=mapping)
job_id = submission.run(application_path)
except RestException, ex:
detail = ex._headers.get('oozie-error-message', ex)
if 'Max retries exceeded with url' in str(detail):
detail = '%s: %s' % (_('The Oozie server is not running'), detail)
LOG.exception(smart_str(detail))
raise PopupException(_("Error submitting job %s") % (application_path,), detail=detail)
request.info(_('Oozie job submitted'))
view = 'list_oozie_bundle' if application_name == 'bundle.xml' else 'list_oozie_coordinator' if application_name == 'coordinator.xml' else 'list_oozie_workflow'
return redirect(reverse('oozie:%s' % view, kwargs={'job_id': job_id}))
else:
request.error(_('Invalid submission form: %s' % params_form.errors))
else:
parameters = Submission(request.user, fs=request.fs, jt=request.jt).get_external_parameters(application_path)
initial_params = ParameterForm.get_initial_params(parameters)
params_form = ParametersFormSet(initial=initial_params)
popup = render('editor/submit_job_popup.mako', request, {
'params_form': params_form,
'name': _('Job'),
'action': reverse('oozie:submit_external_job', kwargs={'application_path': application_path}),
'show_dryrun': os.path.basename(application_path) != 'bundle.xml'
}, force_template=True).content
return JsonResponse(popup, safe=False)
def massaged_workflow_actions_for_json(workflow_actions, oozie_coordinator, oozie_bundle):
actions = []
for action in workflow_actions:
if oozie_coordinator is not None:
setattr(action, 'oozie_coordinator', oozie_coordinator)
if oozie_bundle is not None:
setattr(action, 'oozie_bundle', oozie_bundle)
massaged_action = {
'id': action.id,
'log': action.get_absolute_log_url(),
'url': action.get_absolute_url(),
'name': action.name,
'type': action.type,
'status': action.status,
'externalIdUrl': action.get_external_id_url(),
'externalId': action.externalId,
'startTime': format_time(action.startTime),
'endTime': format_time(action.endTime),
'retries': action.retries,
'errorCode': action.errorCode,
'errorMessage': action.errorMessage,
'transition': action.transition,
'data': action.data,
}
actions.append(massaged_action)
return actions
def massaged_coordinator_actions_for_json(coordinator, oozie_bundle):
coordinator_id = coordinator.id
coordinator_actions = coordinator.get_working_actions()
actions = []
related_job_ids = []
related_job_ids.append('coordinator_job_id=%s' % coordinator_id)
if oozie_bundle is not None:
related_job_ids.append('bundle_job_id=%s' %oozie_bundle.id)
for action in coordinator_actions:
massaged_action = {
'id': action.id,
'url': action.externalId and reverse('oozie:list_oozie_workflow', kwargs={'job_id': action.externalId}) + '?%s' % '&'.join(related_job_ids) or '',
'number': action.actionNumber,
'type': action.type,
'status': action.status,
'externalId': action.externalId or '-',
'externalIdUrl': action.externalId and reverse('oozie:list_oozie_workflow_action', kwargs={'action': action.externalId}) or '',
'nominalTime': format_time(action.nominalTime),
'title': action.title,
'createdTime': format_time(action.createdTime),
'lastModifiedTime': format_time(action.lastModifiedTime),
'errorCode': action.errorCode,
'errorMessage': action.errorMessage,
'missingDependencies': action.missingDependencies
}
actions.append(massaged_action)
# Sorting for Oozie < 4.1 backward compatibility
actions.sort(key=lambda k: k['number'], reverse=True)
return actions
def massaged_bundle_actions_for_json(bundle):
bundle_actions = bundle.get_working_actions()
actions = []
for action in bundle_actions:
massaged_action = {
'id': action.coordJobId,
'url': action.coordJobId and reverse('oozie:list_oozie_coordinator', kwargs={'job_id': action.coordJobId}) + '?bundle_job_id=%s' % bundle.id or '',
'name': action.coordJobName,
'type': action.type,
'status': action.status,
'externalId': action.coordExternalId or '-',
'frequency': action.frequency,
'timeUnit': action.timeUnit,
'nextMaterializedTime': action.nextMaterializedTime,
'concurrency': action.concurrency,
'pauseTime': action.pauseTime,
'user': action.user,
'acl': action.acl,
'timeOut': action.timeOut,
'coordJobPath': action.coordJobPath,
'executionPolicy': action.executionPolicy,
'startTime': action.startTime,
'endTime': action.endTime,
'lastAction': action.lastAction
}
actions.insert(0, massaged_action)
return actions
def format_time(st_time):
if st_time is None:
return '-'
elif type(st_time) == time.struct_time:
return time.strftime("%a, %d %b %Y %H:%M:%S", st_time)
else:
return st_time
def catch_unicode_time(u_time):
if type(u_time) == time.struct_time:
return u_time
else:
return datetime.timetuple(datetime.strptime(u_time, '%a, %d %b %Y %H:%M:%S %Z'))
def massaged_oozie_jobs_for_json(oozie_jobs, user, just_sla=False):
jobs = []
for job in oozie_jobs:
if not just_sla or (just_sla and job.has_sla) and job.appName != 'pig-app-hue-script':
last_modified_time_millis = hasattr(job, 'lastModTime') and job.lastModTime and (time.time() - time.mktime(job.lastModTime)) * 1000 or 0
duration_millis = job.endTime and job.startTime and ((time.mktime(job.endTime) - time.mktime(job.startTime)) * 1000) or 0
massaged_job = {
'id': job.id,
'lastModTime': hasattr(job, 'lastModTime') and job.lastModTime and format_time(job.lastModTime) or None,
'lastModTimeInMillis': last_modified_time_millis,
'lastModTimeFormatted': last_modified_time_millis and format_duration_in_millis(last_modified_time_millis) or None,
'kickoffTime': hasattr(job, 'kickoffTime') and job.kickoffTime and format_time(job.kickoffTime) or '',
'kickoffTimeInMillis': hasattr(job, 'kickoffTime') and job.kickoffTime and time.mktime(catch_unicode_time(job.kickoffTime)) or 0,
'nextMaterializedTime': hasattr(job, 'nextMaterializedTime') and job.nextMaterializedTime and format_time(job.nextMaterializedTime) or '',
'nextMaterializedTimeInMillis': hasattr(job, 'nextMaterializedTime') and job.nextMaterializedTime and time.mktime(job.nextMaterializedTime) or 0,
'timeOut': hasattr(job, 'timeOut') and job.timeOut or None,
'endTime': job.endTime and format_time(job.endTime) or None,
'pauseTime': hasattr(job, 'pauseTime') and job.pauseTime and format_time(job.endTime) or None,
'concurrency': hasattr(job, 'concurrency') and job.concurrency or None,
'endTimeInMillis': job.endTime and time.mktime(job.endTime) or 0,
'status': job.status,
'isRunning': job.is_running(),
'duration': duration_millis and format_duration_in_millis(duration_millis) or None,
'durationInMillis': duration_millis,
'appName': job.appName,
'progress': job.get_progress(),
'user': job.user,
'absoluteUrl': job.get_absolute_url(),
'canEdit': has_job_edition_permission(job, user),
'killUrl': reverse('oozie:manage_oozie_jobs', kwargs={'job_id':job.id, 'action':'kill'}),
'suspendUrl': reverse('oozie:manage_oozie_jobs', kwargs={'job_id':job.id, 'action':'suspend'}),
'resumeUrl': reverse('oozie:manage_oozie_jobs', kwargs={'job_id':job.id, 'action':'resume'}),
'created': hasattr(job, 'createdTime') and job.createdTime and format_time(job.createdTime) or '',
'createdInMillis': hasattr(job, 'createdTime') and job.createdTime and time.mktime(catch_unicode_time(job.createdTime)) or 0,
'startTime': hasattr(job, 'startTime') and format_time(job.startTime) or None,
'startTimeInMillis': hasattr(job, 'startTime') and job.startTime and time.mktime(job.startTime) or 0,
'run': hasattr(job, 'run') and job.run or 0,
'frequency': hasattr(job, 'frequency') and Coordinator.CRON_MAPPING.get(job.frequency, job.frequency) or None,
'timeUnit': hasattr(job, 'timeUnit') and job.timeUnit or None,
'parentUrl': hasattr(job, 'parentId') and job.parentId and get_link(job.parentId) or '',
'submittedManually': hasattr(job, 'parentId') and (job.parentId is None or 'C@' not in job.parentId)
}
jobs.append(massaged_job)
return { 'jobs': jobs }
def check_job_access_permission(request, job_id, **kwargs):
"""
Decorator ensuring that the user has access to the job submitted to Oozie.
Arg: Oozie 'workflow', 'coordinator' or 'bundle' ID.
Return: the Oozie workflow, coordinator or bundle or raise an exception
Notice: its gets an id in input and returns the full object in output (not an id).
"""
if job_id is not None:
oozie_api = get_oozie(request.user)
if job_id.endswith('W'):
get_job = oozie_api.get_job
elif job_id.endswith('C'):
get_job = oozie_api.get_coordinator
else:
get_job = oozie_api.get_bundle
try:
if job_id.endswith('C'):
oozie_job = get_job(job_id, **kwargs)
else:
oozie_job = get_job(job_id)
except RestException, ex:
msg = _("Error accessing Oozie job %s.") % (job_id,)
LOG.exception(msg)
raise PopupException(msg, detail=ex._headers['oozie-error-message', ''])
if request.user.is_superuser \
or oozie_job.user == request.user.username \
or has_dashboard_jobs_access(request.user):
return oozie_job
else:
message = _("Permission denied. %(username)s does not have the permissions to access job %(id)s.") % \
{'username': request.user.username, 'id': oozie_job.id}
access_warn(request, message)
raise PopupException(message)
def check_job_edition_permission(oozie_job, user):
if has_job_edition_permission(oozie_job, user):
return oozie_job
else:
message = _("Permission denied. %(username)s does not have the permissions to modify job %(id)s.") % \
{'username': user.username, 'id': oozie_job.id}
raise PopupException(message)
def has_job_edition_permission(oozie_job, user):
return user.is_superuser or oozie_job.user == user.username
def has_dashboard_jobs_access(user):
return user.is_superuser or user.has_hue_permission(action="dashboard_jobs_access", app=DJANGO_APPS[0])
|
MobinRanjbar/hue
|
apps/oozie/src/oozie/views/dashboard.py
|
Python
|
apache-2.0
| 44,447
|
package me.bttb.crs.model;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="Dali", date="2016-04-24T22:49:20.423+0300")
@StaticMetamodel(Dctr.class)
public class Dctr_ extends Usr_ {
public static volatile SingularAttribute<Dctr, String> dctrMainSpec;
public static volatile SingularAttribute<Dctr, String> dctrSubSpec;
}
|
alibttb/CRS
|
src/me/bttb/crs/model/Dctr_.java
|
Java
|
apache-2.0
| 436
|
# Seriliodinium G.L. Eaton, 1996 GENUS
#### Status
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
Rev Palaeobot Palynol 91 (1-4), March: 152.
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Protozoa/Dinophyta/Dinophyceae/Seriliodinium/README.md
|
Markdown
|
apache-2.0
| 233
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.language.simple.ast;
import org.apache.camel.Expression;
import org.apache.camel.builder.ExpressionBuilder;
import org.apache.camel.language.simple.types.SimpleParserException;
import org.apache.camel.language.simple.types.SimpleToken;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.OgnlHelper;
import org.apache.camel.util.StringHelper;
/**
* Represents one of built-in functions of the
* <a href="http://camel.apache.org/simple.html">simple language</a>
*/
public class SimpleFunctionExpression extends LiteralExpression {
public SimpleFunctionExpression(SimpleToken token) {
super(token);
}
@Override
public Expression createExpression(String expression) {
String function = text.toString();
return createSimpleExpression(function, true);
}
/**
* Creates a Camel {@link Expression} based on this model.
*
* @param expression the input string
* @param strict whether to throw exception if the expression was not a function,
* otherwise <tt>null</tt> is returned
* @return the created {@link Expression}
* @throws org.apache.camel.language.simple.types.SimpleParserException
* should be thrown if error parsing the model
*/
public Expression createExpression(String expression, boolean strict) {
String function = text.toString();
return createSimpleExpression(function, strict);
}
private Expression createSimpleExpression(String function, boolean strict) {
// return the function directly if we can create function without analyzing the prefix
Expression answer = createSimpleExpressionDirectly(function);
if (answer != null) {
return answer;
}
// bodyAs
String remainder = ifStartsWithReturnRemainder("bodyAs", function);
if (remainder != null) {
String type = ObjectHelper.between(remainder, "(", ")");
if (type == null) {
throw new SimpleParserException("Valid syntax: ${bodyAs(type)} was: " + function, token.getIndex());
}
type = StringHelper.removeQuotes(type);
return ExpressionBuilder.bodyExpression(type);
}
// mandatoryBodyAs
remainder = ifStartsWithReturnRemainder("mandatoryBodyAs", function);
if (remainder != null) {
String type = ObjectHelper.between(remainder, "(", ")");
if (type == null) {
throw new SimpleParserException("Valid syntax: ${mandatoryBodyAs(type)} was: " + function, token.getIndex());
}
type = StringHelper.removeQuotes(type);
return ExpressionBuilder.mandatoryBodyExpression(type);
}
// body OGNL
remainder = ifStartsWithReturnRemainder("body", function);
if (remainder == null) {
remainder = ifStartsWithReturnRemainder("in.body", function);
}
if (remainder != null) {
boolean invalid = OgnlHelper.isInvalidValidOgnlExpression(remainder);
if (invalid) {
throw new SimpleParserException("Valid syntax: ${body.OGNL} was: " + function, token.getIndex());
}
return ExpressionBuilder.bodyOgnlExpression(remainder);
}
// Exception OGNL
remainder = ifStartsWithReturnRemainder("exception", function);
if (remainder != null) {
boolean invalid = OgnlHelper.isInvalidValidOgnlExpression(remainder);
if (invalid) {
throw new SimpleParserException("Valid syntax: ${exception.OGNL} was: " + function, token.getIndex());
}
return ExpressionBuilder.exchangeExceptionOgnlExpression(remainder);
}
// headerAs
remainder = ifStartsWithReturnRemainder("headerAs", function);
if (remainder != null) {
String keyAndType = ObjectHelper.between(remainder, "(", ")");
if (keyAndType == null) {
throw new SimpleParserException("Valid syntax: ${headerAs(key, type)} was: " + function, token.getIndex());
}
String key = ObjectHelper.before(keyAndType, ",");
String type = ObjectHelper.after(keyAndType, ",");
if (ObjectHelper.isEmpty(key) || ObjectHelper.isEmpty(type)) {
throw new SimpleParserException("Valid syntax: ${headerAs(key, type)} was: " + function, token.getIndex());
}
key = StringHelper.removeQuotes(key);
type = StringHelper.removeQuotes(type);
return ExpressionBuilder.headerExpression(key, type);
}
// headers function
if ("in.headers".equals(function) || "headers".equals(function)) {
return ExpressionBuilder.headersExpression();
}
// in header function
remainder = ifStartsWithReturnRemainder("in.headers", function);
if (remainder == null) {
remainder = ifStartsWithReturnRemainder("in.header", function);
}
if (remainder == null) {
remainder = ifStartsWithReturnRemainder("headers", function);
}
if (remainder == null) {
remainder = ifStartsWithReturnRemainder("header", function);
}
if (remainder != null) {
// remove leading character (dot or ?)
remainder = remainder.substring(1);
// validate syntax
boolean invalid = OgnlHelper.isInvalidValidOgnlExpression(remainder);
if (invalid) {
throw new SimpleParserException("Valid syntax: ${header.name[key]} was: " + function, token.getIndex());
}
if (OgnlHelper.isValidOgnlExpression(remainder)) {
// ognl based header
return ExpressionBuilder.headersOgnlExpression(remainder);
} else {
// regular header
return ExpressionBuilder.headerExpression(remainder);
}
}
// out header function
remainder = ifStartsWithReturnRemainder("out.header.", function);
if (remainder == null) {
remainder = ifStartsWithReturnRemainder("out.headers.", function);
}
if (remainder != null) {
return ExpressionBuilder.outHeaderExpression(remainder);
}
// property
remainder = ifStartsWithReturnRemainder("property", function);
if (remainder != null) {
// remove leading character (dot or ?)
remainder = remainder.substring(1);
// validate syntax
boolean invalid = OgnlHelper.isInvalidValidOgnlExpression(remainder);
if (invalid) {
throw new SimpleParserException("Valid syntax: ${property.OGNL} was: " + function, token.getIndex());
}
if (OgnlHelper.isValidOgnlExpression(remainder)) {
// ognl based property
return ExpressionBuilder.propertyOgnlExpression(remainder);
} else {
// regular property
return ExpressionBuilder.propertyExpression(remainder);
}
}
// system property
remainder = ifStartsWithReturnRemainder("sys.", function);
if (remainder != null) {
return ExpressionBuilder.systemPropertyExpression(remainder);
}
// system property
remainder = ifStartsWithReturnRemainder("sysenv.", function);
if (remainder != null) {
return ExpressionBuilder.systemEnvironmentExpression(remainder);
}
// file: prefix
remainder = ifStartsWithReturnRemainder("file:", function);
if (remainder != null) {
Expression fileExpression = createSimpleFileExpression(remainder);
if (function != null) {
return fileExpression;
}
}
// date: prefix
remainder = ifStartsWithReturnRemainder("date:", function);
if (remainder != null) {
String[] parts = remainder.split(":");
if (parts.length < 2) {
throw new SimpleParserException("Valid syntax: ${date:command:pattern} was: " + function, token.getIndex());
}
String command = ObjectHelper.before(remainder, ":");
String pattern = ObjectHelper.after(remainder, ":");
return ExpressionBuilder.dateExpression(command, pattern);
}
// bean: prefix
remainder = ifStartsWithReturnRemainder("bean:", function);
if (remainder != null) {
return ExpressionBuilder.beanExpression(remainder);
}
// properties: prefix
remainder = ifStartsWithReturnRemainder("properties:", function);
if (remainder != null) {
String[] parts = remainder.split(":");
if (parts.length > 2) {
throw new SimpleParserException("Valid syntax: ${properties:[locations]:key} was: " + function, token.getIndex());
}
String locations = null;
String key = remainder;
if (parts.length == 2) {
locations = ObjectHelper.before(remainder, ":");
key = ObjectHelper.after(remainder, ":");
}
return ExpressionBuilder.propertiesComponentExpression(key, locations);
}
// ref: prefix
remainder = ifStartsWithReturnRemainder("ref:", function);
if (remainder != null) {
return ExpressionBuilder.refExpression(remainder);
}
if (strict) {
throw new SimpleParserException("Unknown function: " + function, token.getIndex());
} else {
return null;
}
}
private Expression createSimpleExpressionDirectly(String expression) {
if (ObjectHelper.isEqualToAny(expression, "body", "in.body")) {
return ExpressionBuilder.bodyExpression();
} else if (ObjectHelper.equal(expression, "out.body")) {
return ExpressionBuilder.outBodyExpression();
} else if (ObjectHelper.equal(expression, "id")) {
return ExpressionBuilder.messageIdExpression();
} else if (ObjectHelper.equal(expression, "exchangeId")) {
return ExpressionBuilder.exchangeIdExpression();
} else if (ObjectHelper.equal(expression, "exception")) {
return ExpressionBuilder.exchangeExceptionExpression();
} else if (ObjectHelper.equal(expression, "exception.message")) {
return ExpressionBuilder.exchangeExceptionMessageExpression();
} else if (ObjectHelper.equal(expression, "exception.stacktrace")) {
return ExpressionBuilder.exchangeExceptionStackTraceExpression();
} else if (ObjectHelper.equal(expression, "threadName")) {
return ExpressionBuilder.threadNameExpression();
}
return null;
}
private Expression createSimpleFileExpression(String remainder) {
if (ObjectHelper.equal(remainder, "name")) {
return ExpressionBuilder.fileNameExpression();
} else if (ObjectHelper.equal(remainder, "name.noext")) {
return ExpressionBuilder.fileNameNoExtensionExpression();
} else if (ObjectHelper.equal(remainder, "name.ext")) {
return ExpressionBuilder.fileExtensionExpression();
} else if (ObjectHelper.equal(remainder, "onlyname")) {
return ExpressionBuilder.fileOnlyNameExpression();
} else if (ObjectHelper.equal(remainder, "onlyname.noext")) {
return ExpressionBuilder.fileOnlyNameNoExtensionExpression();
} else if (ObjectHelper.equal(remainder, "ext")) {
return ExpressionBuilder.fileExtensionExpression();
} else if (ObjectHelper.equal(remainder, "parent")) {
return ExpressionBuilder.fileParentExpression();
} else if (ObjectHelper.equal(remainder, "path")) {
return ExpressionBuilder.filePathExpression();
} else if (ObjectHelper.equal(remainder, "absolute")) {
return ExpressionBuilder.fileAbsoluteExpression();
} else if (ObjectHelper.equal(remainder, "absolute.path")) {
return ExpressionBuilder.fileAbsolutePathExpression();
} else if (ObjectHelper.equal(remainder, "length") || ObjectHelper.equal(remainder, "size")) {
return ExpressionBuilder.fileSizeExpression();
} else if (ObjectHelper.equal(remainder, "modified")) {
return ExpressionBuilder.fileLastModifiedExpression();
}
throw new SimpleParserException("Unknown file language syntax: " + remainder, token.getIndex());
}
private String ifStartsWithReturnRemainder(String prefix, String text) {
if (text.startsWith(prefix)) {
String remainder = text.substring(prefix.length());
if (remainder.length() > 0) {
return remainder;
}
}
return null;
}
}
|
cexbrayat/camel
|
camel-core/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionExpression.java
|
Java
|
apache-2.0
| 13,859
|
/**
* Copyright 2015-2016 Kakao Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "KOSessionTask.h"
#import "KOTalkProfile.h"
#import "KOChatContext.h"
#import "KOUser.h"
#import "KOChat.h"
#import "KOFriend.h"
/*!
@header KOSessionTask+TalkAPI.h
인증된 session 정보를 바탕으로 각종 카카오톡 API를 호출할 수 있습니다.
*/
/*!
@abstract KOTalkMessageReceiverType
@constant KOTalkMessageReceiverTypeUser
@constant KOTalkMessageReceiverTypeFriend
@constant KOTalkMessageReceiverTypeChat
*/
typedef NS_ENUM(NSInteger, KOTalkMessageReceiverType) {
KOTalkMessageReceiverTypeUser = 0,
KOTalkMessageReceiverTypeFriend,
KOTalkMessageReceiverTypeChat
};
/*!
인증된 session 정보를 바탕으로 각종 카카오톡 API를 호출할 수 있습니다.
*/
@interface KOSessionTask (TalkAPI)
#pragma mark - KakaoTalk
/*!
@abstract 현재 로그인된 사용자의 카카오톡 프로필 정보를 얻을 수 있습니다.
@param completionHandler 카카오톡 프로필 정보를 얻어 처리하는 핸들러
*/
+ (instancetype)talkProfileTaskWithCompletionHandler:(KOSessionTaskCompletionHandler)completionHandler;
/*!
@abstract 현재 로그인된 사용자의 카카오톡 프로필 정보를 얻을 수 있습니다.
@param secureResource 프로필, 썸네일 이미지 등의 리소스 정보들에 대해 https를 지원하는 형식으로 응답을 받을지의 여부. YES일 경우 https지원, NO일 경우 http지원.
@param completionHandler 카카오톡 프로필 정보를 얻어 처리하는 핸들러
*/
+ (instancetype)talkProfileTaskWithSecureResource:(BOOL)secureResource
completionHandler:(KOSessionTaskCompletionHandler)completionHandler;
/*!
@abstract 미리 지정된 Template Message를 사용하여, 카카오톡으로 메시지를 전송합니다. 제휴를 통해 권한이 부여된 특정 앱에서만 호출 가능합니다.
@param templateID 미리 지정된 템플릿 메시지 ID.
@param user 이 메시지를 수신할 User.
@param messageArguments 템플릿 메시지를 만들 때, 채워줘야할 파라미터들.
@param completionHandler 요청 완료시 실행될 block. 오류 처리와 전송 완료 시 수행된다.
*/
+ (instancetype)talkSendMessageTaskWithTemplateID:(NSString *)templateID
receiverUser:(KOUserInfo *)user
messageArguments:(NSDictionary *)messageArguments
completionHandler:(void (^)(NSError *error))completionHandler;
/*!
@abstract 미리 지정된 Template Message를 사용하여, 카카오톡으로 메시지를 전송합니다. 제휴를 통해 권한이 부여된 특정 앱에서만 호출 가능합니다.<br>
@param templateID 미리 지정된 템플릿 메시지 ID.
@param receiverFriend 이 메시지를 수신할 친구.
@param messageArguments 템플릿 메시지를 만들 때, 채워줘야할 파라미터들.
@param completionHandler 요청 완료시 실행될 block. 오류 처리와 전송 완료 시 수행된다.
*/
+ (instancetype)talkSendMessageTaskWithTemplateID:(NSString *)templateID
receiverFriend:(KOFriend *)receiverFriend
messageArguments:(NSDictionary *)messageArguments
completionHandler:(void (^)(NSError *error))completionHandler DEPRECATED_MSG_ATTRIBUTE("Use talkSendMessageTaskWithTemplateID:receiverUser:messageArguments:completionHandler in v1.0.46");
/*!
@abstract 미리 지정된 Template Message를 사용하여, 카카오톡으로 메시지를 전송합니다. 제휴를 통해 권한이 부여된 특정 앱에서만 호출 가능합니다.
@param templateID 미리 지정된 템플릿 메시지 ID.
@param receiverChat 이 메시지를 수신할 채팅방.
@param messageArguments 템플릿 메시지를 만들 때, 채워줘야할 파라미터들.
@param completionHandler 요청 완료시 실행될 block. 오류 처리와 전송 완료 시 수행된다.
*/
+ (instancetype)talkSendMessageTaskWithTemplateID:(NSString *)templateID
receiverChat:(KOChat *)receiverChat
messageArguments:(NSDictionary *)messageArguments
completionHandler:(void (^)(NSError *error))completionHandler;
/*!
@abstract 카카오톡 채팅방 목록을 가져옵니다. 제휴를 통해 권한이 부여된 특정 앱에서만 호출 가능합니다.
@param context 채팅방 목록을 불러올 때, 페이징 정보를 처리하기 위한 context.
@param completionHandler 카카오톡 채팅방 목록을 가져와서 처리하는 핸들러.
*/
+ (instancetype)talkChatListTaskWithContext:(KOChatContext *)context
completionHandler:(void (^)(NSArray *chats, NSError *error))completionHandler;
/*!
@abstract 미리 지정된 Message Template을 사용하여, 카카오톡의 "나와의 채팅방"으로 메시지를 전송합니다. 모든 앱에서 호출 가능합니다.
@param templateID 개발자 사이트를 통해 생성한 메시지 템플릿 id
@param messageArguments 메시지 템플릿에 정의한 키/밸류의 파라미터들. 템플릿에 정의된 모든 파라미터가 포함되어야 합니다.
@param completionHandler 요청 완료시 실행될 block. 오류 처리와 전송 완료 시 수행된다.
*/
+ (instancetype)talkSendMemoTaskWithTemplateID:(NSString *)templateID
messageArguments:(NSDictionary *)messageArguments
completionHandler:(void (^)(NSError *error))completionHandler;
@end
|
blomcheol/cptest
|
KakaoOpenSDK.framework/Versions/A/Headers/KOSessionTask+TalkAPI.h
|
C
|
apache-2.0
| 6,232
|
#include <iostream>
int main() {
//(a)
//int i, *const cp; // Error: a const pointer must be initialized
//(b)
//int *p1, *const p2; // Error: a const pointer must be initialized
//(c)
//const int ic, &r = ic; // Error: const int `ic` must be initialized
//(d)
//const int *const p3; // Error: a const pointer must be initialized
//(e)
const int *p; // OK
return 0;
}
|
jaege/Cpp-Primer-5th-Exercises
|
ch2/2.28.cpp
|
C++
|
apache-2.0
| 397
|
/**
* Copyright 2011 meltmedia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.xchain.test.component;
import org.xchain.annotations.Component;
/**
* A component which extends a parent class with a method based dependency injection.
* @author Devon Tackett
*/
@Component(localName="child-method-component")
public class ChildMethodComponent
extends ParentMethodComponent
{
}
|
ctrimble/xchain
|
core/src/test/java/org/xchain/test/component/ChildMethodComponent.java
|
Java
|
apache-2.0
| 939
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_111) on Wed Jan 04 22:31:17 EST 2017 -->
<title>StaticContinuousOptimalTrajectory</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="StaticContinuousOptimalTrajectory";
}
}
catch(err) {
}
//-->
var methods = {"i0":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/StaticContinuousOptimalTrajectory.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/drip/sample/almgren2009/LowUrgencyTrajectoryComparison.html" title="class in org.drip.sample.almgren2009"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/sample/almgren2009/StaticContinuousOptimalTrajectory.html" target="_top">Frames</a></li>
<li><a href="StaticContinuousOptimalTrajectory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.drip.sample.almgren2009</div>
<h2 title="Class StaticContinuousOptimalTrajectory" class="title">Class StaticContinuousOptimalTrajectory</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.drip.sample.almgren2009.StaticContinuousOptimalTrajectory</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">StaticContinuousOptimalTrajectory</span>
extends java.lang.Object</pre>
<div class="block">StaticContinuousOptimalTrajectory demonstrates the Generation and Usage of Continuous Version of the
Discrete Trading Trajectory generated by the Almgren and Chriss (2000) Scheme under the Criterion of
No-Drift. The References are:
- Almgren, R. F., and N. Chriss (2000): Optimal Execution of Portfolio Transactions, Journal of Risk 3
(2) 5-39.
- Almgren, R. F. (2009): Optimal Trading in a Dynamic Market
https://www.math.nyu.edu/financial_mathematics/content/02_financial/2009-2.pdf.
- Almgren, R. F. (2012): Optimal Trading with Stochastic Liquidity and Volatility, SIAM Journal of
Financial Mathematics 3 (1) 163-181.
- Geman, H., D. B. Madan, and M. Yor (2001): Time Changes for Levy Processes, Mathematical Finance 11 (1)
79-96.
- Walia, N. (2006): Optimal Trading: Dynamic Stock Liquidation Strategies, Senior Thesis, Princeton
University.</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Lakshmi Krishnamurthy</dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/drip/sample/almgren2009/StaticContinuousOptimalTrajectory.html#StaticContinuousOptimalTrajectory--">StaticContinuousOptimalTrajectory</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/drip/sample/almgren2009/StaticContinuousOptimalTrajectory.html#main-java.lang.String:A-">main</a></span>(java.lang.String[] astrArgs)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="StaticContinuousOptimalTrajectory--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>StaticContinuousOptimalTrajectory</h4>
<pre>public StaticContinuousOptimalTrajectory()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="main-java.lang.String:A-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>main</h4>
<pre>public static void main(java.lang.String[] astrArgs)
throws java.lang.Exception</pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.Exception</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/StaticContinuousOptimalTrajectory.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/drip/sample/almgren2009/LowUrgencyTrajectoryComparison.html" title="class in org.drip.sample.almgren2009"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/drip/sample/almgren2009/StaticContinuousOptimalTrajectory.html" target="_top">Frames</a></li>
<li><a href="StaticContinuousOptimalTrajectory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
lakshmiDRIP/DRIP
|
Javadoc/org/drip/sample/almgren2009/StaticContinuousOptimalTrajectory.html
|
HTML
|
apache-2.0
| 10,600
|
package cn.aezo.demo.jackson.bean;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(MyPropertyNamingStrategy.class)
public class HobbyBean {
private String hobby;
private int index;
public HobbyBean() {
}
public HobbyBean(String hobby, int index) {
super();
this.hobby = hobby;
this.index = index;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
@Override
public String toString() {
return this.hobby;
}
}
|
oldinaction/smjava
|
demo/src/test/java/cn/aezo/demo/jackson/bean/HobbyBean.java
|
Java
|
apache-2.0
| 723
|
package com.kilobolt.ZombieBird.client;
import com.badbears.ZombieBird.ZBGame;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
public class GwtLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
GwtApplicationConfiguration cfg = new GwtApplicationConfiguration(1080/4, 1020/4);
return cfg;
}
@Override
public ApplicationListener getApplicationListener () {
return new ZBGame();
}
}
|
zlemisie/KolejDlaBielawy
|
ZombieBird-html/src/com/kilobolt/ZombieBird/client/GwtLauncher.java
|
Java
|
apache-2.0
| 572
|
# QuestionnaireTemplateFiltersModel
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **int[]** | QuestionnaireTemplate id's | [optional]
**tag_names** | **string[]** | Tag names | [optional]
**zone_names** | **string[]** | Zone names | [optional]
**link** | **object[]** | Activity Link ids | [optional]
**links** | **object[]** | Activity Link ids | [optional]
**search_text** | **string** | free search through text and numeric type columns | [optional]
**zone_id** | **int** | Zone ID | [optional]
**brand_id** | **int** | Brand ID | [optional]
**updated_at_since** | [**\DateTime**](\DateTime.md) | Show updated since | [optional]
**updated_at_till** | [**\DateTime**](\DateTime.md) | Show updated till | [optional]
**questionnaire_type_name** | **object** | Questionnaire type name | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
freightlive/bumbal-client-api-php
|
docs/Model/QuestionnaireTemplateFiltersModel.md
|
Markdown
|
apache-2.0
| 1,050
|
<!doctype html>
<html>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- content security for android -->
<!-- look here: http://stackoverflow.com/questions/30212306/no-content-security-policy-meta-tag-found-error-in-my-phonegap-application -->
<meta http-equiv="Content-Security-Policy" content="default-src * data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; script-src * 'unsafe-inline';">
<title>NewsCanary</title>
<link href="aboutPageStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
<!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
<script>var __adobewebfontsappname__="dreamweaver"</script><script src="http://use.edgefonts.net/montserrat:n4:default;source-sans-pro:n2:default.js" type="text/javascript"></script>
</head>
<body>
<!-- Header content -->
<header>
<div class="profileLogo">
<p class="logoPlaceholder"><!-- <img src="logoImage.png" alt="sample logo"> --><span>NewsCanary</span></p>
</div>
<div class="profilePhoto">
<!-- Profile photo -->
<img src="images/News-Briefs.png" alt="news globe" class="globe"> </div>
<!-- Identity details -->
<section class="profileHeader">
<h3>Welcome to NewsCanary for all your latest news and weather updates.</h3>
<hr>
<p><br />Please <a href="login.html">Log In</a> Here<br />
<br />Not already a member?<br />
<br /><a href="register.html"> Sign Up Here!</a></p>
</section>
</header>
<footer>
<hr>
<p class="footerDisclaimer">2016 Copyrights - <span>All Rights Reserved</span></p>
</footer>
</body>
</html>
</html>
|
suethomas1/NewsCanary-rssfeed
|
index.html
|
HTML
|
apache-2.0
| 1,983
|
# Binghamia olowinskiana (Backeb.) W.T.Marshall SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Binghamia/Binghamia olowinskiana/README.md
|
Markdown
|
apache-2.0
| 195
|
# Erigeron welwitschii Hiern SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Felicia welwitschii/ Syn. Erigeron welwitschii/README.md
|
Markdown
|
apache-2.0
| 183
|
/*++
Module Name:
MultiInputReadSupplier.cp
Abstract:
A read supplier that combines other read suppliers. It's used when there are muliple input files to process.
Authors:
Bill Bolosky, November, 2012
Environment:
User mode service.
Revision History:
--*/
#include "stdafx.h"
#include <map>
#include "Compat.h"
#include "Util.h"
#include "Read.h"
#include "DataReader.h"
#include "VariableSizeMap.h"
// turn on to debug matching process
//#define VALIDATE_MATCH
using std::pair;
class PairedReadMatcher: public PairedReadReader
{
public:
PairedReadMatcher(ReadReader* i_single, bool i_autoRelease);
// PairedReadReader
virtual ~PairedReadMatcher();
virtual bool getNextReadPair(Read *read1, Read *read2);
virtual void reinit(_int64 startingOffset, _int64 amountOfFileToProcess)
{ single->reinit(startingOffset, amountOfFileToProcess); }
void releaseBatch(DataBatch batch);
private:
const bool autoRelease;
ReadReader* single; // reader for single reads
typedef _uint64 StringHash;
typedef VariableSizeMap<StringHash,Read> ReadMap;
DataBatch batch[2]; // 0 = current, 1 = previous
bool releasedBatch[2]; // whether each batch has been released
ReadMap unmatched[2]; // read id -> Read
typedef VariableSizeMap<StringHash,ReadWithOwnMemory> OverflowMap;
OverflowMap overflow; // read id -> Read
#ifdef VALIDATE_MATCH
typedef VariableSizeMap<StringHash,char*> StringMap;
StringMap strings;
typedef VariableSizeMap<StringHash,int> HashSet;
HashSet overflowUsed;
#endif
_int64 overflowMatched;
// used only if ! autoRelease:
bool dependents; // true if pairs from 0->1
// manage inter-batch dependencies
// newer depends on older (i.e. only release older after newer)
// erase forward if older released first
// erase both if newer released first
ExclusiveLock lock; // exclusive access to forward/backward
typedef VariableSizeMap<DataBatch::Key,DataBatch> BatchMap;
BatchMap forward; // dependencies from older batch (was unmatched) -> newer batch
BatchMap backward; // newer batch -> older batch
};
PairedReadMatcher::PairedReadMatcher(
ReadReader* i_single,
bool i_autoRelease)
: single(i_single),
forward(),
backward(),
dependents(false),
autoRelease(i_autoRelease),
overflowMatched(0)
{
unmatched[0] = VariableSizeMap<_uint64,Read>(10000);
unmatched[1] = VariableSizeMap<_uint64,Read>(10000);
releasedBatch[0] = releasedBatch[1] = false;
if (! autoRelease) {
InitializeExclusiveLock(&lock);
}
}
PairedReadMatcher::~PairedReadMatcher()
{
if (! autoRelease) {
DestroyExclusiveLock(&lock);
}
delete single;
}
bool
PairedReadMatcher::getNextReadPair(
Read *read1,
Read *read2)
{
int skipped = 0;
while (true) {
if (skipped++ == 10000) {
fprintf(stderr, "warning: no matching read pairs in 10,000 reads, input file might be unsorted or have unexpected read id format\n");
}
Read one;
if (! single->getNextRead(&one)) {
int n = unmatched[0].size() + unmatched[1].size();
int n2 = (int) (overflow.size() - overflowMatched);
if (n + n2 > 0) {
fprintf(stderr, " warning: PairedReadMatcher discarding %d+%d unpaired reads at eof\n", n, n2);
#ifdef VALIDATE_MATCH
for (int i = 0; i < 2; i++) {
fprintf(stdout, "unmatched[%d]\n", i);
for (ReadMap::iterator j = unmatched[i].begin(); j != unmatched[i].end(); j = unmatched[i].next(j)) {
fprintf(stdout, "%s\n", strings[j->key]);
}
}
int printed = 0;
fprintf(stdout, "sample of overflow\n");
for (OverflowMap::iterator o = overflow.begin(); printed < 500 && o != overflow.end(); o = overflow.next(o)) {
if (NULL == overflowUsed.tryFind(o->key)) {
printed++;
fprintf(stdout, "%s\n", strings[o->key]);
}
}
#endif
}
return false;
}
// build key for pending read table, removing /1 or /2 at end
const char* id = one.getId();
unsigned idLength = one.getIdLength();
// truncate at space or slash
char* slash = (char*) memchr((void*)id, '/', idLength);
if (slash != NULL) {
idLength = (unsigned)(slash - id);
}
char* space = (char*) memchr((void*)id, ' ', idLength);
if (space != NULL) {
idLength = (unsigned)(space - id);
}
StringHash key = util::hash64(id, idLength);
#ifdef VALIDATE_MATCH
char* s = new char[idLength+1];
memcpy(s, id, idLength);
s[idLength] = 0;
char** p = strings.tryFind(key);
if (p != NULL && strcmp(*p, s)) {
fprintf(stderr, "hash collision %ld of %s and %s\n", key, *p, s);
soft_exit(1);
}
if (p == NULL) {
strings.put(key, s);
}
#endif
if (one.getBatch() != batch[0]) {
// roll over batches
if (unmatched[1].size() > 0) {
//printf("warning: PairedReadMatcher overflow %d unpaired reads from %d:%d\n", unmatched[1].size(), batch[1].fileID, batch[1].batchID); //!!
//char* buf = (char*) alloca(500);
for (ReadMap::iterator r = unmatched[1].begin(); r != unmatched[1].end(); r = unmatched[1].next(r)) {
overflow.put(r->key, ReadWithOwnMemory(r->value));
#ifdef VALIDATE_MATCH
char*s2 = *strings.tryFind(r->key);
int len = strlen(s2);
_ASSERT(! strncmp(s2, r->value.getId(), len));
ReadWithOwnMemory* rd = overflow.tryFind(r->key);
_ASSERT(! strncmp(s2, rd->getId(), len));
#endif
//memcpy(buf, r->value.getId(), r->value.getIdLength());
//buf[r->value.getIdLength()] = 0;
//printf("overflow add %d:%d %s\n", batch[1].fileID, batch[1].batchID, buf);
}
}
for (ReadMap::iterator i = unmatched[1].begin(); i != unmatched[1].end(); i = unmatched[1].next(i)) {
i->value.dispose();
}
unmatched[1].clear();
unmatched[1] = unmatched[0];
unmatched[0].clear();
if (autoRelease) {
single->releaseBatch(batch[1]);
}
DataBatch overflowBatch = batch[1];
batch[1] = batch[0];
bool releaseOverflowBatch = releasedBatch[1];
releasedBatch[1] = releasedBatch[0];
batch[0] = one.getBatch();
releasedBatch[0] = false;
dependents = false;
if (releaseOverflowBatch && ! autoRelease) {
//printf("release deferred batch %d:%d\n", overflowBatch.fileID, overflowBatch.batchID);
releaseBatch(overflowBatch);
}
}
ReadMap::iterator found = unmatched[0].find(key);
if (found != unmatched[0].end()) {
*read2 = found->value;
//printf("current matched %d:%d->%d:%d %s\n", read2->getBatch().fileID, read2->getBatch().batchID, batch[0].fileID, batch[0].batchID, read2->getId()); //!!
unmatched[0].erase(found->key);
} else {
// try previous batch
found = unmatched[1].find(key);
if (found == unmatched[1].end()) {
// try overflow
OverflowMap::iterator found2 = overflow.find(key);
if (found2 == overflow.end()) {
// no match, remember it for later matching
unmatched[0].put(key, one);
//printf("unmatched add %d:%d %lx\n", batch[0].fileID, batch[0].batchID, key); //!!
continue;
} else {
// copy data into read, keep in overflow table indefinitely to preserve memory
*read2 = * (Read*) &found2->value;
_ASSERT(read2->getData()[0]);
overflowMatched++;
#ifdef VALIDATE_MATCH
overflowUsed.put(key, 1);
#endif
//printf("overflow matched %d:%d %s\n", read2->getBatch().fileID, read2->getBatch().batchID, read2->getId()); //!!
read2->setBatch(batch[0]); // overwrite batch so both reads have same batch, will track deps instead
}
} else {
// found, remember dependency
if ((! autoRelease) && (! dependents)) {
dependents = true;
AcquireExclusiveLock(&lock);
//printf("add dependency %d:%d->%d:%d\n", batch[0].fileID, batch[0].batchID, batch[1].fileID, batch[1].batchID);
forward.put(batch[1].asKey(), batch[0]);
backward.put(batch[0].asKey(), batch[1]);
ReleaseExclusiveLock(&lock);
}
*read2 = found->value;
//printf("prior matched %d:%d->%d:%d %s\n", read2->getBatch().fileID, read2->getBatch().batchID, batch[0].fileID, batch[0].batchID, read2->getId()); //!!
read2->setBatch(batch[0]); // overwrite batch so both reads have same batch, will track deps instead
unmatched[1].erase(found->key);
}
}
// found a match
*read1 = one;
return true;
}
}
void
PairedReadMatcher::releaseBatch(
DataBatch batch)
{
if (autoRelease) {
return;
}
for (int i = 0; i < 2; i++) {
if (batch == this->batch[i]) {
if (! releasedBatch[i]) {
releasedBatch[i] = true;
//printf("releaseBatch %d:%d active %d, deferred\n", batch.fileID, batch.batchID, i);
}
return;
}
}
// only release when both forward & backward dependent batches have been released
AcquireExclusiveLock(&lock);
DataBatch::Key key = batch.asKey();
// case in which i'm the newer batch
DataBatch* b = backward.tryFind(key);
if (b != NULL) {
DataBatch* bf = forward.tryFind(b->asKey());
if (bf == NULL) {
// batch I depend on already released, can release it now
//printf("release older batch %d:%d->%d:%d\n", batch.fileID, batch.batchID, b->fileID, b->batchID);
single->releaseBatch(*b);
} else {
// forget dependency so older batch can be released later
//printf("forget newer batch dependency %d:%d->%d:%d\n", batch.fileID, batch.batchID, b->fileID, b->batchID);
forward.erase(b->asKey());
}
backward.erase(key);
}
// case in which I'm the older batch
DataBatch* f = forward.tryFind(key);
if (f != NULL) {
// someone depends on me, signal that I've been released
//printf("keep older batch %d:%d->%d:%d\n", f->fileID, f->batchID, batch.fileID, batch.batchID);
forward.erase(key);
} else {
// noone depends on me, I can be released
//printf("release independent batch %d:%d\n", batch.fileID, batch.batchID);
single->releaseBatch(batch);
}
ReleaseExclusiveLock(&lock);
}
// define static factory function
PairedReadReader*
PairedReadReader::PairMatcher(
ReadReader* single,
bool autoRelease)
{
return new PairedReadMatcher(single, autoRelease);
}
|
PriceLab/snapr
|
SNAPLib/PairedReadMatcher.cpp
|
C++
|
apache-2.0
| 11,639
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "REDACTEDsubmissions/training/v0_7/models/prod/minigo/cc/model/inference_cache.h"
#include <tuple>
#include "REDACTEDmemory/memory.h"
namespace minigo {
std::ostream& operator<<(std::ostream& os, InferenceCache::Key key) {
return os << absl::StreamFormat("%016x:%016x", key.cache_hash_,
key.stone_hash_);
}
InferenceCache::Key InferenceCache::Key::CreateTestKey(
zobrist::Hash cache_hash, zobrist::Hash stone_hash) {
InferenceCache::Key key;
key.cache_hash_ = cache_hash;
key.stone_hash_ = stone_hash;
return key;
}
InferenceCache::Key::Key(Coord prev_move, symmetry::Symmetry canonical_sym,
const Position& position) {
cache_hash_ ^= zobrist::ToPlayHash(position.to_play());
if (prev_move == Coord::kPass) {
cache_hash_ ^= zobrist::OpponentPassedHash();
}
const auto& coord_symmetry = symmetry::kCoords[canonical_sym];
const auto& stones = position.stones();
for (int real_c = 0; real_c < kN * kN; ++real_c) {
auto symmetric_c = coord_symmetry[real_c];
auto h = zobrist::MoveHash(symmetric_c, stones[real_c].color());
stone_hash_ ^= h;
cache_hash_ ^= h;
if (stones[real_c].color() == Color::kEmpty &&
!position.legal_move(real_c)) {
cache_hash_ ^= zobrist::IllegalEmptyPointHash(symmetric_c);
}
}
}
InferenceCache::~InferenceCache() = default;
std::ostream& operator<<(std::ostream& os, const InferenceCache::Stats& stats) {
auto num_lookups =
stats.num_hits + stats.num_complete_misses + stats.num_symmetry_misses;
auto hit_rate =
static_cast<float>(stats.num_hits) / static_cast<float>(num_lookups);
auto full =
static_cast<float>(stats.size) / static_cast<float>(stats.capacity);
return os << "size:" << stats.size << " capacity:" << stats.capacity
<< " full:" << (100 * full) << "%"
<< " hits:" << stats.num_hits
<< " complete_misses:" << stats.num_complete_misses
<< " symmetry_misses:" << stats.num_symmetry_misses
<< " hit_rate:" << (100 * hit_rate) << "%";
}
void NullInferenceCache::Clear() {}
void NullInferenceCache::Merge(Key key, symmetry::Symmetry canonical_sym,
symmetry::Symmetry inference_sym,
ModelOutput* output) {}
bool NullInferenceCache::TryGet(Key key, symmetry::Symmetry canonical_sym,
symmetry::Symmetry inference_sym,
ModelOutput* output) {
stats_.num_complete_misses += 1;
return false;
}
InferenceCache::Stats NullInferenceCache::GetStats() const { return stats_; }
size_t BasicInferenceCache::CalculateCapacity(size_t size_mb) {
// Minimum load factory of an absl::node_hash_map at the time of writing,
// taken from https://abseil.io/docs/cpp/guides/container.
// This is a pessimistic estimate of the cache's load factor but since the
// size of each node pointer is much smaller than that of the node itself, it
// shouldn't make that much difference either way.
float load_factor = 0.4375;
// absl::node_hash_map allocates each (key, value) pair on the heap and stores
// pointers to those pairs in the table itself, along with one byte of hash
// for each element.
float element_size =
sizeof(Map::value_type) + (sizeof(Map::value_type*) + 1) / load_factor;
return static_cast<size_t>(size_mb * 1024.0f * 1024.0f / element_size);
}
BasicInferenceCache::BasicInferenceCache(size_t capacity) {
MG_CHECK(capacity > 0);
stats_.capacity = capacity;
Clear();
}
void BasicInferenceCache::Clear() {
// Init the LRU list.
list_.prev = &list_;
list_.next = &list_;
map_.clear();
}
void BasicInferenceCache::Merge(Key key, symmetry::Symmetry canonical_sym,
symmetry::Symmetry inference_sym,
ModelOutput* output) {
if (map_.size() == stats_.capacity) {
// Cache is full, remove the last element from the LRU queue.
auto it = map_.find(static_cast<Element*>(list_.prev)->key);
MG_CHECK(it != map_.end());
Unlink(&it->second);
map_.erase(it);
stats_.size -= 1;
}
// Symmetry that converts the model output into canonical form.
auto inverse_canonical_sym = symmetry::Inverse(canonical_sym);
auto canonical_inference_sym =
symmetry::Concat(inference_sym, inverse_canonical_sym);
int sym_bit = (1 << canonical_inference_sym);
auto result = map_.try_emplace(key, key, canonical_inference_sym);
auto inserted = result.second;
auto* elem = &result.first->second;
if (inserted) {
// Transform the model output into canonical form.
Model::ApplySymmetry(inverse_canonical_sym, *output, &elem->output);
elem->valid_symmetry_bits = sym_bit;
elem->num_valid_symmetries = 1;
stats_.size += 1;
} else {
// The element was already in the cache.
Unlink(elem);
if ((elem->valid_symmetry_bits & sym_bit) == 0) {
const auto& coord_symmetry = symmetry::kCoords[inverse_canonical_sym];
// This is a new symmetry for this key: merge it in.
float n = static_cast<float>(elem->num_valid_symmetries);
float a = n / (n + 1);
float b = 1 / (n + 1);
auto& cached = elem->output;
for (size_t i = 0; i < kNumMoves; ++i) {
cached.policy[i] =
a * cached.policy[i] + b * output->policy[coord_symmetry[i]];
}
cached.value = a * cached.value + b * output->value;
elem->valid_symmetry_bits |= sym_bit;
elem->num_valid_symmetries += 1;
}
Model::ApplySymmetry(canonical_sym, elem->output, output);
}
PushFront(elem);
}
bool BasicInferenceCache::TryGet(Key key, symmetry::Symmetry canonical_sym,
symmetry::Symmetry inference_sym,
ModelOutput* output) {
auto it = map_.find(key);
if (it == map_.end()) {
stats_.num_complete_misses += 1;
return false;
}
auto* elem = &it->second;
Unlink(elem);
PushFront(elem);
// Symmetry that converts the model output into canonical form.
auto inverse_canonical_sym = symmetry::Inverse(canonical_sym);
auto canonical_inference_sym =
symmetry::Concat(inference_sym, inverse_canonical_sym);
int sym_bit = (1 << canonical_inference_sym);
if ((elem->valid_symmetry_bits & sym_bit) == 0) {
// We have some symmetries for this position, just not the one requested.
stats_.num_symmetry_misses += 1;
return false;
}
Model::ApplySymmetry(canonical_sym, elem->output, output);
stats_.num_hits += 1;
return true;
}
BasicInferenceCache::Stats BasicInferenceCache::GetStats() const {
return stats_;
}
ThreadSafeInferenceCache::ThreadSafeInferenceCache(size_t total_capacity,
int num_shards) {
shards_.reserve(num_shards);
size_t shard_capacity_sum = 0;
for (int i = 0; i < num_shards; ++i) {
auto a = i * total_capacity / num_shards;
auto b = (i + 1) * total_capacity / num_shards;
auto shard_capacity = b - a;
shard_capacity_sum += shard_capacity;
shards_.push_back(absl::make_unique<Shard>(shard_capacity));
}
MG_CHECK(shard_capacity_sum == total_capacity);
}
void ThreadSafeInferenceCache::Clear() {
for (auto& shard : shards_) {
absl::MutexLock lock(&shard->mutex);
shard->cache.Clear();
}
}
void ThreadSafeInferenceCache::Merge(Key key, symmetry::Symmetry canonical_sym,
symmetry::Symmetry inference_sym,
ModelOutput* output) {
auto* shard = shards_[key.Shard(shards_.size())].get();
absl::MutexLock lock(&shard->mutex);
shard->cache.Merge(key, canonical_sym, inference_sym, output);
}
bool ThreadSafeInferenceCache::TryGet(Key key, symmetry::Symmetry canonical_sym,
symmetry::Symmetry inference_sym,
ModelOutput* output) {
auto* shard = shards_[key.Shard(shards_.size())].get();
absl::MutexLock lock(&shard->mutex);
return shard->cache.TryGet(key, canonical_sym, inference_sym, output);
}
InferenceCache::Stats ThreadSafeInferenceCache::GetStats() const {
Stats result;
for (auto& shard : shards_) {
absl::MutexLock lock(&shard->mutex);
auto s = shard->cache.GetStats();
result.size += s.size;
result.capacity += s.capacity;
result.num_hits += s.num_hits;
result.num_complete_misses += s.num_complete_misses;
result.num_symmetry_misses += s.num_symmetry_misses;
}
return result;
}
} // namespace minigo
|
mlperf/training_results_v0.7
|
Google/benchmarks/minigo/implementations/minigo-research-TF-tpu-v4-128/cc/model/inference_cache.cc
|
C++
|
apache-2.0
| 9,201
|
/*
* Copyright (c) 2015 PLUMgrid, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eBPF mini library */
#ifndef LIBBPF_H
#define LIBBPF_H
#include "linux/bpf.h"
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
struct bpf_create_map_attr;
struct bpf_load_program_attr;
enum bpf_probe_attach_type {
BPF_PROBE_ENTRY,
BPF_PROBE_RETURN
};
int bcc_create_map(enum bpf_map_type map_type, const char *name,
int key_size, int value_size, int max_entries,
int map_flags);
int bcc_create_map_xattr(struct bpf_create_map_attr *attr, bool allow_rlimit);
int bpf_update_elem(int fd, void *key, void *value, unsigned long long flags);
int bpf_lookup_elem(int fd, void *key, void *value);
int bpf_delete_elem(int fd, void *key);
int bpf_get_first_key(int fd, void *key, size_t key_size);
int bpf_get_next_key(int fd, void *key, void *next_key);
int bpf_lookup_and_delete(int fd, void *key, void *value);
/*
* Load a BPF program, and return the FD of the loaded program.
*
* On newer Kernels, the parameter name is used to identify the loaded program
* for inspection and debugging. It could be different from the function name.
*
* If log_level has value greater than 0, or the load failed, it will enable
* extra logging of loaded BPF bytecode and register status, and will print the
* logging message to stderr. In such cases:
* - If log_buf and log_buf_size are provided, it will use and also write the
* log messages to the provided log_buf. If log_buf is insufficient in size,
* it will not to any additional memory allocation.
* - Otherwise, it will allocate an internal temporary buffer for log message
* printing, and continue to attempt increase that allocated buffer size if
* initial attempt was insufficient in size.
*/
int bcc_prog_load(enum bpf_prog_type prog_type, const char *name,
const struct bpf_insn *insns, int prog_len,
const char *license, unsigned kern_version,
int log_level, char *log_buf, unsigned log_buf_size);
int bcc_prog_load_xattr(struct bpf_load_program_attr *attr,
int prog_len, char *log_buf,
unsigned log_buf_size, bool allow_rlimit);
int bpf_attach_socket(int sockfd, int progfd);
/* create RAW socket. If name is not NULL/a non-empty null-terminated string,
* bind the raw socket to the interface 'name' */
int bpf_open_raw_sock(const char *name);
typedef void (*perf_reader_raw_cb)(void *cb_cookie, void *raw, int raw_size);
typedef void (*perf_reader_lost_cb)(void *cb_cookie, uint64_t lost);
int bpf_attach_kprobe(int progfd, enum bpf_probe_attach_type attach_type,
const char *ev_name, const char *fn_name, uint64_t fn_offset,
int maxactive);
int bpf_detach_kprobe(const char *ev_name);
int bpf_attach_uprobe(int progfd, enum bpf_probe_attach_type attach_type,
const char *ev_name, const char *binary_path,
uint64_t offset, pid_t pid);
int bpf_detach_uprobe(const char *ev_name);
int bpf_attach_tracepoint(int progfd, const char *tp_category,
const char *tp_name);
int bpf_detach_tracepoint(const char *tp_category, const char *tp_name);
int bpf_attach_raw_tracepoint(int progfd, const char *tp_name);
int bpf_attach_kfunc(int prog_fd);
int bpf_attach_lsm(int prog_fd);
bool bpf_has_kernel_btf(void);
void * bpf_open_perf_buffer(perf_reader_raw_cb raw_cb,
perf_reader_lost_cb lost_cb, void *cb_cookie,
int pid, int cpu, int page_cnt);
/* attached a prog expressed by progfd to the device specified in dev_name */
int bpf_attach_xdp(const char *dev_name, int progfd, uint32_t flags);
// attach a prog expressed by progfd to run on a specific perf event. The perf
// event will be created using the perf_event_attr pointer provided.
int bpf_attach_perf_event_raw(int progfd, void *perf_event_attr, pid_t pid,
int cpu, int group_fd, unsigned long extra_flags);
// attach a prog expressed by progfd to run on a specific perf event, with
// certain sample period or sample frequency
int bpf_attach_perf_event(int progfd, uint32_t ev_type, uint32_t ev_config,
uint64_t sample_period, uint64_t sample_freq,
pid_t pid, int cpu, int group_fd);
int bpf_open_perf_event(uint32_t type, uint64_t config, int pid, int cpu);
int bpf_close_perf_event_fd(int fd);
typedef int (*ring_buffer_sample_fn)(void *ctx, void *data, size_t size);
struct ring_buffer;
void * bpf_new_ringbuf(int map_fd, ring_buffer_sample_fn sample_cb, void *ctx);
void bpf_free_ringbuf(struct ring_buffer *rb);
int bpf_add_ringbuf(struct ring_buffer *rb, int map_fd,
ring_buffer_sample_fn sample_cb, void *ctx);
int bpf_poll_ringbuf(struct ring_buffer *rb, int timeout_ms);
int bpf_consume_ringbuf(struct ring_buffer *rb);
int bpf_obj_pin(int fd, const char *pathname);
int bpf_obj_get(const char *pathname);
int bpf_obj_get_info(int prog_map_fd, void *info, uint32_t *info_len);
int bpf_prog_compute_tag(const struct bpf_insn *insns, int prog_len,
unsigned long long *tag);
int bpf_prog_get_tag(int fd, unsigned long long *tag);
int bpf_prog_get_next_id(uint32_t start_id, uint32_t *next_id);
int bpf_prog_get_fd_by_id(uint32_t id);
int bpf_map_get_fd_by_id(uint32_t id);
int bpf_obj_get_info_by_fd(int prog_fd, void *info, uint32_t *info_len);
#define LOG_BUF_SIZE 65536
// Put non-static/inline functions in their own section with this prefix +
// fn_name to enable discovery by the bcc library.
#define BPF_FN_PREFIX ".bpf.fn."
/* ALU ops on registers, bpf_add|sub|...: dst_reg += src_reg */
#define BPF_ALU64_REG(OP, DST, SRC) \
((struct bpf_insn) { \
.code = BPF_ALU64 | BPF_OP(OP) | BPF_X, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = 0, \
.imm = 0 })
#define BPF_ALU32_REG(OP, DST, SRC) \
((struct bpf_insn) { \
.code = BPF_ALU | BPF_OP(OP) | BPF_X, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = 0, \
.imm = 0 })
/* ALU ops on immediates, bpf_add|sub|...: dst_reg += imm32 */
#define BPF_ALU64_IMM(OP, DST, IMM) \
((struct bpf_insn) { \
.code = BPF_ALU64 | BPF_OP(OP) | BPF_K, \
.dst_reg = DST, \
.src_reg = 0, \
.off = 0, \
.imm = IMM })
#define BPF_ALU32_IMM(OP, DST, IMM) \
((struct bpf_insn) { \
.code = BPF_ALU | BPF_OP(OP) | BPF_K, \
.dst_reg = DST, \
.src_reg = 0, \
.off = 0, \
.imm = IMM })
/* Short form of mov, dst_reg = src_reg */
#define BPF_MOV64_REG(DST, SRC) \
((struct bpf_insn) { \
.code = BPF_ALU64 | BPF_MOV | BPF_X, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = 0, \
.imm = 0 })
/* Short form of mov, dst_reg = imm32 */
#define BPF_MOV64_IMM(DST, IMM) \
((struct bpf_insn) { \
.code = BPF_ALU64 | BPF_MOV | BPF_K, \
.dst_reg = DST, \
.src_reg = 0, \
.off = 0, \
.imm = IMM })
/* BPF_LD_IMM64 macro encodes single 'load 64-bit immediate' insn */
#define BPF_LD_IMM64(DST, IMM) \
BPF_LD_IMM64_RAW(DST, 0, IMM)
#define BPF_LD_IMM64_RAW(DST, SRC, IMM) \
((struct bpf_insn) { \
.code = BPF_LD | BPF_DW | BPF_IMM, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = 0, \
.imm = (__u32) (IMM) }), \
((struct bpf_insn) { \
.code = 0, /* zero is reserved opcode */ \
.dst_reg = 0, \
.src_reg = 0, \
.off = 0, \
.imm = ((__u64) (IMM)) >> 32 })
#define BPF_PSEUDO_MAP_FD 1
/* pseudo BPF_LD_IMM64 insn used to refer to process-local map_fd */
#define BPF_LD_MAP_FD(DST, MAP_FD) \
BPF_LD_IMM64_RAW(DST, BPF_PSEUDO_MAP_FD, MAP_FD)
/* Direct packet access, R0 = *(uint *) (skb->data + imm32) */
#define BPF_LD_ABS(SIZE, IMM) \
((struct bpf_insn) { \
.code = BPF_LD | BPF_SIZE(SIZE) | BPF_ABS, \
.dst_reg = 0, \
.src_reg = 0, \
.off = 0, \
.imm = IMM })
/* Memory load, dst_reg = *(uint *) (src_reg + off16) */
#define BPF_LDX_MEM(SIZE, DST, SRC, OFF) \
((struct bpf_insn) { \
.code = BPF_LDX | BPF_SIZE(SIZE) | BPF_MEM, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = OFF, \
.imm = 0 })
/* Memory store, *(uint *) (dst_reg + off16) = src_reg */
#define BPF_STX_MEM(SIZE, DST, SRC, OFF) \
((struct bpf_insn) { \
.code = BPF_STX | BPF_SIZE(SIZE) | BPF_MEM, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = OFF, \
.imm = 0 })
/* Memory store, *(uint *) (dst_reg + off16) = imm32 */
#define BPF_ST_MEM(SIZE, DST, OFF, IMM) \
((struct bpf_insn) { \
.code = BPF_ST | BPF_SIZE(SIZE) | BPF_MEM, \
.dst_reg = DST, \
.src_reg = 0, \
.off = OFF, \
.imm = IMM })
/* Conditional jumps against registers, if (dst_reg 'op' src_reg) goto pc + off16 */
#define BPF_JMP_REG(OP, DST, SRC, OFF) \
((struct bpf_insn) { \
.code = BPF_JMP | BPF_OP(OP) | BPF_X, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = OFF, \
.imm = 0 })
/* Conditional jumps against immediates, if (dst_reg 'op' imm32) goto pc + off16 */
#define BPF_JMP_IMM(OP, DST, IMM, OFF) \
((struct bpf_insn) { \
.code = BPF_JMP | BPF_OP(OP) | BPF_K, \
.dst_reg = DST, \
.src_reg = 0, \
.off = OFF, \
.imm = IMM })
/* Raw code statement block */
#define BPF_RAW_INSN(CODE, DST, SRC, OFF, IMM) \
((struct bpf_insn) { \
.code = CODE, \
.dst_reg = DST, \
.src_reg = SRC, \
.off = OFF, \
.imm = IMM })
/* Program exit */
#define BPF_EXIT_INSN() \
((struct bpf_insn) { \
.code = BPF_JMP | BPF_EXIT, \
.dst_reg = 0, \
.src_reg = 0, \
.off = 0, \
.imm = 0 })
#ifdef __cplusplus
}
#endif
#endif
|
tuxology/bcc
|
src/cc/libbpf.h
|
C
|
apache-2.0
| 10,497
|
# Pachycentria formosana Hayata SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Melastomataceae/Medinilla/Medinilla fengii/ Syn. Pachycentria formosana/README.md
|
Markdown
|
apache-2.0
| 186
|
/***********************************************************************
* Copyright (c) 2013-2017 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
***********************************************************************/
package org.locationtech.geomesa.utils.io.fs
import java.io.InputStream
import org.apache.hadoop.fs.{FileStatus, FileSystem, Path, PathFilter}
import org.locationtech.geomesa.utils.io.fs.FileSystemDelegate.FileHandle
import org.locationtech.geomesa.utils.io.fs.HadoopDelegate.HadoopFileHandle
/**
* Delegate allows us to avoid a runtime dependency on hadoop
*/
class HadoopDelegate extends FileSystemDelegate {
import HadoopDelegate.HiddenFileFilter
import org.apache.hadoop.fs.{FileStatus, LocatedFileStatus, Path}
private val conf = new org.apache.hadoop.conf.Configuration()
// use the same property as FileInputFormat
private val recursive = conf.getBoolean("mapreduce.input.fileinputformat.input.dir.recursive", false)
// based on logic from hadoop FileInputFormat
override def interpretPath(path: String): Seq[FileHandle] = {
val p = new Path(path)
// TODO close filesystem?
val fs = p.getFileSystem(conf)
val files = fs.globStatus(p, HiddenFileFilter)
if (files == null) {
throw new IllegalArgumentException(s"Input path does not exist: $path")
} else if (files.isEmpty) {
throw new IllegalArgumentException(s"Input path does not match any files: $path")
}
def getFiles(file: FileStatus): Seq[FileHandle] = {
if (!file.isDirectory) {
Seq(new HadoopFileHandle(file, fs))
} else if (recursive) {
val children = fs.listLocatedStatus(file.getPath)
new Iterator[LocatedFileStatus] {
override def hasNext: Boolean = children.hasNext
override def next(): LocatedFileStatus = children.next
}.filter(f => HiddenFileFilter.accept(f.getPath)).toSeq.flatMap(getFiles)
} else {
Seq.empty
}
}
files.flatMap(getFiles)
}
}
object HadoopDelegate {
val HiddenFileFilter: PathFilter = new PathFilter() {
override def accept(path: Path): Boolean = {
val name = path.getName
!name.startsWith("_") && !name.startsWith(".")
}
}
class HadoopFileHandle(file: FileStatus, fs: FileSystem) extends FileHandle {
override def path: String = file.getPath.toString
override def length: Long = file.getLen
override def open: InputStream = fs.open(file.getPath)
}
}
|
ronq/geomesa
|
geomesa-utils/src/main/scala/org/locationtech/geomesa/utils/io/fs/HadoopDelegate.scala
|
Scala
|
apache-2.0
| 2,712
|
# Asplenium leucothrix Maxon SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Aspleniaceae/Asplenium/Asplenium leucothrix/README.md
|
Markdown
|
apache-2.0
| 176
|
package org.nudge.elasticstack.exception;
/**
* Exception related to interaction with the Nudge API.
*/
public class NudgeApiException extends Exception {
public NudgeApiException() {
super();
}
public NudgeApiException(String message) {
super(message);
}
public NudgeApiException(String message, Throwable cause) {
super(message, cause);
}
}
|
NudgeApm/nudge-elasticstack-connector
|
src/main/java/org/nudge/elasticstack/exception/NudgeApiException.java
|
Java
|
apache-2.0
| 397
|
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_09.html">Class Test_AbaRouteValidator_09</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_18203_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_09.html?line=14761#src-14761" >testAbaNumberCheck_18203_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:39:03
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_18203_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=34654#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html>
|
dcarda/aba.route.validator
|
target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_09_testAbaNumberCheck_18203_good_qqm.html
|
HTML
|
apache-2.0
| 9,181
|
/**
* Copyright 2011-2017 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.runtime.io.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.text.MessageFormat;
/**
* Installs a temporary file.
* @since 0.9.0
*/
public final class TemporaryFileInstaller {
private final byte[] bytes;
private final boolean executable;
private TemporaryFileInstaller(byte[] bytes, boolean executable) {
this.bytes = bytes;
this.executable = executable;
}
/**
* Creates a new instance.
* @param contents the file contents
* @param executable {@code true} to install as an executable file, otherwise {@code false}
* @return the created instance
* @throws IOException if failed to load contents
*/
public static TemporaryFileInstaller newInstance(InputStream contents, boolean executable) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (true) {
int read = contents.read(buf);
if (read < 0) {
break;
}
output.write(buf, 0, read);
}
byte[] bytes = output.toByteArray();
return new TemporaryFileInstaller(bytes, executable);
}
/**
* Installs contents into the target file.
* @param target the target file
* @param reuse {@code true} to reuse installed file, otherwise {@code false}
* @return {@code true} if target file is successfully installed,
* or {@code false} if the file is already installed
* @throws IOException if error occurred while installing the target file
*/
public boolean install(File target, boolean reuse) throws IOException {
File parent = target.getAbsoluteFile().getParentFile();
if (parent.mkdirs() == false && parent.isDirectory() == false) {
throw new IOException(MessageFormat.format(
"failed to create a file: {0}",
target));
}
try (RandomAccessFile file = new RandomAccessFile(target, "rw"); //$NON-NLS-1$
FileLock lock = file.getChannel().lock(0, 0, false)) {
if (reuse && isReusable(target, file)) {
return false;
}
doInstall(target, file);
return true;
}
}
private boolean isReusable(File target, RandomAccessFile file) throws IOException {
if (executable && target.canExecute() == false) {
return false;
}
if (bytes.length != file.length()) {
return false;
}
int offset = 0;
file.seek(offset);
byte[] buf = new byte[256];
while (true) {
int read = file.read(buf);
if (read < 0) {
break;
}
for (int i = 0; i < read; i++) {
if (bytes[i + offset] != buf[i]) {
return false;
}
}
offset += read;
}
return true;
}
private void doInstall(File target, RandomAccessFile file) throws IOException {
file.setLength(0L);
file.write(bytes);
if (executable) {
target.setExecutable(true);
}
}
}
|
cocoatomo/asakusafw
|
core-project/asakusa-runtime/src/main/java/com/asakusafw/runtime/io/util/TemporaryFileInstaller.java
|
Java
|
apache-2.0
| 3,987
|
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.59
* Generated at: 2015-05-11 04:59:12 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp.WEB_002dINF.view.edit;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class editConfirm_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0;
static {
_jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("f:url", org.seasar.struts.taglib.S2Functions.class, "url", new Class[] {java.lang.String.class});
}
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
static {
_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1);
_jspx_dependants.put("/WEB-INF/view/common/common.jsp", Long.valueOf(1431143320000L));
}
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write("<title>編集確認</title>\n");
out.write("</head>\n");
out.write("<body>\n");
out.write("<h1>この内容で編集しますか?</h1>\n");
out.write("<a href='");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${f:url(\"/list\")}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, _jspx_fnmap_0, false));
out.write("'>戻る</a>\n");
out.write("<a href='");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${f:url(\"editComplete\")}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, _jspx_fnmap_0, false));
out.write("'>完了</a>\n");
out.write("\n");
out.write("</body>\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
|
Recomember/Recom-repaire
|
Recom/work/org/apache/jsp/WEB_002dINF/view/edit/editConfirm_jsp.java
|
Java
|
apache-2.0
| 4,764
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/tasks/v2/cloudtasks.proto
require 'google/protobuf'
require 'google/api/annotations_pb'
require 'google/api/client_pb'
require 'google/api/field_behavior_pb'
require 'google/cloud/tasks/v2/queue_pb'
require 'google/cloud/tasks/v2/task_pb'
require 'google/iam/v1/iam_policy_pb'
require 'google/iam/v1/policy_pb'
require 'google/protobuf/empty_pb'
require 'google/protobuf/field_mask_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_message "google.cloud.tasks.v2.ListQueuesRequest" do
optional :parent, :string, 1
optional :filter, :string, 2
optional :page_size, :int32, 3
optional :page_token, :string, 4
end
add_message "google.cloud.tasks.v2.ListQueuesResponse" do
repeated :queues, :message, 1, "google.cloud.tasks.v2.Queue"
optional :next_page_token, :string, 2
end
add_message "google.cloud.tasks.v2.GetQueueRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tasks.v2.CreateQueueRequest" do
optional :parent, :string, 1
optional :queue, :message, 2, "google.cloud.tasks.v2.Queue"
end
add_message "google.cloud.tasks.v2.UpdateQueueRequest" do
optional :queue, :message, 1, "google.cloud.tasks.v2.Queue"
optional :update_mask, :message, 2, "google.protobuf.FieldMask"
end
add_message "google.cloud.tasks.v2.DeleteQueueRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tasks.v2.PurgeQueueRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tasks.v2.PauseQueueRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tasks.v2.ResumeQueueRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tasks.v2.ListTasksRequest" do
optional :parent, :string, 1
optional :response_view, :enum, 2, "google.cloud.tasks.v2.Task.View"
optional :page_size, :int32, 3
optional :page_token, :string, 4
end
add_message "google.cloud.tasks.v2.ListTasksResponse" do
repeated :tasks, :message, 1, "google.cloud.tasks.v2.Task"
optional :next_page_token, :string, 2
end
add_message "google.cloud.tasks.v2.GetTaskRequest" do
optional :name, :string, 1
optional :response_view, :enum, 2, "google.cloud.tasks.v2.Task.View"
end
add_message "google.cloud.tasks.v2.CreateTaskRequest" do
optional :parent, :string, 1
optional :task, :message, 2, "google.cloud.tasks.v2.Task"
optional :response_view, :enum, 3, "google.cloud.tasks.v2.Task.View"
end
add_message "google.cloud.tasks.v2.DeleteTaskRequest" do
optional :name, :string, 1
end
add_message "google.cloud.tasks.v2.RunTaskRequest" do
optional :name, :string, 1
optional :response_view, :enum, 2, "google.cloud.tasks.v2.Task.View"
end
end
module Google
module Cloud
module Tasks
module V2
ListQueuesRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.ListQueuesRequest").msgclass
ListQueuesResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.ListQueuesResponse").msgclass
GetQueueRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.GetQueueRequest").msgclass
CreateQueueRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.CreateQueueRequest").msgclass
UpdateQueueRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.UpdateQueueRequest").msgclass
DeleteQueueRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.DeleteQueueRequest").msgclass
PurgeQueueRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.PurgeQueueRequest").msgclass
PauseQueueRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.PauseQueueRequest").msgclass
ResumeQueueRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.ResumeQueueRequest").msgclass
ListTasksRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.ListTasksRequest").msgclass
ListTasksResponse = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.ListTasksResponse").msgclass
GetTaskRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.GetTaskRequest").msgclass
CreateTaskRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.CreateTaskRequest").msgclass
DeleteTaskRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.DeleteTaskRequest").msgclass
RunTaskRequest = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.tasks.v2.RunTaskRequest").msgclass
end
end
end
end
|
blowmage/gcloud-ruby
|
google-cloud-tasks/lib/google/cloud/tasks/v2/cloudtasks_pb.rb
|
Ruby
|
apache-2.0
| 4,930
|
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2017 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sarl.m2e;
import java.io.File;
/** Configuration of a SARL project.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
class SARLConfiguration {
private File input;
private File output;
private File testInput;
private File testOutput;
private String inputCompliance;
private String outputCompliance;
private String encoding;
/** Set the uninitialized field with given configuration.
*
* @param config - the configured values.
*/
@SuppressWarnings("checkstyle:npathcomplexity")
public void setFrom(SARLConfiguration config) {
if (this.input == null) {
this.input = config.getInput();
}
if (this.output == null) {
this.output = config.getOutput();
}
if (this.testInput == null) {
this.testInput = config.getTestInput();
}
if (this.testOutput == null) {
this.testOutput = config.getTestOutput();
}
if (this.inputCompliance == null) {
this.inputCompliance = config.getInputCompliance();
}
if (this.outputCompliance == null) {
this.outputCompliance = config.getOutputCompliance();
}
if (this.encoding == null) {
this.encoding = config.getEncoding();
}
}
/** Replies the input file.
*
* @return the input
*/
public File getInput() {
return this.input;
}
/** Set the input file.
*
* @param input the input to set
*/
public void setInput(File input) {
this.input = input;
}
/** Replies the output file.
*
* @return the output
*/
public File getOutput() {
return this.output;
}
/** Set the output file.
*
* @param output the output to set
*/
public void setOutput(File output) {
this.output = output;
}
/** Replies the input file for tests.
*
* @return the testInput
*/
public File getTestInput() {
return this.testInput;
}
/** Set the input file for tests.
*
* @param testInput the testInput to set
*/
public void setTestInput(File testInput) {
this.testInput = testInput;
}
/** Replies the output file for tests.
*
* @return the testOutput
*/
public File getTestOutput() {
return this.testOutput;
}
/** Set the output file for tests.
*
* @param testOutput the testOutput to set
*/
public void setTestOutput(File testOutput) {
this.testOutput = testOutput;
}
/** Replies the input's Java compliance.
*
* @return the inputCompliance
*/
public String getInputCompliance() {
return this.inputCompliance;
}
/** Change the input's Java compliance.
*
* @param inputCompliance the inputCompliance to set
*/
public void setInputCompliance(String inputCompliance) {
this.inputCompliance = inputCompliance;
}
/** Replies the output's Java compliance.
*
* @return the outputCompliance
*/
public String getOutputCompliance() {
return this.outputCompliance;
}
/** Change the output's Java compliance.
*
* @param outputCompliance the outputCompliance to set
*/
public void setOutputCompliance(String outputCompliance) {
this.outputCompliance = outputCompliance;
}
/** Replies the encoding of the files.
*
* @return the encoding
*/
public String getEncoding() {
return this.encoding;
}
/** Change the encoding of the files.
*
* @param encoding the encoding to set
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
@Override
public String toString() {
return "input = " + this.input //$NON-NLS-1$
+ "\noutput = " + this.output //$NON-NLS-1$
+ "\ntestInput = " + this.testInput //$NON-NLS-1$
+ "\ntestOutput = " + this.testOutput //$NON-NLS-1$
+ "\ninputCompliance = " + this.inputCompliance //$NON-NLS-1$
+ "\noutputCompliance = " + this.outputCompliance //$NON-NLS-1$
+ "\nencoding = " + this.encoding; //$NON-NLS-1$
}
}
|
jgfoster/sarl
|
main/coreplugins/io.sarl.m2e/src/io/sarl/m2e/SARLConfiguration.java
|
Java
|
apache-2.0
| 4,511
|
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.directconnect.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.directconnect.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DescribeTagsResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeTagsResultJsonUnmarshaller implements Unmarshaller<DescribeTagsResult, JsonUnmarshallerContext> {
public DescribeTagsResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DescribeTagsResult describeTagsResult = new DescribeTagsResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return describeTagsResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("resourceTags", targetDepth)) {
context.nextToken();
describeTagsResult.setResourceTags(new ListUnmarshaller<ResourceTag>(ResourceTagJsonUnmarshaller.getInstance()).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return describeTagsResult;
}
private static DescribeTagsResultJsonUnmarshaller instance;
public static DescribeTagsResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeTagsResultJsonUnmarshaller();
return instance;
}
}
|
dagnir/aws-sdk-java
|
aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/transform/DescribeTagsResultJsonUnmarshaller.java
|
Java
|
apache-2.0
| 2,845
|
package com.serenegiant.system;
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2021 saki t_saki@serenegiant.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import androidx.annotation.NonNull;
public class SysPropReader {
private static final boolean DEBUG = false; // set false on production
private static final String TAG = SysPropReader.class.getSimpleName();
private static final String GETPROP_EXECUTABLE_PATH = "/system/bin/getprop";
private SysPropReader() {
// インスタンス化をエラーにするためにデフォルトコンストラクタをprivateに
}
/**
* システムプロパティを読み込み文字列として返す
* システムプロパティの値が1行で無い場合は最初の行のみ読み込む
* @param propName
* @return
*/
@NonNull
public static String read(@NonNull final String propName) {
Process process = null;
BufferedReader bufferedReader = null;
String result = null;
try {
process = new ProcessBuilder()
.command(GETPROP_EXECUTABLE_PATH, propName)
.redirectErrorStream(true)
.start();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
result = bufferedReader.readLine();
if (DEBUG) Log.v(TAG, "read System Property: " + propName + "=" + result);
} catch (final Exception e) {
if (DEBUG) Log.d(TAG, "Failed to read System Property " + propName, e);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException e) {
if (DEBUG) Log.w(TAG, e);
}
}
if (process != null) {
process.destroy();
}
}
if (TextUtils.isEmpty(result)) {
// 指定したプロパティがセットされていないか読み込み時にエラーが発生した
result = "";
}
return result;
}
/**
* システムプロパティを読み込み文字列として返す
* システムプロパティの値が1行で無い場合もすべて読み込む
* @param propName
* @return
*/
@NonNull
public static String readAll(@NonNull final String propName) {
final StringBuilder sb = new StringBuilder();
Process process = null;
BufferedReader bufferedReader = null;
try {
process = new ProcessBuilder()
.command(GETPROP_EXECUTABLE_PATH, propName)
.redirectErrorStream(true)
.start();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
do {
line = bufferedReader.readLine();
if (!TextUtils.isEmpty(line)) {
if (sb.length() > 0) {
sb.append("\n");
}
sb.append(line);
}
} while (!TextUtils.isEmpty(line));
} catch (final Exception e) {
if (DEBUG) Log.d(TAG, "Failed to read System Property " + propName, e);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException e) {
if (DEBUG) Log.w(TAG, e);
}
}
if (process != null) {
process.destroy();
}
}
return sb.toString();
}
}
|
saki4510t/libcommon
|
common/src/main/java/com/serenegiant/system/SysPropReader.java
|
Java
|
apache-2.0
| 3,710
|
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/util/TreeMap_DescendingKeySpliterator.hpp>
extern void unimplemented_(const char16_t* name);
java::util::TreeMap_DescendingKeySpliterator::TreeMap_DescendingKeySpliterator(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
java::util::TreeMap_DescendingKeySpliterator::TreeMap_DescendingKeySpliterator(TreeMap* tree, TreeMap_Entry* origin, TreeMap_Entry* fence, int32_t side, int32_t est, int32_t expectedModCount)
: TreeMap_DescendingKeySpliterator(*static_cast< ::default_init_tag* >(0))
{
ctor(tree, origin, fence, side, est, expectedModCount);
}
void ::java::util::TreeMap_DescendingKeySpliterator::ctor(TreeMap* tree, TreeMap_Entry* origin, TreeMap_Entry* fence, int32_t side, int32_t est, int32_t expectedModCount)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::util::TreeMap_DescendingKeySpliterator::ctor(TreeMap* tree, TreeMap_Entry* origin, TreeMap_Entry* fence, int32_t side, int32_t est, int32_t expectedModCount)");
}
int32_t java::util::TreeMap_DescendingKeySpliterator::characteristics()
{ /* stub */
unimplemented_(u"int32_t java::util::TreeMap_DescendingKeySpliterator::characteristics()");
return 0;
}
void java::util::TreeMap_DescendingKeySpliterator::forEachRemaining(::java::util::function::Consumer* action)
{ /* stub */
unimplemented_(u"void java::util::TreeMap_DescendingKeySpliterator::forEachRemaining(::java::util::function::Consumer* action)");
}
bool java::util::TreeMap_DescendingKeySpliterator::tryAdvance(::java::util::function::Consumer* action)
{ /* stub */
unimplemented_(u"bool java::util::TreeMap_DescendingKeySpliterator::tryAdvance(::java::util::function::Consumer* action)");
return 0;
}
java::util::TreeMap_DescendingKeySpliterator* java::util::TreeMap_DescendingKeySpliterator::trySplit()
{ /* stub */
unimplemented_(u"java::util::TreeMap_DescendingKeySpliterator* java::util::TreeMap_DescendingKeySpliterator::trySplit()");
return 0;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* java::util::TreeMap_DescendingKeySpliterator::class_()
{
static ::java::lang::Class* c = ::class_(u"java.util.TreeMap.DescendingKeySpliterator", 42);
return c;
}
int64_t java::util::TreeMap_DescendingKeySpliterator::estimateSize()
{
return TreeMap_TreeMapSpliterator::estimateSize();
}
java::lang::Class* java::util::TreeMap_DescendingKeySpliterator::getClass0()
{
return class_();
}
|
pebble2015/cpoi
|
ext/stub/java/util/TreeMap_DescendingKeySpliterator-stub.cpp
|
C++
|
apache-2.0
| 2,591
|
package org.drools.guvnor.client.explorer.navigation.qa;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;
public class VerifierPlace extends Place {
private final String moduleUuid;
public VerifierPlace(String moduleUuid) {
this.moduleUuid = moduleUuid;
}
public String getModuleUuid() {
return moduleUuid;
}
@Override
public boolean equals(Object o) {
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
VerifierPlace that = (VerifierPlace) o;
if ( moduleUuid != null ? !moduleUuid.equals( that.moduleUuid ) : that.moduleUuid != null ) return false;
return true;
}
@Override
public int hashCode() {
return moduleUuid != null ? moduleUuid.hashCode() : 0;
}
public static class Tokenizer implements PlaceTokenizer<VerifierPlace> {
public String getToken(VerifierPlace place) {
return place.getModuleUuid();
}
public VerifierPlace getPlace(String token) {
return new VerifierPlace( token );
}
}
}
|
cyberdrcarr/guvnor
|
guvnor-webapp-drools/src/main/java/org/drools/guvnor/client/explorer/navigation/qa/VerifierPlace.java
|
Java
|
apache-2.0
| 1,163
|
//-----------------------------------------------------------------------
// <copyright file="EntityWriter.cs" company="Genesys Source">
// Copyright (c) Genesys Source. All rights reserved.
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the 'License'); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using Genesys.Extensions;
using Genesys.Extras.Configuration;
using Genesys.Framework.Activity;
using Genesys.Framework.Data;
using Genesys.Framework.Operation;
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Linq.Expressions;
namespace Genesys.Framework.Repository
{
/// <summary>
/// EF DbContext for read-only GetBy* operations
/// </summary>
public partial class StoredProcedureWriter<TEntity> : DbContext,
ICreateOperation<TEntity>, IUpdateOperation<TEntity>, IDeleteOperation<TEntity> where TEntity : StoredProcedureEntity<TEntity>, new()
{
/// <summary>
/// Data set DbSet class that gets/saves the entity.
/// Note: EF requires public get/set
/// </summary>
public DbSet<TEntity> Data { get; set; }
/// <summary>
/// Constructor
/// </summary>
public StoredProcedureWriter()
: base(ConnectionStringGet())
{
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory());
Database.SetInitializer<StoredProcedureWriter<TEntity>>(null);
}
/// <summary>
/// Constructor. Explicitly set database connection.
/// </summary>
/// <param name="connectionString">Connection String to be used for this object data access</param>
protected StoredProcedureWriter(string connectionString)
: base(connectionString)
{
Database.SetInitializer<StoredProcedureWriter<TEntity>>(null);
}
/// <summary>
/// Create operation on the object
/// </summary>
/// <param name="entity">Entity to be saved to datastore</param>
/// <returns>Object pulled from datastore</returns>
public TEntity Create(TEntity entity)
{
try
{
if (entity.CreateStoredProcedure == null) throw new Exception("Create() requires CreateStoredProcedure to be initialized properly.");
if (entity.IsValid() && CanInsert(entity))
{
entity.Key = entity.Key == TypeExtension.DefaultGuid ? Guid.NewGuid() : entity.Key; // Required to re-pull data after save
entity.ActivityContextKey = entity.ActivityContextKey == TypeExtension.DefaultGuid ? ActivityContextWriter.Create().ActivityContextKey : entity.ActivityContextKey;
var rowsAffected = ExecuteSqlCommand(entity.CreateStoredProcedure);
if (rowsAffected > 0) entity.Fill(Read(x => x.Key == entity.Key).FirstOrDefaultSafe()); // Re-pull clean object, exactly as the DB has stored
}
}
catch (Exception ex)
{
ExceptionLogWriter.Create(ex, typeof(TEntity), $"StoredProcedureWriter.Create() on {this.ToString()}");
throw;
}
return entity;
}
/// <summary>
/// Retrieve TEntity objects operation
/// Default: Does Not read from a Get stored procedure.
/// Reads directly from DbSet defined in repository class.
/// </summary>
/// <param name="expression">Expression to query the datastore</param>
/// <returns>IQueryable of read operation</returns>
public IQueryable<TEntity> Read(Expression<Func<TEntity, bool>> expression)
{
return Data.Where(expression);
}
/// <summary>
/// Update the object
/// </summary>
public TEntity Update(TEntity entity)
{
try
{
if (entity.UpdateStoredProcedure == null) throw new Exception("Update() requires UpdateStoredProcedure to be initialized properly.");
if (entity.IsValid() && CanUpdate(entity))
{
entity.ActivityContextKey = entity.ActivityContextKey == TypeExtension.DefaultGuid ? ActivityContextWriter.Create().ActivityContextKey : entity.ActivityContextKey;
var rowsAffected = ExecuteSqlCommand(entity.UpdateStoredProcedure);
if (rowsAffected > 0) entity.Fill(Read(x => x.Key == entity.Key).FirstOrDefaultSafe());
}
}
catch (Exception ex)
{
ExceptionLogWriter.Create(ex, typeof(TEntity), $"StoredProcedureWriter.Update() on {this.ToString()}");
throw;
}
return entity;
}
/// <summary>
/// Worker that saves this object with automatic tracking.
/// </summary>
public virtual TEntity Save(TEntity entity)
{
if (CanInsert(entity))
entity = Create(entity);
else if (CanUpdate(entity))
entity = Update(entity);
return entity;
}
/// <summary>
/// Deletes operation on this entity
/// </summary>
public TEntity Delete(TEntity entity)
{
try
{
if (entity.DeleteStoredProcedure == null) throw new Exception("Delete() requires DeleteStoredProcedure to be initialized properly.");
if (CanDelete(entity))
{
entity.ActivityContextKey = entity.ActivityContextKey == TypeExtension.DefaultGuid ? ActivityContextWriter.Create().ActivityContextKey : entity.ActivityContextKey;
var rowsAffected = ExecuteSqlCommand(entity.DeleteStoredProcedure);
if (rowsAffected > 0) entity.Fill(Read(x => x.Key == entity.Key).FirstOrDefaultSafe());
}
}
catch (Exception ex)
{
ExceptionLogWriter.Create(ex, typeof(TEntity), $"StoredProcedureWriter.Delete() on {this.ToString()}");
throw;
}
return entity;
}
/// <summary>
/// Gets connection strings from connectionstrings.config
/// </summary>
/// <returns></returns>
private static string ConnectionStringGet()
{
var returnValue = TypeExtension.DefaultString;
var configDb = new ConfigurationEntity<TEntity>();
var configManager = new ConfigurationManagerFull();
var configConnectString = configManager.ConnectionString(configDb.ConnectionName);
var adoConnectionString = configConnectString.ToADO();
if (adoConnectionString.Length > 0)
{
returnValue = adoConnectionString;
}
else
{
throw new Exception("Connection string could not be found. A valid connection string required for data access.");
}
return returnValue;
}
/// <summary>
/// Set values when creating a model in the database
/// </summary>
/// <param name="modelBuilder"></param>
/// <remarks></remarks>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if ((DatabaseConfig.ConnectionString.Length == 0 || !CanConnect))
throw new Exception("Database connection failed or the connection string could not be found. A valid connection string required for data access.");
modelBuilder.HasDefaultSchema(DatabaseConfig.DatabaseSchema);
// Table
modelBuilder.Entity<TEntity>().ToTable(DatabaseConfig.TableName);
modelBuilder.Entity<TEntity>().HasKey(p => p.Key);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// Columns
modelBuilder.Entity<TEntity>().Property(x => x.Id)
.HasColumnName($"{DatabaseConfig.ColumnPrefix}Id");
modelBuilder.Entity<TEntity>().Property(x => x.Key)
.HasColumnName($"{DatabaseConfig.ColumnPrefix}Key");
// Ignored
modelBuilder.Ignore(DatabaseConfig.IgnoredTypes);
foreach (var item in DatabaseConfig.IgnoredProperties)
{
modelBuilder.Entity<TEntity>().Ignore(item);
}
base.OnModelCreating(modelBuilder);
}
/// <summary>
/// Executes stored procedure for specific parameter behavior
/// Named: @Param1 is used to match parameter with entity data.
/// - Uses: Database.ExecuteSqlCommand(entity.CreateStoredProcedure.ToString());
/// Ordinal: @Param1, @Param2 are assigned in ordinal position
/// - Uses: Database.ExecuteSqlCommand(entity.CreateStoredProcedure.SqlPrefix, entity.CreateStoredProcedure.Parameters.ToArray());
/// </summary>
public int ExecuteSqlCommand(StoredProcedure<TEntity> storedProc)
{
var returnValue = TypeExtension.DefaultInteger;
switch (ParameterBehavior)
{
case ParameterBehaviors.Named:
returnValue = Database.ExecuteSqlCommand(storedProc.ToString());
break;
case ParameterBehaviors.Ordinal:
default:
returnValue = Database.ExecuteSqlCommand(storedProc.SqlPrefix, storedProc.Parameters.ToArray());
break;
}
return returnValue;
}
}
}
|
GenesysSource/Foundation
|
src/DataTier/Framework.DataAccess.Full/Repository/StoredProcedureWriter.Full.cs
|
C#
|
apache-2.0
| 10,606
|
package com.duckma.example.recyclerview;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
gazzumatteo/RecyclerView-Example
|
app/src/androidTest/java/com/duckma/example/recyclerview/ApplicationTest.java
|
Java
|
apache-2.0
| 362
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.