hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44695e046a9f88c516e457a8f7684087f889ddb6
| 12,464
|
hpp
|
C++
|
include/behemoth/enumerator.hpp
|
gian21391/behemoth
|
923bf18a686603022bbab7ce8674dec4c59cdcde
|
[
"MIT"
] | null | null | null |
include/behemoth/enumerator.hpp
|
gian21391/behemoth
|
923bf18a686603022bbab7ce8674dec4c59cdcde
|
[
"MIT"
] | null | null | null |
include/behemoth/enumerator.hpp
|
gian21391/behemoth
|
923bf18a686603022bbab7ce8674dec4c59cdcde
|
[
"MIT"
] | null | null | null |
/* behemoth: A syntax-guided synthesis library
* Copyright (C) 2018 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <behemoth/expr.hpp>
#include <cassert>
#include <fmt/format.h>
#include <iostream>
#include <queue>
#include <algorithm>
#include <map>
#include <utility>
namespace behemoth
{
struct rule_t
{
unsigned match;
unsigned replace;
unsigned cost = 1;
};
using rules_t = std::vector<rule_t>;
/* expression with associated cost */
using cexpr_t = std::pair<unsigned,unsigned>;
struct expr_greater_than
{
expr_greater_than( context& ctx )
: _ctx( ctx )
{}
bool operator()(const cexpr_t& a, const cexpr_t& b) const
{
/* higher costs means greater */
if ( a.second > b.second ) return true;
if ( a.second < b.second ) return false;
/* more non-terminals means greater */
if ( _ctx.count_nonterminals( a.first ) > _ctx.count_nonterminals( b.first ) ) return true;
if ( _ctx.count_nonterminals( a.first ) < _ctx.count_nonterminals( b.first ) ) return false;
/* more nodes means greater */
if ( _ctx.count_nodes( a.first ) > _ctx.count_nodes( b.first ) ) return true;
if ( _ctx.count_nodes( a.first ) < _ctx.count_nodes( b.first ) ) return false;
return false;
}
context& _ctx;
}; // expr_greater_than
struct path_t
{
path_t ( unsigned initial_depth = std::numeric_limits<unsigned>::max() )
: depth( initial_depth )
{}
bool operator<( const path_t& other ) const
{
return ( depth < other.depth );
}
std::string as_string() const
{
std::string s = "[";
for ( auto i = 0u; i < indices.size(); ++i )
{
s += fmt::format( "%s", indices[indices.size()-1u-i] );
}
s += "] ";
s += invalid() ? "∞" : ( fmt::format( "%d", depth ) );
return s;
}
inline unsigned operator[]( std::size_t i )
{
return indices[indices.size()-1u-i];
}
inline void push_front( unsigned v )
{
indices.push_back( v );
}
inline void pop_front()
{
indices.pop_back();
}
inline void incr_depth()
{
++depth;
}
inline bool invalid() const
{
return indices.empty() && depth == std::numeric_limits<unsigned>::max();
}
inline bool valid() const
{
return !invalid();
}
/* indices in reverse order */
std::vector<unsigned> indices;
unsigned depth;
}; // path_t
std::vector<std::pair<unsigned,unsigned>> refine_expression_recurse( context& ctx, unsigned e, path_t path, const rules_t& rules )
{
if ( path.indices.empty() )
{
/* apply all rules */
std::vector<std::pair<unsigned,unsigned>> results;
for ( const auto& r : rules )
{
if ( e == r.match )
{
results.emplace_back( r.replace, r.cost );
}
}
return results;
}
auto index = path[ 0u ];
path.pop_front();
auto candidates = refine_expression_recurse( ctx, ctx._exprs[ e ]._children[ index ], path, rules );
std::vector<std::pair<unsigned,unsigned>> results;
for ( const auto& c : candidates )
{
std::vector<unsigned> new_children;
/* copy the children before index */
for ( auto i = 0u; i < index; ++i )
{
new_children.push_back( ctx._exprs[ e ]._children[ i ] );
}
/* add new instantiation */
new_children.push_back( c.first );
/* copy the children after index */
for ( auto i = index+1; i < ctx._exprs[ e ]._children.size(); ++i )
{
new_children.push_back( ctx._exprs[ e ]._children[ i ] );
}
results.emplace_back( ctx.make_fun( ctx._exprs[ e ]._name, new_children, ctx._exprs[ e ]._attr ), c.second );
}
return results;
}
path_t get_path_to_concretizable_element( context& ctx, unsigned e )
{
/* non-terminal */
if ( ctx._exprs[ e ]._name[0] == '_' )
{
return path_t( 0u );
}
/* variable or constant */
if ( ctx._exprs[ e ]._children.empty() )
{
return path_t( std::numeric_limits<unsigned>::max() );
}
/* others */
path_t min_path;
min_path.depth = std::numeric_limits<unsigned>::max();
for ( auto i = 0u; i < ctx._exprs[e]._children.size(); ++i )
{
auto path = get_path_to_concretizable_element( ctx, ctx._exprs[e]._children[ i ] );
if ( path < min_path )
{
auto new_path = path;
new_path.push_front( i );
min_path = new_path;
}
}
if ( min_path < std::numeric_limits<unsigned>::max() )
{
min_path.incr_depth();
}
return min_path;
}
bool is_concrete( context& ctx, unsigned e )
{
return get_path_to_concretizable_element( ctx, e ).invalid();
}
class enumerator
{
public:
using expr_queue_t = std::priority_queue<cexpr_t, std::vector<cexpr_t>, expr_greater_than>;
public:
enumerator( context& ctx, rules_t rules, int max_cost )
: ctx( ctx )
, rules(std::move( rules ))
, max_cost( max_cost )
, candidate_expressions( ctx ) /* pass ctx to the expr_greater_than */
{}
virtual ~enumerator() = default;
void add_expression( unsigned e );
void deduce( unsigned number_of_steps = 1u );
virtual bool is_redundant_in_search_order( unsigned e ) const;
bool check_double_application( unsigned e ) const;
bool check_idempotence_and_commutative( unsigned e ) const;
bool check_idempotence( unsigned e ) const;
bool check_commutativity( unsigned e ) const;
virtual void on_expression( cexpr_t e )
{
(void)e;
}
virtual void on_concrete_expression( cexpr_t e )
{
(void)e;
}
virtual void on_abstract_expression( cexpr_t e )
{
candidate_expressions.push( e );
}
void signal_termination()
{
quit_enumeration = true;
}
bool is_running() const
{
return !quit_enumeration;
}
protected:
context& ctx;
bool quit_enumeration = false;
rules_t rules;
unsigned max_cost;
expr_queue_t candidate_expressions;
unsigned current_costs = 0u;
};
void enumerator::add_expression( unsigned e )
{
candidate_expressions.push( { e, 0u } );
}
void enumerator::deduce( unsigned number_of_steps )
{
for ( auto i = 0u; i < number_of_steps; ++i )
{
if ( candidate_expressions.empty() )
{
quit_enumeration = true;
}
if ( !is_running() ) { return; }
auto next_candidate = candidate_expressions.top();
candidate_expressions.pop();
if ( next_candidate.second > current_costs )
{
std::cout << "[i] finished considering expressions of cost " << (current_costs+1u) << std::endl;
current_costs = next_candidate.second;
}
if ( next_candidate.second >= max_cost )
{
quit_enumeration = true;
continue;
}
auto p = get_path_to_concretizable_element( ctx, next_candidate.first );
auto new_candidates = refine_expression_recurse( ctx, next_candidate.first, p, rules );
for ( const auto& c : new_candidates )
{
if ( !is_running() ) break;
if ( is_redundant_in_search_order( c.first ) ) continue;
auto cc = cexpr_t{ c.first, next_candidate.second + c.second };
on_expression( cc );
if ( is_concrete( ctx, c.first ) )
{
on_concrete_expression(cc);
}
else
{
on_abstract_expression(cc);
}
}
}
}
bool enumerator::check_double_application( unsigned e ) const
{
const auto expr = ctx._exprs[ e ];
/* no double-negation */
if ( expr._name[0] != '_' && (expr._attr & expr_attr_enum::_no_double_application) == expr_attr_enum::_no_double_application )
{
assert( expr._children.size() == 1u );
const auto child0 = ctx._exprs[ expr._children[0u] ];
if ( child0._name == expr._name && child0._attr == expr_attr_enum::_no_double_application )
{
return true;
}
}
for ( const auto& c : expr._children )
{
if ( check_double_application( c ) )
{
return true;
}
}
return false;
}
void get_leaves_of_same_op_impl( context& ctx, unsigned e, const std::string& op, std::vector<unsigned>& leaves )
{
const auto expr = ctx._exprs[e];
for ( const auto& c : expr._children )
{
if ( ctx._exprs[c]._children.empty() && ctx._exprs[c]._name[0] != '_' )
{
leaves.emplace_back( c );
}
if ( ctx._exprs[c]._name == op )
{
get_leaves_of_same_op_impl( ctx, c, op, leaves );
}
}
}
// this function gets all the leaves of the chains of the same operation
std::vector<unsigned> get_leaves_of_same_op( context& ctx, unsigned e )
{
std::vector<unsigned> leaves;
const auto expr = ctx._exprs[e];
for ( const auto& c : expr._children )
{
if ( ctx._exprs[c]._children.empty() && ctx._exprs[c]._name[0] != '_' )
{
leaves.emplace_back( c );
}
if ( ctx._exprs[c]._name == expr._name )
{
get_leaves_of_same_op_impl( ctx, c, expr._name, leaves );
}
}
return leaves;
}
bool enumerator::check_idempotence( unsigned e ) const
{
// get all chains of same op starting from e
auto leaves = get_leaves_of_same_op( ctx, e );
// check for equal elements
if ( leaves.size() < 2 )
{
return false;
}
std::map<unsigned, unsigned> dup;
std::for_each( leaves.begin(), leaves.end(), [&dup]( unsigned val ) { dup[val]++; } );
auto result = std::find_if( dup.begin(), dup.end(), []( std::pair<const unsigned int, unsigned int> val ) { return val.second > 1; } );
return result != dup.end();
}
bool enumerator::check_commutativity( unsigned e ) const
{
// get all chains of same op starting from e
auto leaves = get_leaves_of_same_op( ctx, e );
// check ordering of elements
if ( leaves.size() < 2 )
{
return false;
}
if ( !std::is_sorted( leaves.begin(), leaves.end() ) )
{
return true;
}
return false;
}
bool enumerator::check_idempotence_and_commutative( unsigned e ) const
{
const auto is_set = []( unsigned value, unsigned flag ) { return ( ( value & flag ) == flag ); };
const auto expr = ctx._exprs[ e ];
if ( expr._name[0] != '_' && expr._children.size() == 2u &&
(ctx.count_nonterminals( expr._children[0u] ) == 0) &&
(ctx.count_nonterminals( expr._children[1u] ) == 0) )
{
if ( is_set( expr._attr, expr_attr_enum::_idempotent | expr_attr_enum::_commutative ) &&
expr._children[0u] >= expr._children[1u] )
{
return true;
}
else if ( is_set( expr._attr, expr_attr_enum::_commutative ) &&
expr._children[0u] > expr._children[1u] )
{
return true;
}
else if ( is_set( expr._attr, expr_attr_enum::_idempotent ) &&
expr._children[0u] == expr._children[1u] )
{
return true;
}
}
if ( expr._name[0] != '_' && expr._children.size() == 2u && is_set( expr._attr, expr_attr_enum::_idempotent ) )
{
if ( check_idempotence( e ) )
{
return true;
}
}
if ( expr._name[0] != '_' && expr._children.size() == 2u && is_set( expr._attr, expr_attr_enum::_commutative ) )
{
if ( check_commutativity( e ) )
{
return true;
}
}
for ( const auto& c : expr._children )
{
if ( check_idempotence_and_commutative( c ) )
{
return true;
}
}
return false;
}
bool enumerator::is_redundant_in_search_order( unsigned e ) const
{
if ( check_double_application( e ) )
{
return true;
}
if ( check_idempotence_and_commutative( e ) )
{
return true;
}
/* keep all other expressions */
return false;
}
} // namespace behemoth
// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:
| 24.391389
| 137
| 0.638639
|
gian21391
|
446ba9ba528732bbf9937cb572cec46831c742a7
| 18,187
|
cpp
|
C++
|
DBow/HVocabulary.cpp
|
jjzhang166/DBow
|
275d4504c8a008100f9a038abfe745a0c067e913
|
[
"BSD-3-Clause"
] | 33
|
2015-08-26T06:35:20.000Z
|
2021-08-04T05:23:10.000Z
|
DBow/HVocabulary.cpp
|
jjzhang166/DBow
|
275d4504c8a008100f9a038abfe745a0c067e913
|
[
"BSD-3-Clause"
] | null | null | null |
DBow/HVocabulary.cpp
|
jjzhang166/DBow
|
275d4504c8a008100f9a038abfe745a0c067e913
|
[
"BSD-3-Clause"
] | 13
|
2016-03-10T13:19:25.000Z
|
2021-04-14T10:00:26.000Z
|
/**
* File: HVocabulary.cpp
* Date: April 2010
* Author: Dorian Galvez
* Description: hierarchical vocabulary implementing (Nister, 2006)
*/
#include "HVocabulary.h"
#include "HVocParams.h"
#include "DUtils.h"
#include <cassert>
#include <algorithm>
#include <numeric>
#include <vector>
#include <cmath>
#include <fstream>
using namespace std;
using namespace DBow;
// Use Kmeans++
// (no other method supported currently)
#define KMEANS_PLUS_PLUS
HVocabulary::HVocabulary(const HVocParams ¶ms):
Vocabulary(params), m_params(params)
{
assert(params.k > 1 && params.L > 0);
}
HVocabulary::HVocabulary(const char *filename) :
Vocabulary(HVocParams(0,0)), m_params(HVocParams(0,0))
{
Load(filename);
}
HVocabulary::HVocabulary(const HVocabulary &voc) :
Vocabulary(voc), m_params(voc.m_params)
{
m_nodes = voc.m_nodes;
m_words.clear();
m_words.resize(voc.m_words.size());
vector<Node*>::const_iterator it;
for(it = voc.m_words.begin(); it != voc.m_words.end(); it++){
const Node *p = *it;
m_words[it - voc.m_words.begin()] = &m_nodes[p->Id];
}
}
HVocabulary::~HVocabulary(void)
{
}
void HVocabulary::Create(const vector<vector<float> >& training_features)
{
// expected_nodes = Sum_{i=0..L} ( k^i )
int expected_nodes =
(int)((pow((double)m_params.k, (double)m_params.L + 1) - 1)/(m_params.k - 1));
// remove previous tree, allocate memory and insert root node
m_nodes.resize(0);
m_nodes.reserve(expected_nodes); // prevents allocations when creating the tree
m_nodes.push_back(Node(0)); // root
// prepare data
int nfeatures = 0;
for(unsigned int i = 0; i < training_features.size(); i++){
assert(training_features[i].size() % m_params.DescriptorLength == 0);
nfeatures += training_features[i].size() / m_params.DescriptorLength;
}
vector<pFeature> pfeatures;
pfeatures.reserve(nfeatures);
vector<vector<float> >::const_iterator it;
vector<float>::const_iterator jt;
for(it = training_features.begin(); it != training_features.end(); it++){
for(jt = it->begin(); jt < it->end(); jt += m_params.DescriptorLength){
pfeatures.push_back( jt );
}
}
vector<float> buffer;
buffer.reserve( m_params.k * m_params.DescriptorLength );
// start hierarchical kmeans
HKMeansStep(0, pfeatures, 1, buffer);
// create word nodes
CreateWords();
// set the flag
m_created = true;
// set node weigths
SetNodeWeights(training_features);
}
void HVocabulary::HKMeansStep(NodeId parentId, const vector<pFeature> &pfeatures,
int level, vector<float>& clusters)
{
if(pfeatures.empty()) return;
// features associated to each cluster
vector<vector<unsigned int> > groups; // indices from pfeatures
groups.reserve(m_params.k);
// number of final clusters
int nclusters = 0;
if((int)pfeatures.size() <= m_params.k){
// trivial case: if there is a few features, each feature is a cluster
nclusters = pfeatures.size();
clusters.resize(pfeatures.size() * m_params.DescriptorLength);
groups.resize(pfeatures.size());
for(unsigned int i = 0; i < pfeatures.size(); i++){
copy(pfeatures[i], pfeatures[i] + m_params.DescriptorLength,
clusters.begin() + i * m_params.DescriptorLength);
groups[i].push_back(i);
}
}else{ // choose clusters with kmeans++
bool first_time = true;
bool goon = true;
vector<pFeature>::const_iterator fit;
// to check if clusters move after iterations
vector<int> last_association, current_association;
while(goon){
// 1. Calculate clusters
if(first_time){
// random sample
#ifdef KMEANS_PLUS_PLUS
RandomClustersPlusPlus(clusters, pfeatures);
#else
#error No initial clustering method
#endif
nclusters = clusters.size() / m_params.DescriptorLength;
}else{
// calculate cluster centres
vector<float>::iterator pfirst, pend, cit;
vector<unsigned int>::const_iterator vit;
for(int i = 0; i < nclusters; i++){
pfirst = clusters.begin() + i * m_params.DescriptorLength;
pend = clusters.begin() + (i+1) * m_params.DescriptorLength;
fill(pfirst, pend, 0.f);
for(vit = groups[i].begin(); vit != groups[i].end(); vit++){
fit = pfeatures.begin() + *vit;
// Possible improvement: divide this into chunks of 4 operations
for(cit = pfirst; cit != pend; cit++){
*cit += *((*fit) + (cit - pfirst));
}
}
for(cit = pfirst; cit != pend; cit++) *cit /= groups[i].size();
}
} // if(first_time)
// 2. Associate features with clusters
// calculate distances to cluster centers
groups.clear();
groups.resize(nclusters, vector<unsigned int>());
current_association.resize(pfeatures.size());
for(fit = pfeatures.begin(); fit != pfeatures.end(); fit++){
double best_sqd = DescriptorSqDistance(*fit, clusters.begin());
int icluster = 0;
for(int i = 1; i < nclusters; i++){
double sqd = DescriptorSqDistance(*fit,
clusters.begin() + i * m_params.DescriptorLength);
if(sqd < best_sqd){
best_sqd = sqd;
icluster = i;
}
}
groups[icluster].push_back(fit - pfeatures.begin());
current_association[ fit - pfeatures.begin() ] = icluster;
}
// remove clusters with no features
// (this is not necessary with kmeans++)
#ifndef KMEANS_PLUS_PLUS
for(int i = nclusters-1; i >= 0; i--){
if(groups[i].empty()){
groups.erase(groups.begin() + i);
clusters.erase(clusters.begin() + i * m_params.DescriptorLength,
clusters.begin() + (i+1) * m_params.DescriptorLength);
}
}
nclusters = groups.size();
#endif
// 3. check convergence
if(first_time){
first_time = false;
}else{
goon = false;
for(unsigned int i = 0; i < current_association.size(); i++){
if(current_association[i] != last_association[i]){
goon = true;
break;
}
}
}
if(goon){
// copy last feature-cluster association
last_association = current_association;
}
} // while(goon)
} // if trivial case
// Kmeans done, create nodes
// create child nodes
for(int i = 0; i < nclusters; i++){
NodeId id = m_nodes.size();
m_nodes.push_back(Node(id));
m_nodes.back().Descriptor.resize(m_params.DescriptorLength);
copy(clusters.begin() + i * m_params.DescriptorLength,
clusters.begin() + (i+1) * m_params.DescriptorLength,
m_nodes.back().Descriptor.begin());
m_nodes[parentId].Children.push_back(id);
}
if(level < m_params.L){
// iterate again with the resulting clusters
for(int i = 0; i < nclusters; i++){
NodeId id = m_nodes[m_nodes[parentId].Children[i]].Id;
vector<pFeature> child_features;
child_features.reserve(groups[i].size());
vector<unsigned int>::const_iterator vit;
for(vit = groups[i].begin(); vit != groups[i].end(); vit++){
child_features.push_back(pfeatures[*vit]);
}
if(child_features.size() > 1){
// (clusters variable can be safely reused now)
HKMeansStep(id, child_features, level + 1, clusters);
}
}
}
}
int HVocabulary::GetNumberOfWords() const
{
return m_words.size();
}
void HVocabulary::SaveBinary(const char *filename) const
{
// Format (binary):
// [Header]
// k L N
// NodeId_1 ParentId Weight d1 ... d_D
// ...
// NodeId_(N-1) ParentId Weight d1 ... d_D
// WordId_0 frequency NodeId
// ...
// WordId_(N-1) frequency NodeId
//
// Where:
// k (int32): branching factor
// L (int32): depth levels
// N (int32): number of nodes, including root
// NodeId (int32): root node is not present. Not in order
// ParentId (int32)
// Weight (double64)
// d_i (float32): descriptor entry
// WordId (int32): in ascending order
// frequency (float32): frequency of word
// NodeId (int32): node associated to word
//
// (the number along with the data type represents the size in bits)
DUtils::BinaryFile f(filename, DUtils::WRITE);
const int N = m_nodes.size();
// header
SaveBinaryHeader(f);
f << m_params.k << m_params.L << N;
// tree
vector<NodeId> parents, children;
vector<NodeId>::const_iterator pit;
parents.push_back(0); // root
while(!parents.empty()){
NodeId pid = parents.back();
parents.pop_back();
const Node& parent = m_nodes[pid];
children = parent.Children;
for(pit = children.begin(); pit != children.end(); pit++){
const Node& child = m_nodes[*pit];
// save node data
f << (int)child.Id << (int)pid << (double)child.Weight;
for(int i = 0; i < m_params.DescriptorLength; i++){
f << child.Descriptor[i];
}
// add to parent list
if(!child.isLeaf()){
parents.push_back(*pit);
}
}
}
// vocabulary
vector<Node*>::const_iterator wit;
for(wit = m_words.begin(); wit != m_words.end(); wit++){
WordId id = wit - m_words.begin();
f << (int)id << GetWordFrequency(id) << (int)(*wit)->Id;
}
f.Close();
}
void HVocabulary::SaveText(const char *filename) const
{
// Format (text)
// [Header]
// k L N
// NodeId_1 ParentId Weight d1 ... d_D
// ...
// NodeId_(N-1) ParentId Weight d1 ... d_D
// WordId_0 frequency NodeId
// ...
// WordId_(N-1) frequency NodeId
fstream f(filename, ios::out);
if(!f.is_open()) throw DUtils::DException("Cannot open file");
// magic word is not necessary in the text file
f.precision(10);
const int N = m_nodes.size();
// header
SaveTextHeader(f);
f << m_params.k << " " << m_params.L << " " << N << endl;
// tree
vector<NodeId> parents, children;
vector<NodeId>::const_iterator pit;
parents.push_back(0); // root
while(!parents.empty()){
NodeId pid = parents.back();
parents.pop_back();
const Node& parent = m_nodes[pid];
children = parent.Children;
for(pit = children.begin(); pit != children.end(); pit++){
const Node& child = m_nodes[*pit];
// save node data
f << child.Id << " "
<< pid << " "
<< child.Weight << " ";
for(int i = 0; i < m_params.DescriptorLength; i++){
f << child.Descriptor[i] << " ";
}
f << endl;
// add to parent list
if(!child.isLeaf()){
parents.push_back(*pit);
}
}
}
// vocabulary
vector<Node*>::const_iterator wit;
for(wit = m_words.begin(); wit != m_words.end(); wit++){
WordId id = wit - m_words.begin();
f << (int)id << " "
<< GetWordFrequency(id) << " "
<< (int)(*wit)->Id
<< endl;
}
f.close();
}
unsigned int HVocabulary::LoadBinary(const char *filename)
{
// Format (binary):
// [Header]
// k L N
// NodeId_1 ParentId Weight d1 ... d_D
// ...
// NodeId_(N-1) ParentId Weight d1 ... d_D
// WordId_0 frequency NodeId
// ...
// WordId_(N-1) frequency NodeId
DUtils::BinaryFile f(filename, DUtils::READ);
int nwords = LoadBinaryHeader(f);
_load<DUtils::BinaryFile>(f, nwords);
unsigned int ret = f.BytesRead();
f.Close();
return ret;
}
unsigned int HVocabulary::LoadText(const char *filename)
{
// Format (text)
// [Header]
// k L N
// NodeId_1 ParentId Weight d1 ... d_D
// ...
// NodeId_(N-1) ParentId Weight d1 ... d_D
// WordId_0 frequency NodeId
// ...
// WordId_(N-1) frequency NodeId
fstream f(filename, ios::in);
if(!f.is_open()) throw DUtils::DException("Cannot open file");
int nwords = LoadTextHeader(f);
_load<fstream>(f, nwords);
unsigned int ret = (unsigned int)f.tellg();
f.close();
return ret;
}
template<class T>
void HVocabulary::_load(T &f, int nwords)
{
// general header has already been read,
// giving value to these member variables
int nfreq = m_frequent_words_stopped;
int ninfreq = m_infrequent_words_stopped;
// removes nodes, words and frequencies
m_created = false;
m_words.clear();
m_nodes.clear();
m_word_frequency.clear();
// h header
int nnodes;
f >> m_params.k >> m_params.L >> nnodes;
// creates all the nodes at a time
m_nodes.resize(nnodes);
m_nodes[0].Id = 0; // root node
for(int i = 1; i < nnodes; i++){
int nodeid, parentid;
double weight;
f >> nodeid >> parentid >> weight;
m_nodes[nodeid].Id = nodeid;
m_nodes[nodeid].Weight = weight;
m_nodes[parentid].Children.push_back(nodeid);
m_nodes[nodeid].Descriptor.resize(m_params.DescriptorLength);
for(int j = 0; j < m_params.DescriptorLength; j++){
f >> m_nodes[nodeid].Descriptor[j];
}
}
m_words.resize(nwords);
m_word_frequency.resize(nwords);
for(int i = 0; i < nwords; i++){
int wordid, nodeid;
float frequency;
f >> wordid >> frequency >> nodeid;
m_nodes[nodeid].WId = wordid;
m_words[wordid] = &m_nodes[nodeid];
m_word_frequency[wordid] = frequency;
}
// all was ok
m_created = true;
// create an empty stop list
CreateStopList();
// and stop words
StopWords(nfreq, ninfreq);
}
void HVocabulary::RandomClustersPlusPlus(vector<float>& clusters,
const vector<pFeature> &pfeatures) const
{
// Implements kmeans++ seeding algorithm
// Algorithm:
// 1. Choose one center uniformly at random from among the data points.
// 2. For each data point x, compute D(x), the distance between x and the nearest
// center that has already been chosen.
// 3. Add one new data point as a center. Each point x is chosen with probability
// proportional to D(x)^2.
// 4. Repeat Steps 2 and 3 until k centers have been chosen.
// 5. Now that the initial centers have been chosen, proceed using standard k-means
// clustering.
clusters.resize(m_params.k * m_params.DescriptorLength);
vector<bool> feature_used(pfeatures.size(), false);
// 1.
int ifeature = DUtils::Random::RandomInt(0, pfeatures.size()-1);
feature_used[ifeature] = true;
// create first cluster
copy(pfeatures[ifeature], pfeatures[ifeature] + m_params.DescriptorLength,
clusters.begin());
int used_clusters = 1;
vector<double> sqdistances;
vector<int> ifeatures;
sqdistances.reserve(pfeatures.size());
ifeatures.reserve(pfeatures.size());
vector<pFeature>::const_iterator fit;
while(used_clusters < m_params.k){
// 2.
sqdistances.resize(0);
ifeatures.resize(0);
for(fit = pfeatures.begin(); fit != pfeatures.end(); fit++){
ifeature = fit - pfeatures.begin();
if(!feature_used[ifeature]){
double min_sqd = DescriptorSqDistance(*fit, clusters.begin());
for(int i = 1; i < used_clusters; i++){
double sqd = DescriptorSqDistance(*fit,
clusters.begin() + i * m_params.DescriptorLength);
if(sqd < min_sqd){
min_sqd = sqd;
}
}
sqdistances.push_back(min_sqd);
ifeatures.push_back(ifeature);
}
}
// 3.
double sqd_sum = accumulate(sqdistances.begin(), sqdistances.end(), 0.0);
if(sqd_sum > 0){
double cut_d;
do{
cut_d = DUtils::Random::RandomValue<double>(0, sqd_sum);
}while(cut_d == 0.0);
double d_up_now = 0;
vector<double>::iterator dit;
for(dit = sqdistances.begin(); dit != sqdistances.end(); dit++){
d_up_now += *dit;
if(d_up_now >= cut_d) break;
}
if(dit == sqdistances.end()) dit = sqdistances.begin() + sqdistances.size()-1;
ifeature = ifeatures[dit - sqdistances.begin()];
assert(!feature_used[ifeature]);
copy(pfeatures[ifeature], pfeatures[ifeature] + m_params.DescriptorLength,
clusters.begin() + used_clusters * m_params.DescriptorLength);
feature_used[ifeature] = true;
used_clusters++;
}else
break;
}
if(used_clusters < m_params.k)
clusters.resize(used_clusters * m_params.DescriptorLength);
}
double HVocabulary::DescriptorSqDistance(const pFeature &v,
const pFeature &w) const
{
double sqd = 0.0;
const int rest = m_params.DescriptorLength % 4;
for(int i = 0; i < m_params.DescriptorLength - rest; i += 4){
sqd += (*(v + i) - *(w + i)) * (*(v + i) - *(w + i));
sqd += (*(v + i + 1) - *(w + i + 1)) * (*(v + i + 1) - *(w + i + 1));
sqd += (*(v + i + 2) - *(w + i + 2)) * (*(v + i + 2) - *(w + i + 2));
sqd += (*(v + i + 3) - *(w + i + 3)) * (*(v + i + 3) - *(w + i + 3));
}
for(int i = m_params.DescriptorLength - rest; i < m_params.DescriptorLength; i++){
sqd += (*(v + i) - *(w + i)) * (*(v + i) - *(w + i));
}
return sqd;
}
void HVocabulary::SetNodeWeights(const vector<vector<float> >& training_features)
{
vector<WordValue> weights;
GetWordWeightsAndCreateStopList(training_features, weights);
assert(weights.size() == m_words.size());
for(unsigned int i = 0; i < m_words.size(); i++){
m_words[i]->Weight = weights[i];
}
}
WordId HVocabulary::Transform(const vector<float>::const_iterator &pfeature) const
{
if(isEmpty()) return 0;
assert(!m_nodes[0].isLeaf());
// propagate the feature down the tree
vector<NodeId> nodes;
vector<NodeId>::const_iterator it;
NodeId final_id = 0; // root
do{
nodes = m_nodes[final_id].Children;
final_id = nodes[0];
double best_sqd = DescriptorSqDistance(pfeature, m_nodes[final_id].Descriptor.begin());
for(it = nodes.begin() + 1; it != nodes.end(); it++){
NodeId id = *it;
double sqd = DescriptorSqDistance(pfeature, m_nodes[id].Descriptor.begin());
if(sqd < best_sqd){
best_sqd = sqd;
final_id = id;
}
}
} while( !m_nodes[final_id].isLeaf() );
// turn node id into word id
return m_nodes[final_id].WId;
}
void HVocabulary::CreateWords()
{
m_words.resize(0);
m_words.reserve( (int)pow((double)m_params.k, (double)m_params.L) );
// the actual order of the words is not important
vector<Node>::iterator it;
for(it = m_nodes.begin(); it != m_nodes.end(); it++){
if(it->isLeaf()){
it->WId = m_words.size();
m_words.push_back( &(*it) );
}
}
}
WordValue HVocabulary::GetWordWeight(WordId id) const
{
if(isEmpty()) return 0;
assert(id < m_words.size());
return m_words[id]->Weight;
}
| 25.400838
| 90
| 0.625392
|
jjzhang166
|
446d7d7cecaa283e60f7725f15bfbfea6e57a0af
| 5,096
|
cpp
|
C++
|
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/qhpwriter.cpp
|
GrinCash/Grinc-core
|
1377979453ba84082f70f9c128be38e57b65a909
|
[
"MIT"
] | null | null | null |
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/qhpwriter.cpp
|
GrinCash/Grinc-core
|
1377979453ba84082f70f9c128be38e57b65a909
|
[
"MIT"
] | null | null | null |
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qttools/src/assistant/qhelpconverter/qhpwriter.cpp
|
GrinCash/Grinc-core
|
1377979453ba84082f70f9c128be38e57b65a909
|
[
"MIT"
] | null | null | null |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QFile>
#include "qhpwriter.h"
#include "adpreader.h"
QT_BEGIN_NAMESPACE
QhpWriter::QhpWriter(const QString &namespaceName,
const QString &virtualFolder)
{
m_namespaceName = namespaceName;
m_virtualFolder = virtualFolder;
setAutoFormatting(true);
}
void QhpWriter::setAdpReader(AdpReader *reader)
{
m_adpReader = reader;
}
void QhpWriter::setFilterAttributes(const QStringList &attributes)
{
m_filterAttributes = attributes;
}
void QhpWriter::setCustomFilters(const QList<CustomFilter> filters)
{
m_customFilters = filters;
}
void QhpWriter::setFiles(const QStringList &files)
{
m_files = files;
}
void QhpWriter::generateIdentifiers(IdentifierPrefix prefix,
const QString prefixString)
{
m_prefix = prefix;
m_prefixString = prefixString;
}
bool QhpWriter::writeFile(const QString &fileName)
{
QFile out(fileName);
if (!out.open(QIODevice::WriteOnly))
return false;
setDevice(&out);
writeStartDocument();
writeStartElement(QLatin1String("QtHelpProject"));
writeAttribute(QLatin1String("version"), QLatin1String("1.0"));
writeTextElement(QLatin1String("namespace"), m_namespaceName);
writeTextElement(QLatin1String("virtualFolder"), m_virtualFolder);
writeCustomFilters();
writeFilterSection();
writeEndDocument();
out.close();
return true;
}
void QhpWriter::writeCustomFilters()
{
if (!m_customFilters.count())
return;
for (const CustomFilter &f : qAsConst(m_customFilters)) {
writeStartElement(QLatin1String("customFilter"));
writeAttribute(QLatin1String("name"), f.name);
for (const QString &a : f.filterAttributes)
writeTextElement(QLatin1String("filterAttribute"), a);
writeEndElement();
}
}
void QhpWriter::writeFilterSection()
{
writeStartElement(QLatin1String("filterSection"));
for (const QString &a : qAsConst(m_filterAttributes))
writeTextElement(QLatin1String("filterAttribute"), a);
writeToc();
writeKeywords();
writeFiles();
writeEndElement();
}
void QhpWriter::writeToc()
{
const QList<ContentItem> &list = m_adpReader->contents();
if (list.isEmpty())
return;
int depth = -1;
writeStartElement(QLatin1String("toc"));
for (const ContentItem &i : list) {
while (depth-- >= i.depth)
writeEndElement();
writeStartElement(QLatin1String("section"));
writeAttribute(QLatin1String("title"), i.title);
writeAttribute(QLatin1String("ref"), i.reference);
depth = i.depth;
}
while (depth-- >= -1)
writeEndElement();
}
void QhpWriter::writeKeywords()
{
const QList<KeywordItem> &list = m_adpReader->keywords();
if (list.isEmpty())
return;
writeStartElement(QLatin1String("keywords"));
for (const KeywordItem &i : list) {
writeEmptyElement(QLatin1String("keyword"));
writeAttribute(QLatin1String("name"), i.keyword);
writeAttribute(QLatin1String("ref"), i.reference);
if (m_prefix == FilePrefix) {
QString str = i.reference.mid(
i.reference.lastIndexOf(QLatin1Char('/')) + 1);
str = str.left(str.lastIndexOf(QLatin1Char('.')));
writeAttribute(QLatin1String("id"), str + QLatin1String("::") + i.keyword);
} else if (m_prefix == GlobalPrefix) {
writeAttribute(QLatin1String("id"), m_prefixString + i.keyword);
}
}
writeEndElement();
}
void QhpWriter::writeFiles()
{
if (m_files.isEmpty())
return;
writeStartElement(QLatin1String("files"));
for (const QString &f : qAsConst(m_files))
writeTextElement(QLatin1String("file"), f);
writeEndElement();
}
QT_END_NAMESPACE
| 29.627907
| 87
| 0.660911
|
GrinCash
|
446fe89cefa2483f6898bf6ff5c1d9a4eeecfa20
| 4,379
|
cpp
|
C++
|
rviz_default_plugins/src/rviz_default_plugins/tools/focus/focus_tool.cpp
|
romi2002/rviz
|
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
rviz_default_plugins/src/rviz_default_plugins/tools/focus/focus_tool.cpp
|
romi2002/rviz
|
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
rviz_default_plugins/src/rviz_default_plugins/tools/focus/focus_tool.cpp
|
romi2002/rviz
|
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
|
[
"BSD-3-Clause-Clear"
] | 1
|
2020-04-29T07:08:07.000Z
|
2020-04-29T07:08:07.000Z
|
/*
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sstream>
#ifndef _WIN32
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wpedantic"
#else
#pragma warning(push)
#pragma warning(disable : 4996)
#endif
#include <OgreCamera.h>
#include <OgreRay.h>
#include <OgreVector3.h>
#include <OgreViewport.h>
#ifndef _WIN32
# pragma GCC diagnostic pop
#else
# pragma warning(pop)
#endif
#include "rviz_common/display_context.hpp"
#include "rviz_common/interaction/view_picker_iface.hpp"
#include "rviz_common/load_resource.hpp"
#include "rviz_common/render_panel.hpp"
#include "rviz_common/viewport_mouse_event.hpp"
#include "rviz_common/view_controller.hpp"
#include "rviz_rendering/render_window.hpp"
#include "rviz_default_plugins/tools/focus/focus_tool.hpp"
namespace rviz_default_plugins
{
namespace tools
{
FocusTool::FocusTool()
: Tool()
{
shortcut_key_ = 'c';
}
FocusTool::~FocusTool() = default;
void FocusTool::onInitialize()
{
std_cursor_ = rviz_common::getDefaultCursor();
hit_cursor_ = rviz_common::makeIconCursor("package://rviz_common/icons/crosshair.svg");
}
void FocusTool::activate()
{}
void FocusTool::deactivate()
{}
int FocusTool::processMouseEvent(rviz_common::ViewportMouseEvent & event)
{
int flags = 0;
Ogre::Vector3 position;
bool success = context_->getViewPicker()->get3DPoint(event.panel, event.x, event.y, position);
setCursor(success ? hit_cursor_ : std_cursor_);
if (!success) {
computePositionForDirection(event, position);
setStatus("<b>Left-Click:</b> Look in this direction.");
} else {
setStatusFrom(position);
}
if (event.leftUp()) {
if (event.panel->getViewController()) {
event.panel->getViewController()->lookAt(position);
}
flags |= Finished;
}
return flags;
}
void FocusTool::setStatusFrom(const Ogre::Vector3 & position)
{
std::ostringstream s;
s << "<b>Left-Click:</b> Focus on this point.";
s.precision(3);
s << " [" << position.x << "," << position.y << "," << position.z << "]";
setStatus(s.str().c_str());
}
void FocusTool::computePositionForDirection(
const rviz_common::ViewportMouseEvent & event, Ogre::Vector3 & position)
{
auto viewport =
rviz_rendering::RenderWindowOgreAdapter::getOgreViewport(event.panel->getRenderWindow());
Ogre::Ray mouse_ray = viewport->getCamera()->getCameraToViewportRay(
static_cast<float>(event.x) / static_cast<float>(viewport->getActualWidth()),
static_cast<float>(event.y) / static_cast<float>(viewport->getActualHeight()));
position = mouse_ray.getPoint(1.0);
}
} // namespace tools
} // namespace rviz_default_plugins
#include <pluginlib/class_list_macros.hpp> // NOLINT
PLUGINLIB_EXPORT_CLASS(rviz_default_plugins::tools::FocusTool, rviz_common::Tool)
| 31.278571
| 96
| 0.738982
|
romi2002
|
4471948114cf73b9e901df5d96ea11fae039b912
| 1,899
|
cxx
|
C++
|
Remoting/Core/vtkPVOptionsXMLParser.cxx
|
xj361685640/ParaView
|
0a27eef5abc5a0c0472ab0bc806c4db881156e64
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 815
|
2015-01-03T02:14:04.000Z
|
2022-03-26T07:48:07.000Z
|
Remoting/Core/vtkPVOptionsXMLParser.cxx
|
xj361685640/ParaView
|
0a27eef5abc5a0c0472ab0bc806c4db881156e64
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 9
|
2015-04-28T20:10:37.000Z
|
2021-08-20T18:19:01.000Z
|
Remoting/Core/vtkPVOptionsXMLParser.cxx
|
xj361685640/ParaView
|
0a27eef5abc5a0c0472ab0bc806c4db881156e64
|
[
"Apache-2.0",
"BSD-3-Clause"
] | 328
|
2015-01-22T23:11:46.000Z
|
2022-03-14T06:07:52.000Z
|
/*=========================================================================
Module: vtkPVOptionsXMLParser.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPVOptionsXMLParser.h"
#include "vtkObjectFactory.h"
#include "vtkPVOptions.h"
#include <vtksys/SystemTools.hxx>
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPVOptionsXMLParser);
//----------------------------------------------------------------------------
void vtkPVOptionsXMLParser::SetProcessType(const char* ptype)
{
if (!ptype)
{
this->SetProcessTypeInt(vtkCommandOptions::EVERYBODY);
return;
}
std::string type = vtksys::SystemTools::LowerCase((ptype ? ptype : ""));
if (type == "client")
{
this->SetProcessTypeInt(vtkPVOptions::PVCLIENT);
return;
}
if (type == "server")
{
this->SetProcessTypeInt(vtkPVOptions::PVSERVER);
return;
}
if (type == "render-server" || type == "renderserver")
{
this->SetProcessTypeInt(vtkPVOptions::PVRENDER_SERVER);
return;
}
if (type == "data-server" || type == "dataserver")
{
this->SetProcessTypeInt(vtkPVOptions::PVDATA_SERVER);
return;
}
if (type == "paraview")
{
this->SetProcessTypeInt(vtkPVOptions::PARAVIEW);
return;
}
this->Superclass::SetProcessType(ptype);
}
//----------------------------------------------------------------------------
void vtkPVOptionsXMLParser::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| 27.521739
| 78
| 0.557662
|
xj361685640
|
4472ac1711ff3cc4ab2f07de2143fcfab8d06bb9
| 11,047
|
cpp
|
C++
|
src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
|
mehrdad-shokri/OpenStudio
|
1773b54ce1cb660818ac0114dd7eefae6639ca36
|
[
"blessing"
] | null | null | null |
src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
|
mehrdad-shokri/OpenStudio
|
1773b54ce1cb660818ac0114dd7eefae6639ca36
|
[
"blessing"
] | null | null | null |
src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
|
mehrdad-shokri/OpenStudio
|
1773b54ce1cb660818ac0114dd7eefae6639ca36
|
[
"blessing"
] | null | null | null |
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include <gtest/gtest.h>
#include "EnergyPlusFixture.hpp"
#include "../ErrorFile.hpp"
#include "../ForwardTranslator.hpp"
#include "../ReverseTranslator.hpp"
// Objects of interest
#include "../../model/GeneratorMicroTurbine.hpp"
#include "../../model/GeneratorMicroTurbine_Impl.hpp"
#include "../../model/GeneratorMicroTurbineHeatRecovery.hpp"
#include "../../model/GeneratorMicroTurbineHeatRecovery_Impl.hpp"
// Needed resources
#include "../../model/PlantLoop.hpp"
#include "../../model/PlantLoop_Impl.hpp"
#include "../../model/Node.hpp"
#include "../../model/Node_Impl.hpp"
#include "../../model/Curve.hpp"
#include "../../model/Curve_Impl.hpp"
#include "../../model/CurveBiquadratic.hpp"
#include "../../model/CurveBiquadratic_Impl.hpp"
#include "../../model/CurveCubic.hpp"
#include "../../model/CurveCubic_Impl.hpp"
#include "../../model/CurveQuadratic.hpp"
#include "../../model/CurveQuadratic_Impl.hpp"
#include "../../model/StraightComponent.hpp"
#include "../../model/StraightComponent_Impl.hpp"
#include "../../model/Schedule.hpp"
#include "../../model/Schedule_Impl.hpp"
// For testing PlantEquipOperation
#include "../../model/WaterHeaterMixed.hpp"
#include "../../model/WaterHeaterMixed_Impl.hpp"
#include "../../model/PlantEquipmentOperationHeatingLoad.hpp"
#include "../../model/PlantEquipmentOperationHeatingLoad_Impl.hpp"
#include "../../model/ElectricLoadCenterDistribution.hpp"
#include "../../model/ElectricLoadCenterDistribution_Impl.hpp"
// IDF FieldEnums
#include <utilities/idd/Generator_MicroTurbine_FieldEnums.hxx>
// #include <utilities/idd/OS_Generator_MicroTurbine_HeatRecovery_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentList_FieldEnums.hxx>
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/IddFactory.hxx>
// Misc
#include "../../model/Version.hpp"
#include "../../model/Version_Impl.hpp"
#include "../../utilities/core/Optional.hpp"
#include "../../utilities/core/Checksum.hpp"
#include "../../utilities/core/UUID.hpp"
#include "../../utilities/sql/SqlFile.hpp"
#include "../../utilities/idf/IdfFile.hpp"
#include "../../utilities/idf/IdfObject.hpp"
#include "../../utilities/idf/IdfExtensibleGroup.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <resources.hxx>
#include <sstream>
#include <vector>
// Debug
#include "../../utilities/core/Logger.hpp"
using namespace openstudio::energyplus;
using namespace openstudio::model;
using namespace openstudio;
/**
* Tests whether the ForwarTranslator will handle the name of the GeneratorMicroTurbine correctly in the PlantEquipmentOperationHeatingLoad
**/
TEST_F(EnergyPlusFixture,ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop)
{
// TODO: Temporarily output the Log in the console with the Trace (-3) level
// for debug
// openstudio::Logger::instance().standardOutLogger().enable();
// openstudio::Logger::instance().standardOutLogger().setLogLevel(Trace);
// Create a model, a mchp, a mchpHR, a plantLoop and an electricalLoadCenter
Model model;
GeneratorMicroTurbine mchp = GeneratorMicroTurbine(model);
GeneratorMicroTurbineHeatRecovery mchpHR = GeneratorMicroTurbineHeatRecovery(model, mchp);
ASSERT_EQ(mchpHR, mchp.generatorMicroTurbineHeatRecovery().get());
PlantLoop plantLoop(model);
// Add a supply branch for the mchpHR
ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(mchpHR));
// Create a WaterHeater:Mixed
WaterHeaterMixed waterHeater(model);
// Add it on the same branch as the chpHR, right after it
Node mchpHROutletNode = mchpHR.outletModelObject()->cast<Node>();
ASSERT_TRUE(waterHeater.addToNode(mchpHROutletNode));
// Create a plantEquipmentOperationHeatingLoad
PlantEquipmentOperationHeatingLoad operation(model);
operation.setName(plantLoop.name().get() + " PlantEquipmentOperationHeatingLoad");
ASSERT_TRUE(plantLoop.setPlantEquipmentOperationHeatingLoad(operation));
ASSERT_TRUE(operation.addEquipment(mchpHR));
ASSERT_TRUE(operation.addEquipment(waterHeater));
// Create an ELCD
ElectricLoadCenterDistribution elcd = ElectricLoadCenterDistribution(model);
elcd.setName("Capstone C65 ELCD");
elcd.setElectricalBussType("AlternatingCurrent");
elcd.addGenerator(mchp);
// Forward Translates
ForwardTranslator forwardTranslator;
Workspace workspace = forwardTranslator.translateModel(model);
EXPECT_EQ(0u, forwardTranslator.errors().size());
ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::WaterHeater_Mixed).size());
ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::ElectricLoadCenter_Distribution).size());
// The MicroTurbine should have been forward translated since there is an ELCD
WorkspaceObjectVector microTurbineObjects(workspace.getObjectsByType(IddObjectType::Generator_MicroTurbine));
EXPECT_EQ(1u, microTurbineObjects.size());
// Check that the HR nodes have been set
WorkspaceObject idf_mchp(microTurbineObjects[0]);
EXPECT_EQ(mchpHR.inletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterInletNodeName).get());
EXPECT_EQ(mchpHR.outletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterOutletNodeName).get());
OptionalWorkspaceObject idf_operation(workspace.getObjectByTypeAndName(IddObjectType::PlantEquipmentOperation_HeatingLoad,*(operation.name())));
ASSERT_TRUE(idf_operation);
// Get the extensible
ASSERT_EQ(1u, idf_operation->numExtensibleGroups());
// IdfExtensibleGroup eg = idf_operation.getExtensibleGroup(0);
// idf_operation.targets[0]
ASSERT_EQ(1u, idf_operation->targets().size());
WorkspaceObject plantEquipmentList(idf_operation->targets()[0]);
ASSERT_EQ(2u, plantEquipmentList.extensibleGroups().size());
IdfExtensibleGroup eg(plantEquipmentList.extensibleGroups()[0]);
ASSERT_EQ("Generator:MicroTurbine", eg.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get());
// This fails
EXPECT_EQ(mchp.name().get(), eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());
IdfExtensibleGroup eg2(plantEquipmentList.extensibleGroups()[1]);
ASSERT_EQ("WaterHeater:Mixed", eg2.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get());
EXPECT_EQ(waterHeater.name().get(), eg2.getString(PlantEquipmentListExtensibleFields::EquipmentName).get());
// model.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.osm"), true);
// workspace.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.idf"), true);
}
//test orphaning the generator before FT
TEST_F(EnergyPlusFixture, ForwardTranslatorGeneratorMicroTurbine_ELCD_Orphan)
{
// Create a model, a mchp, a mchpHR, a plantLoop and an electricalLoadCenter
Model model;
GeneratorMicroTurbine mchp = GeneratorMicroTurbine(model);
GeneratorMicroTurbineHeatRecovery mchpHR = GeneratorMicroTurbineHeatRecovery(model, mchp);
ASSERT_EQ(mchpHR, mchp.generatorMicroTurbineHeatRecovery().get());
PlantLoop plantLoop(model);
// Add a supply branch for the mchpHR
ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(mchpHR));
// Create a WaterHeater:Mixed
WaterHeaterMixed waterHeater(model);
// Add it on the same branch as the chpHR, right after it
Node mchpHROutletNode = mchpHR.outletModelObject()->cast<Node>();
ASSERT_TRUE(waterHeater.addToNode(mchpHROutletNode));
EXPECT_TRUE(waterHeater.plantLoop());
// Create a plantEquipmentOperationHeatingLoad
PlantEquipmentOperationHeatingLoad operation(model);
operation.setName(plantLoop.name().get() + " PlantEquipmentOperationHeatingLoad");
ASSERT_TRUE(plantLoop.setPlantEquipmentOperationHeatingLoad(operation));
ASSERT_TRUE(operation.addEquipment(mchpHR));
ASSERT_TRUE(operation.addEquipment(waterHeater));
// Create an ELCD
ElectricLoadCenterDistribution elcd = ElectricLoadCenterDistribution(model);
elcd.setName("Capstone C65 ELCD");
elcd.setElectricalBussType("AlternatingCurrent");
elcd.addGenerator(mchp);
// orphan the generator from the ELCD
boost::optional<ElectricLoadCenterDistribution> elcd2 = mchp.electricLoadCenterDistribution();
elcd2.get().remove();
EXPECT_FALSE(mchp.electricLoadCenterDistribution());
// Forward Translates
ForwardTranslator forwardTranslator;
Workspace workspace = forwardTranslator.translateModel(model);
EXPECT_EQ(0u, forwardTranslator.errors().size());
//ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::WaterHeater_Mixed).size());
ASSERT_EQ(0u, workspace.getObjectsByType(IddObjectType::ElectricLoadCenter_Distribution).size());
// model.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_orhpan.osm"), true);
// workspace.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_orphan.idf"), true);
}
| 46.029167
| 146
| 0.76437
|
mehrdad-shokri
|
447336c8bdeda9ca261722539acddb9480c4cf48
| 9,889
|
cc
|
C++
|
init/file_attrs_cleaner_test.cc
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 4
|
2020-07-24T06:54:16.000Z
|
2021-06-16T17:13:53.000Z
|
init/file_attrs_cleaner_test.cc
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 1
|
2021-04-02T17:35:07.000Z
|
2021-04-02T17:35:07.000Z
|
init/file_attrs_cleaner_test.cc
|
strassek/chromiumos-platform2
|
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
|
[
"BSD-3-Clause"
] | 1
|
2020-11-04T22:31:45.000Z
|
2020-11-04T22:31:45.000Z
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "init/file_attrs_cleaner.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/xattr.h>
#include <linux/fs.h>
#include <string>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/files/scoped_temp_dir.h>
#include <gtest/gtest.h>
using file_attrs_cleaner::AttributeCheckStatus;
using file_attrs_cleaner::CheckFileAttributes;
using file_attrs_cleaner::ImmutableAllowed;
using file_attrs_cleaner::RemoveURLExtendedAttributes;
using file_attrs_cleaner::ScanDir;
namespace {
// Helper to create a test file.
bool CreateFile(const base::FilePath& file_path, base::StringPiece content) {
if (!base::CreateDirectory(file_path.DirName()))
return false;
return base::WriteFile(file_path, content.data(), content.size()) ==
content.size();
}
} // namespace
namespace {
class CheckFileAttributesTest : public ::testing::Test {
void SetUp() {
ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
test_dir_ = scoped_temp_dir_.GetPath();
}
protected:
// Setting file attributes (like immutable) requires privileges.
// If we don't have that, we can't validate these tests :/.
bool CanSetFileAttributes() {
const base::FilePath path = test_dir_.Append(".attrs.test");
base::ScopedFD fd(open(path.value().c_str(),
O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, 0600));
if (!fd.is_valid())
abort();
long flags; // NOLINT(runtime/int)
if (ioctl(fd.get(), FS_IOC_GETFLAGS, &flags) != 0)
abort();
flags |= FS_IMMUTABLE_FL;
if (ioctl(fd.get(), FS_IOC_SETFLAGS, &flags) != 0) {
PLOG(WARNING) << "Unable to test immutable bit behavior";
if (errno != EPERM)
abort();
return false;
}
return true;
}
base::FilePath test_dir_;
base::ScopedTempDir scoped_temp_dir_;
};
} // namespace
TEST_F(CheckFileAttributesTest, BadFd) {
const base::FilePath path = test_dir_.Append("asdf");
EXPECT_EQ(AttributeCheckStatus::ERROR, CheckFileAttributes(path, false, -1));
EXPECT_EQ(AttributeCheckStatus::ERROR, CheckFileAttributes(path, true, -1));
EXPECT_EQ(AttributeCheckStatus::ERROR, CheckFileAttributes(path, true, 1000));
EXPECT_EQ(AttributeCheckStatus::ERROR,
CheckFileAttributes(path, false, 1000));
}
// Accept paths w/out the immutable bit set.
TEST_F(CheckFileAttributesTest, NormalPaths) {
const base::FilePath path = test_dir_.Append("file");
ASSERT_TRUE(CreateFile(path, ""));
base::ScopedFD fd(open(path.value().c_str(), O_RDONLY | O_CLOEXEC));
ASSERT_TRUE(fd.is_valid());
EXPECT_EQ(AttributeCheckStatus::NO_ATTR,
CheckFileAttributes(path, false, fd.get()));
const base::FilePath dir = test_dir_.Append("dir");
ASSERT_EQ(0, mkdir(dir.value().c_str(), 0700));
fd.reset(open(dir.value().c_str(), O_RDONLY | O_CLOEXEC));
ASSERT_TRUE(fd.is_valid());
EXPECT_EQ(AttributeCheckStatus::NO_ATTR,
CheckFileAttributes(dir, false, fd.get()));
}
// Clear files w/the immutable bit set.
TEST_F(CheckFileAttributesTest, ResetFile) {
if (!CanSetFileAttributes()) {
SUCCEED();
return;
}
const base::FilePath path = test_dir_.Append("file");
ASSERT_TRUE(CreateFile(path, ""));
base::ScopedFD fd(open(path.value().c_str(), O_RDONLY | O_CLOEXEC));
ASSERT_TRUE(fd.is_valid());
long flags; // NOLINT(runtime/int)
EXPECT_EQ(0, ioctl(fd.get(), FS_IOC_GETFLAGS, &flags));
flags |= FS_IMMUTABLE_FL;
EXPECT_EQ(0, ioctl(fd.get(), FS_IOC_SETFLAGS, &flags));
EXPECT_EQ(AttributeCheckStatus::CLEARED,
CheckFileAttributes(path, false, fd.get()));
}
// Clear dirs w/the immutable bit set.
TEST_F(CheckFileAttributesTest, ResetDir) {
if (!CanSetFileAttributes()) {
SUCCEED();
return;
}
const base::FilePath dir = test_dir_.Append("dir");
ASSERT_EQ(0, mkdir(dir.value().c_str(), 0700));
base::ScopedFD fd(open(dir.value().c_str(), O_RDONLY | O_CLOEXEC));
ASSERT_TRUE(fd.is_valid());
long flags; // NOLINT(runtime/int)
EXPECT_EQ(0, ioctl(fd.get(), FS_IOC_GETFLAGS, &flags));
flags |= FS_IMMUTABLE_FL;
EXPECT_EQ(0, ioctl(fd.get(), FS_IOC_SETFLAGS, &flags));
EXPECT_EQ(AttributeCheckStatus::CLEARED,
CheckFileAttributes(dir, false, fd.get()));
}
namespace {
class RemoveURLExtendedAttributesTest : public ::testing::Test {
void SetUp() {
ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
test_dir_ = scoped_temp_dir_.GetPath();
}
protected:
base::FilePath test_dir_;
base::ScopedTempDir scoped_temp_dir_;
};
} // namespace
// Don't fail when files don't have extended attributes.
TEST_F(RemoveURLExtendedAttributesTest, NoAttributesSucceeds) {
const base::FilePath path = test_dir_.Append("xattr");
ASSERT_TRUE(CreateFile(path, ""));
EXPECT_EQ(AttributeCheckStatus::NO_ATTR, RemoveURLExtendedAttributes(path));
}
// Clear files with the "xdg" xattrs set, see crbug.com/919486.
TEST_F(RemoveURLExtendedAttributesTest, Success) {
const base::FilePath path = test_dir_.Append("xattr");
ASSERT_TRUE(CreateFile(path, ""));
const char* path_cstr = path.value().c_str();
EXPECT_EQ(
0, setxattr(path_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0, 0));
EXPECT_EQ(
0, setxattr(path_cstr, file_attrs_cleaner::xdg_referrer_url, NULL, 0, 0));
EXPECT_EQ(AttributeCheckStatus::CLEARED, RemoveURLExtendedAttributes(path));
// getxattr(2) call should fail now.
EXPECT_GT(0,
getxattr(path_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0));
EXPECT_GT(0,
getxattr(path_cstr, file_attrs_cleaner::xdg_referrer_url, NULL, 0));
}
// Leave other attributes alone.
TEST_F(RemoveURLExtendedAttributesTest, OtherAttributesUnchanged) {
const base::FilePath path = test_dir_.Append("xattr");
ASSERT_TRUE(CreateFile(path, ""));
EXPECT_EQ(0, setxattr(path.value().c_str(), "user.test", NULL, 0, 0));
EXPECT_EQ(AttributeCheckStatus::NO_ATTR, RemoveURLExtendedAttributes(path));
// getxattr(2) call should succeed.
EXPECT_EQ(0, getxattr(path.value().c_str(), "user.test", NULL, 0));
}
namespace {
class ScanDirTest : public ::testing::Test {
void SetUp() {
ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
test_dir_ = scoped_temp_dir_.GetPath();
url_xattrs_count_ = 0;
}
protected:
base::FilePath test_dir_;
base::ScopedTempDir scoped_temp_dir_;
int url_xattrs_count_;
};
} // namespace
TEST_F(ScanDirTest, Empty) {
EXPECT_TRUE(ScanDir(test_dir_, {}, &url_xattrs_count_));
}
TEST_F(ScanDirTest, Leaf) {
CreateFile(test_dir_.Append("file1"), "");
CreateFile(test_dir_.Append("file2"), "");
EXPECT_TRUE(ScanDir(test_dir_, {}, &url_xattrs_count_));
}
TEST_F(ScanDirTest, Nested) {
CreateFile(test_dir_.Append("file1"), "");
CreateFile(test_dir_.Append("file2"), "");
EXPECT_TRUE(base::CreateDirectory(test_dir_.Append("emptydir")));
const base::FilePath dir1(test_dir_.Append("dir1"));
EXPECT_TRUE(base::CreateDirectory(dir1));
CreateFile(dir1.Append("file1"), "");
CreateFile(dir1.Append("file2"), "");
EXPECT_TRUE(base::CreateDirectory(dir1.Append("emptydir")));
const base::FilePath dir2(dir1.Append("dir1"));
EXPECT_TRUE(base::CreateDirectory(dir2));
CreateFile(dir2.Append("file1"), "");
CreateFile(dir2.Append("file2"), "");
EXPECT_TRUE(base::CreateDirectory(dir2.Append("emptydir")));
EXPECT_TRUE(ScanDir(test_dir_, {}, &url_xattrs_count_));
}
TEST_F(ScanDirTest, RecurseAndClearAttributes) {
const base::FilePath file1 = test_dir_.Append("file1");
CreateFile(file1, "");
CreateFile(test_dir_.Append("file1"), "");
CreateFile(test_dir_.Append("file2"), "");
const base::FilePath subdir(test_dir_.Append("subdir"));
EXPECT_TRUE(base::CreateDirectory(subdir));
const base::FilePath subfile1(subdir.Append("subfile1"));
const base::FilePath subfile2(subdir.Append("subfile2"));
const base::FilePath subfile3(subdir.Append("subfile3"));
CreateFile(subfile1, "");
CreateFile(subfile2, "");
CreateFile(subfile3, "");
const char* file1_cstr = file1.value().c_str();
const char* subf1_cstr = subfile1.value().c_str();
const char* subf3_cstr = subfile3.value().c_str();
EXPECT_EQ(
0, setxattr(file1_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0, 0));
EXPECT_EQ(
0, setxattr(subf1_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0, 0));
EXPECT_EQ(
0, setxattr(subf3_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0, 0));
EXPECT_TRUE(ScanDir(test_dir_, {}, &url_xattrs_count_));
EXPECT_EQ(url_xattrs_count_, 3);
EXPECT_GT(0,
getxattr(file1_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0));
EXPECT_GT(0,
getxattr(subf1_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0));
EXPECT_GT(0,
getxattr(subf3_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0));
}
TEST_F(ScanDirTest, SkipRecurse) {
CreateFile(test_dir_.Append("file1"), "");
CreateFile(test_dir_.Append("file2"), "");
const base::FilePath subdir(test_dir_.Append("subdir"));
EXPECT_TRUE(base::CreateDirectory(subdir));
const base::FilePath subfile(subdir.Append("subfile"));
CreateFile(subfile, "");
const char* subf_cstr = subfile.value().c_str();
EXPECT_EQ(
0, setxattr(subf_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0, 0));
std::vector<std::string> skip = {"subdir"};
EXPECT_TRUE(ScanDir(test_dir_, skip, &url_xattrs_count_));
EXPECT_EQ(0,
getxattr(subf_cstr, file_attrs_cleaner::xdg_origin_url, NULL, 0));
}
TEST_F(ScanDirTest, InvalidDirSucceeds) {
const base::FilePath subdir(
test_dir_.Append("this_dir_definitely_does_not_exist"));
EXPECT_TRUE(ScanDir(subdir, {}, &url_xattrs_count_));
}
| 31.294304
| 80
| 0.707857
|
strassek
|
4475715a4c17dea905da48f2ef8f4c8919066a38
| 5,129
|
cpp
|
C++
|
lib/src/textures.cpp
|
konstructs/client
|
2616d2c37dd97b6e799e933fe0b932fd2e7c27d4
|
[
"MIT"
] | 48
|
2015-05-15T19:51:40.000Z
|
2021-06-08T14:55:48.000Z
|
lib/src/textures.cpp
|
konstructs/client
|
2616d2c37dd97b6e799e933fe0b932fd2e7c27d4
|
[
"MIT"
] | 180
|
2015-05-09T16:28:28.000Z
|
2020-12-20T19:53:54.000Z
|
lib/src/textures.cpp
|
konstructs/client
|
2616d2c37dd97b6e799e933fe0b932fd2e7c27d4
|
[
"MIT"
] | 14
|
2015-07-17T20:32:13.000Z
|
2021-03-12T07:52:33.000Z
|
#include <fstream>
#include <streambuf>
#include <gl_includes.h>
#include <iostream>
#include <cstdlib>
#include "textures.h"
#include "util.h"
#define KONSTRUCTS_PATH_SIZE 256
namespace konstructs {
void shtxt_path(const char *name, const char *type, char *path, size_t max_len) {
snprintf(path, max_len, "%s/%s", type, name);
if (!file_exist(path)) {
if(const char* env_p = std::getenv("SNAP")) {
snprintf(path, max_len, "%s/%s/%s", env_p, type, name);
}
}
if (!file_exist(path)) {
snprintf(path, max_len, "../%s/%s", type, name);
}
if (!file_exist(path)) {
snprintf(path, max_len, "/usr/local/share/konstructs-client/%s/%s", type, name);
}
if (!file_exist(path)) {
printf("Error, no %s for %s found.\n", type, name);
exit(1);
}
}
void texture_path(const char *name, char *path, size_t max_len) {
shtxt_path(name, "textures", path, max_len);
}
void model_path(const char *name, char *path, size_t max_len) {
shtxt_path(name, "models", path, max_len);
}
void shader_path(const char *name, char *path, size_t max_len) {
shtxt_path(name, "shaders", path, max_len);
}
void load_textures() {
char txtpth[KONSTRUCTS_PATH_SIZE];
GLuint sky;
glGenTextures(1, &sky);
glActiveTexture(GL_TEXTURE0 + SKY_TEXTURE);
glBindTexture(GL_TEXTURE_2D, sky);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
texture_path("sky.png", txtpth, KONSTRUCTS_PATH_SIZE);
load_png_texture(txtpth);
GLuint font;
glGenTextures(1, &font);
glActiveTexture(GL_TEXTURE0 + FONT_TEXTURE);
glBindTexture(GL_TEXTURE_2D, font);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
texture_path("font.png", txtpth, KONSTRUCTS_PATH_SIZE);
load_png_texture(txtpth);
GLuint inventory_texture;
glGenTextures(1, &inventory_texture);
glActiveTexture(GL_TEXTURE0 + INVENTORY_TEXTURE);
glBindTexture(GL_TEXTURE_2D, inventory_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texture_path("inventory.png", txtpth, KONSTRUCTS_PATH_SIZE);
load_png_texture(txtpth);
GLuint player_texture;
glGenTextures(1, &player_texture);
glActiveTexture(GL_TEXTURE0 + PLAYER_TEXTURE);
glBindTexture(GL_TEXTURE_2D, player_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texture_path("player.png", txtpth, KONSTRUCTS_PATH_SIZE);
load_png_texture(txtpth);
GLuint damage_texture;
glGenTextures(1, &damage_texture);
glActiveTexture(GL_TEXTURE0 + DAMAGE_TEXTURE);
glBindTexture(GL_TEXTURE_2D, damage_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texture_path("damage.png", txtpth, KONSTRUCTS_PATH_SIZE);
load_png_texture(txtpth);
GLuint health_bar_texture;
glGenTextures(1, &health_bar_texture);
glActiveTexture(GL_TEXTURE0 + HEALTH_BAR_TEXTURE);
glBindTexture(GL_TEXTURE_2D, health_bar_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texture_path("health_bar.png", txtpth, KONSTRUCTS_PATH_SIZE);
load_png_texture(txtpth);
// Set Active texture to GL_TEXTURE0, nanogui will use the active texture
glActiveTexture(GL_TEXTURE0);
}
tinyobj::shape_t load_player() {
char objpth[KONSTRUCTS_PATH_SIZE];
model_path("player.obj", objpth, KONSTRUCTS_PATH_SIZE);
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err;
tinyobj::LoadObj(shapes, materials, err, objpth);
return shapes[0];
}
std::string load_shader(const char* name) {
char shader_pth[KONSTRUCTS_PATH_SIZE];
shader_path(name, shader_pth, KONSTRUCTS_PATH_SIZE);
std::ifstream shader(shader_pth);
std::string shader_str((std::istreambuf_iterator<char>(shader)),
std::istreambuf_iterator<char>());
return shader_str;
}
std::string load_chunk_vertex_shader() {
return load_shader("chunk.vert");
}
std::string load_chunk_fragment_shader() {
return load_shader("chunk.frag");
}
};
| 36.899281
| 92
| 0.666797
|
konstructs
|
4476251d4084b04d1d79b25f1d4cb70694b07750
| 14,334
|
ipp
|
C++
|
boost/test/impl/framework.ipp
|
jonstewart/boost-svn
|
7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59
|
[
"BSL-1.0"
] | 1
|
2017-04-08T10:44:28.000Z
|
2017-04-08T10:44:28.000Z
|
boost/test/impl/framework.ipp
|
jonstewart/boost-svn
|
7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59
|
[
"BSL-1.0"
] | null | null | null |
boost/test/impl/framework.ipp
|
jonstewart/boost-svn
|
7f6dc0c0cb807b28072c7bdd3d77bb01ab290c59
|
[
"BSL-1.0"
] | null | null | null |
// (C) Copyright Gennadiy Rozental 2005-2008.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : implements framework API - main driver for the test
// ***************************************************************************
#ifndef BOOST_TEST_FRAMEWORK_IPP_021005GER
#define BOOST_TEST_FRAMEWORK_IPP_021005GER
// Boost.Test
#include <boost/test/framework.hpp>
#include <boost/test/execution_monitor.hpp>
#include <boost/test/debug.hpp>
#include <boost/test/unit_test_suite_impl.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/unit_test_monitor.hpp>
#include <boost/test/test_observer.hpp>
#include <boost/test/results_collector.hpp>
#include <boost/test/progress_monitor.hpp>
#include <boost/test/results_reporter.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
#include <boost/test/detail/global_typedef.hpp>
#include <boost/test/utils/foreach.hpp>
// Boost
#include <boost/timer.hpp>
// STL
#include <map>
#include <set>
#include <cstdlib>
#include <ctime>
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std { using ::time; using ::srand; }
#endif
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace unit_test {
// ************************************************************************** //
// ************** test_start calls wrapper ************** //
// ************************************************************************** //
namespace ut_detail {
struct test_start_caller {
test_start_caller( test_observer* to, counter_t tc_amount )
: m_to( to )
, m_tc_amount( tc_amount )
{}
int operator()()
{
m_to->test_start( m_tc_amount );
return 0;
}
private:
// Data members
test_observer* m_to;
counter_t m_tc_amount;
};
//____________________________________________________________________________//
struct test_init_caller {
explicit test_init_caller( init_unit_test_func init_func )
: m_init_func( init_func )
{}
int operator()()
{
#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
if( !(*m_init_func)() )
throw std::runtime_error( "test module initialization failed" );
#else
test_suite* manual_test_units = (*m_init_func)( framework::master_test_suite().argc, framework::master_test_suite().argv );
if( manual_test_units )
framework::master_test_suite().add( manual_test_units );
#endif
return 0;
}
// Data members
init_unit_test_func m_init_func;
};
}
// ************************************************************************** //
// ************** framework ************** //
// ************************************************************************** //
class framework_impl : public test_tree_visitor {
public:
framework_impl()
: m_master_test_suite( 0 )
, m_curr_test_case( INV_TEST_UNIT_ID )
, m_next_test_case_id( MIN_TEST_CASE_ID )
, m_next_test_suite_id( MIN_TEST_SUITE_ID )
, m_is_initialized( false )
, m_test_in_progress( false )
{}
~framework_impl() { clear(); }
void clear()
{
while( !m_test_units.empty() ) {
test_unit_store::value_type const& tu = *m_test_units.begin();
test_unit const* tu_ptr = tu.second;
// the delete will erase this element from map
if( ut_detail::test_id_2_unit_type( tu.second->p_id ) == tut_suite )
delete static_cast<test_suite const*>(tu_ptr);
else
delete static_cast<test_case const*>(tu_ptr);
}
}
void set_tu_id( test_unit& tu, test_unit_id id ) { tu.p_id.value = id; }
// test_tree_visitor interface implementation
void visit( test_case const& tc )
{
if( !tc.check_dependencies() ) {
BOOST_TEST_FOREACH( test_observer*, to, m_observers )
to->test_unit_skipped( tc );
return;
}
BOOST_TEST_FOREACH( test_observer*, to, m_observers )
to->test_unit_start( tc );
boost::timer tc_timer;
test_unit_id bkup = m_curr_test_case;
m_curr_test_case = tc.p_id;
unit_test_monitor_t::error_level run_result = unit_test_monitor.execute_and_translate( tc );
unsigned long elapsed = static_cast<unsigned long>( tc_timer.elapsed() * 1e6 );
if( unit_test_monitor.is_critical_error( run_result ) ) {
BOOST_TEST_FOREACH( test_observer*, to, m_observers )
to->test_aborted();
}
BOOST_TEST_FOREACH( test_observer*, to, m_observers )
to->test_unit_finish( tc, elapsed );
m_curr_test_case = bkup;
if( unit_test_monitor.is_critical_error( run_result ) )
throw test_being_aborted();
}
bool test_suite_start( test_suite const& ts )
{
if( !ts.check_dependencies() ) {
BOOST_TEST_FOREACH( test_observer*, to, m_observers )
to->test_unit_skipped( ts );
return false;
}
BOOST_TEST_FOREACH( test_observer*, to, m_observers )
to->test_unit_start( ts );
return true;
}
void test_suite_finish( test_suite const& ts )
{
BOOST_TEST_FOREACH( test_observer*, to, m_observers )
to->test_unit_finish( ts, 0 );
}
//////////////////////////////////////////////////////////////////
struct priority_order {
bool operator()( test_observer* lhs, test_observer* rhs ) const
{
return (lhs->priority() < rhs->priority()) || ((lhs->priority() == rhs->priority()) && (lhs < rhs));
}
};
typedef std::map<test_unit_id,test_unit*> test_unit_store;
typedef std::set<test_observer*,priority_order> observer_store;
master_test_suite_t* m_master_test_suite;
test_unit_id m_curr_test_case;
test_unit_store m_test_units;
test_unit_id m_next_test_case_id;
test_unit_id m_next_test_suite_id;
bool m_is_initialized;
bool m_test_in_progress;
observer_store m_observers;
};
//____________________________________________________________________________//
namespace {
#if defined(__CYGWIN__)
framework_impl& s_frk_impl() { static framework_impl* the_inst = 0; if(!the_inst) the_inst = new framework_impl; return *the_inst; }
#else
framework_impl& s_frk_impl() { static framework_impl the_inst; return the_inst; }
#endif
} // local namespace
//____________________________________________________________________________//
namespace framework {
void
init( init_unit_test_func init_func, int argc, char* argv[] )
{
runtime_config::init( argc, argv );
// set the log level and format
unit_test_log.set_threshold_level( runtime_config::log_level() );
unit_test_log.set_format( runtime_config::log_format() );
// set the report level and format
results_reporter::set_level( runtime_config::report_level() );
results_reporter::set_format( runtime_config::report_format() );
register_observer( results_collector );
register_observer( unit_test_log );
if( runtime_config::show_progress() )
register_observer( progress_monitor );
if( runtime_config::detect_memory_leaks() > 0 ) {
debug::detect_memory_leaks( true );
debug::break_memory_alloc( runtime_config::detect_memory_leaks() );
}
// init master unit test suite
master_test_suite().argc = argc;
master_test_suite().argv = argv;
try {
boost::execution_monitor em;
ut_detail::test_init_caller tic( init_func );
em.execute( tic );
}
catch( execution_exception const& ex ) {
throw setup_error( ex.what() );
}
s_frk_impl().m_is_initialized = true;
}
//____________________________________________________________________________//
bool
is_initialized()
{
return s_frk_impl().m_is_initialized;
}
//____________________________________________________________________________//
void
register_test_unit( test_case* tc )
{
BOOST_TEST_SETUP_ASSERT( tc->p_id == INV_TEST_UNIT_ID, BOOST_TEST_L( "test case already registered" ) );
test_unit_id new_id = s_frk_impl().m_next_test_case_id;
BOOST_TEST_SETUP_ASSERT( new_id != MAX_TEST_CASE_ID, BOOST_TEST_L( "too many test cases" ) );
typedef framework_impl::test_unit_store::value_type map_value_type;
s_frk_impl().m_test_units.insert( map_value_type( new_id, tc ) );
s_frk_impl().m_next_test_case_id++;
s_frk_impl().set_tu_id( *tc, new_id );
}
//____________________________________________________________________________//
void
register_test_unit( test_suite* ts )
{
BOOST_TEST_SETUP_ASSERT( ts->p_id == INV_TEST_UNIT_ID, BOOST_TEST_L( "test suite already registered" ) );
test_unit_id new_id = s_frk_impl().m_next_test_suite_id;
BOOST_TEST_SETUP_ASSERT( new_id != MAX_TEST_SUITE_ID, BOOST_TEST_L( "too many test suites" ) );
typedef framework_impl::test_unit_store::value_type map_value_type;
s_frk_impl().m_test_units.insert( map_value_type( new_id, ts ) );
s_frk_impl().m_next_test_suite_id++;
s_frk_impl().set_tu_id( *ts, new_id );
}
//____________________________________________________________________________//
void
deregister_test_unit( test_unit* tu )
{
s_frk_impl().m_test_units.erase( tu->p_id );
}
//____________________________________________________________________________//
void
clear()
{
s_frk_impl().clear();
}
//____________________________________________________________________________//
void
register_observer( test_observer& to )
{
s_frk_impl().m_observers.insert( &to );
}
//____________________________________________________________________________//
void
deregister_observer( test_observer& to )
{
s_frk_impl().m_observers.erase( &to );
}
//____________________________________________________________________________//
void
reset_observers()
{
s_frk_impl().m_observers.clear();
}
//____________________________________________________________________________//
master_test_suite_t&
master_test_suite()
{
if( !s_frk_impl().m_master_test_suite )
s_frk_impl().m_master_test_suite = new master_test_suite_t;
return *s_frk_impl().m_master_test_suite;
}
//____________________________________________________________________________//
test_case const&
current_test_case()
{
return get<test_case>( s_frk_impl().m_curr_test_case );
}
//____________________________________________________________________________//
test_unit&
get( test_unit_id id, test_unit_type t )
{
test_unit* res = s_frk_impl().m_test_units[id];
if( (res->p_type & t) == 0 )
throw internal_error( "Invalid test unit type" );
return *res;
}
//____________________________________________________________________________//
void
run( test_unit_id id, bool continue_test )
{
if( id == INV_TEST_UNIT_ID )
id = master_test_suite().p_id;
test_case_counter tcc;
traverse_test_tree( id, tcc );
BOOST_TEST_SETUP_ASSERT( tcc.p_count != 0 , runtime_config::test_to_run().is_empty()
? BOOST_TEST_L( "test tree is empty" )
: BOOST_TEST_L( "no test cases matching filter" ) );
bool call_start_finish = !continue_test || !s_frk_impl().m_test_in_progress;
bool was_in_progress = s_frk_impl().m_test_in_progress;
s_frk_impl().m_test_in_progress = true;
if( call_start_finish ) {
BOOST_TEST_FOREACH( test_observer*, to, s_frk_impl().m_observers ) {
boost::execution_monitor em;
try {
em.execute( ut_detail::test_start_caller( to, tcc.p_count ) );
}
catch( execution_exception const& ex ) {
throw setup_error( ex.what() );
}
}
}
switch( runtime_config::random_seed() ) {
case 0:
break;
case 1: {
unsigned int seed = static_cast<unsigned int>( std::time( 0 ) );
BOOST_TEST_MESSAGE( "Test cases order is shuffled using seed: " << seed );
std::srand( seed );
break;
}
default:
BOOST_TEST_MESSAGE( "Test cases order is shuffled using seed: " << runtime_config::random_seed() );
std::srand( runtime_config::random_seed() );
}
try {
traverse_test_tree( id, s_frk_impl() );
}
catch( test_being_aborted const& ) {
// abort already reported
}
if( call_start_finish ) {
BOOST_TEST_FOREACH( test_observer*, to, s_frk_impl().m_observers )
to->test_finish();
}
s_frk_impl().m_test_in_progress = was_in_progress;
}
//____________________________________________________________________________//
void
run( test_unit const* tu, bool continue_test )
{
run( tu->p_id, continue_test );
}
//____________________________________________________________________________//
void
assertion_result( bool passed )
{
BOOST_TEST_FOREACH( test_observer*, to, s_frk_impl().m_observers )
to->assertion_result( passed );
}
//____________________________________________________________________________//
void
exception_caught( execution_exception const& ex )
{
BOOST_TEST_FOREACH( test_observer*, to, s_frk_impl().m_observers )
to->exception_caught( ex );
}
//____________________________________________________________________________//
void
test_unit_aborted( test_unit const& tu )
{
BOOST_TEST_FOREACH( test_observer*, to, s_frk_impl().m_observers )
to->test_unit_aborted( tu );
}
//____________________________________________________________________________//
} // namespace framework
} // namespace unit_test
} // namespace boost
//____________________________________________________________________________//
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_FRAMEWORK_IPP_021005GER
| 28.440476
| 132
| 0.66876
|
jonstewart
|
447794b296f1ca47c7dc73cb484dced1c00fa0e4
| 1,043
|
cpp
|
C++
|
editor/src/editorcommands/addspatialentitycommand.cpp
|
gameraccoon/HideAndSeek
|
bc1e9c8dd725968ad4bc204877d8ddca2132ace7
|
[
"MIT"
] | null | null | null |
editor/src/editorcommands/addspatialentitycommand.cpp
|
gameraccoon/HideAndSeek
|
bc1e9c8dd725968ad4bc204877d8ddca2132ace7
|
[
"MIT"
] | null | null | null |
editor/src/editorcommands/addspatialentitycommand.cpp
|
gameraccoon/HideAndSeek
|
bc1e9c8dd725968ad4bc204877d8ddca2132ace7
|
[
"MIT"
] | null | null | null |
#include "addspatialentitycommand.h"
#include <QtWidgets/qcombobox.h>
#include "GameData/Components/TransformComponent.generated.h"
#include "GameData/World.h"
AddSpatialEntityCommand::AddSpatialEntityCommand(const SpatialEntity& entity, const Vector2D& location)
: EditorCommand(EffectBitset(EffectType::Entities))
, mEntity(entity)
, mLocation(location)
{
}
void AddSpatialEntityCommand::doCommand(World* world)
{
WorldCell& cell = world->getSpatialData().getOrCreateCell(mEntity.cell);
EntityManager& cellEnttiyManager = cell.getEntityManager();
cellEnttiyManager.addExistingEntityUnsafe(mEntity.entity.getEntity());
TransformComponent* transform = cellEnttiyManager.addComponent<TransformComponent>(mEntity.entity.getEntity());
transform->setLocation(mLocation);
}
void AddSpatialEntityCommand::undoCommand(World* world)
{
if (WorldCell* cell = world->getSpatialData().getCell(mEntity.cell))
{
EntityManager& cellEnttiyManager = cell->getEntityManager();
cellEnttiyManager.removeEntity(mEntity.entity.getEntity());
}
}
| 32.59375
| 112
| 0.802493
|
gameraccoon
|
4477bee1e72e9cab5d423d1d989799ea66e26d96
| 5,195
|
cpp
|
C++
|
code/szen/src/System/Window.cpp
|
Sonaza/scyori
|
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
|
[
"BSD-3-Clause"
] | null | null | null |
code/szen/src/System/Window.cpp
|
Sonaza/scyori
|
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
|
[
"BSD-3-Clause"
] | null | null | null |
code/szen/src/System/Window.cpp
|
Sonaza/scyori
|
a894a9c7bd45a68ea1b6ff14877cdbe47ddd39cf
|
[
"BSD-3-Clause"
] | null | null | null |
#include <szen/System/Window.hpp>
#include <szen/Game/Camera.hpp>
#include <sstream>
#ifdef SFML_SYSTEM_WINDOWS
#include <Windows.h>
#endif
using namespace sz;
namespace
{
sf::RenderWindow* m_window = NULL;
float m_aspectRatio;
sf::Uint32 m_virtualWidth = 1920;
sf::View m_view;
std::string m_title;
sf::Uint32 m_antialiasing;
}
////////////////////////////////////////////////////
void Window::open(sf::VideoMode videomode, const std::string &title,
const sf::Uint32 style, const sf::Uint32 antialias,
const sf::Uint32 virtualWidth)
{
assert(!m_window && "Window is already open");
sf::ContextSettings settings;
settings.antialiasingLevel = antialias;
// Create new window instance
m_window = new(std::nothrow) sf::RenderWindow(videomode, title, style, settings);
assert(m_window && "Allocation failed");
m_title = title;
m_antialiasing = antialias;
m_aspectRatio = videomode.width / static_cast<float>(videomode.height);
// Set virtual width
m_virtualWidth = (virtualWidth == 0 ? videomode.width : virtualWidth);
m_window->setVerticalSyncEnabled(true);
m_window->clear(sf::Color::Black);
m_window->display();
Camera::updateScreenSize();
}
////////////////////////////////////////////////////
void Window::changeMode(sf::VideoMode videomode, const sf::Uint32 style)
{
if(!m_window) return;
// Delete old window and create new instead
delete m_window;
sf::ContextSettings settings;
settings.antialiasingLevel = m_antialiasing;
m_window = new sf::RenderWindow(videomode, m_title, style, settings);
m_aspectRatio = videomode.width / static_cast<float>(videomode.height);
m_window->setVerticalSyncEnabled(true);
m_window->clear(sf::Color::Black);
m_window->display();
Camera::updateScreenSize();
}
////////////////////////////////////////////////////
void Window::close()
{
if(m_window)
{
m_window->close();
delete m_window;
m_window = NULL;
}
}
////////////////////////////////////////////////////
sf::Vector2u Window::getSize()
{
return m_window->getSize();
}
////////////////////////////////////////////////////
void Window::setVirtualWidth(const sf::Uint32 width)
{
m_virtualWidth = width;
Camera::updateScreenSize();
}
////////////////////////////////////////////////////
sf::Vector2u Window::getVirtualSize()
{
return sf::Vector2u(
m_virtualWidth,
static_cast<sf::Uint32>(ceil(m_virtualWidth * (1.f / m_aspectRatio))));
}
////////////////////////////////////////////////////
sf::RenderWindow* Window::getRenderWindow()
{
return m_window;
}
////////////////////////////////////////////////////
bool Window::isActive()
{
// Windows implementation
return m_window->getSystemHandle() == GetActiveWindow();
}
////////////////////////////////////////////////////////////
sf::VideoMode Window::getOptimalResolution(const bool fullscreen)
{
sf::VideoMode native = sf::VideoMode::getDesktopMode();
std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
sf::VideoMode videomode = native;
if(fullscreen && native == modes[0]) return videomode;
float nativeRatio = native.width / static_cast<float>(native.height);
float ratio;
for(std::vector<sf::VideoMode>::iterator it = modes.begin(); it != modes.end(); ++it)
{
sf::VideoMode mode = *it;
if(mode.bitsPerPixel != native.bitsPerPixel) continue;
if(mode.width >= native.width) continue;
ratio = mode.width / static_cast<float>(mode.height);
if(fabs(nativeRatio - ratio) <= 0.001f)
{
videomode = mode;
break;
}
}
return videomode;
}
#include <iostream>
////////////////////////////////////////////////////////////
int calculateGCD(int a, int b) {
return (b == 0) ? a : calculateGCD (b, a%b);
}
////////////////////////////////////////////////////////////
std::vector<sf::VideoMode> Window::getSupportedResolutions(const bool fullscreen)
{
sf::VideoMode native = sf::VideoMode::getDesktopMode();
float nativeAspect = native.width / (float)native.height;
std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
std::vector<sf::VideoMode> result;
for(int i=0; i < modes.size(); ++i)
{
sf::VideoMode mode = modes[i];
bool cond = true;
float ratio = mode.width / (float)mode.height;
cond &= mode.bitsPerPixel == modes[0].bitsPerPixel;
cond &= mode.width >= 1024;
cond &= mode.width <= native.width && mode.height <= native.height;
//cond &= nativeAspect == ratio;
if(cond)
{
result.push_back(mode);
}
}
std::sort(result.begin(), result.end(),
[](sf::VideoMode& a, sf::VideoMode& b) -> bool
{
/*float ra = a.width / (float)a.height;
float rb = b.width / (float)b.height;
*/
return (a.width * a.height) < (b.width * b.height);
}
);
std::cout << "============================================================\n";
for(int i=0; i < result.size(); ++i)
{
sf::VideoMode mode = result[i];
std::stringstream aspect;
int gcd = calculateGCD(mode.width, mode.height);
sf::Vector2i ratio(mode.width, mode.height);
ratio /= gcd;
if(ratio.x == 8 && ratio.y == 5) ratio *= 2;
aspect << ratio.x << ":" << ratio.y;
std::cout << mode.width << " x " << mode.height << " (" << aspect.str() << ")\n";
}
return result;
}
| 23.506787
| 86
| 0.596535
|
Sonaza
|
4478f21af676c7a08c1b77f5ec68f64e89aed5b3
| 1,814
|
cpp
|
C++
|
src/lib/CatenaBase_NetSave.cpp
|
dhineshkumarmcci/Catena-Arduino-Platform
|
478ad23318a7646f2e03170e9294b0ea69885da4
|
[
"MIT"
] | 1
|
2021-11-27T22:56:25.000Z
|
2021-11-27T22:56:25.000Z
|
src/lib/CatenaBase_NetSave.cpp
|
dhineshkumarmcci/Catena-Arduino-Platform
|
478ad23318a7646f2e03170e9294b0ea69885da4
|
[
"MIT"
] | null | null | null |
src/lib/CatenaBase_NetSave.cpp
|
dhineshkumarmcci/Catena-Arduino-Platform
|
478ad23318a7646f2e03170e9294b0ea69885da4
|
[
"MIT"
] | 1
|
2021-04-03T09:56:13.000Z
|
2021-04-03T09:56:13.000Z
|
/* CatenaBase_NetSave.cpp Mon Dec 03 2018 13:21:28 chwon */
/*
Module: CatenaBase_NetSave.cpp
Function:
Interface from LoRaWAN to FRAM.
Version:
V0.12.0 Mon Dec 03 2018 13:21:28 chwon Edit level 1
Copyright notice:
This file copyright (C) 2018 by
MCCI Corporation
3520 Krums Corners Road
Ithaca, NY 14850
An unpublished work. All rights reserved.
This file is proprietary information, and may not be disclosed or
copied without the prior permission of MCCI Corporation
Author:
ChaeHee Won, MCCI Corporation December 2018
Revision history:
0.12.0 Mon Dec 03 2018 13:21:28 chwon
Module created.
*/
#include <CatenaBase.h>
#include <Catena_Fram.h>
#include <Catena_Log.h>
using namespace McciCatena;
void
CatenaBase::NetSaveFCntUp(
uint32_t uFCntUp
)
{
auto const pFram = this->getFram();
if (pFram != nullptr)
pFram->saveField(cFramStorage::kFCntUp, uFCntUp);
}
void
CatenaBase::NetSaveFCntDown(
uint32_t uFCntDown
)
{
auto const pFram = this->getFram();
if (pFram != nullptr)
pFram->saveField(cFramStorage::kFCntDown, uFCntDown);
}
void
CatenaBase::NetSaveSessionInfo(
const Arduino_LoRaWAN::SessionInfo &Info,
const uint8_t *pExtraInfo,
size_t nExtraInfo
)
{
auto const pFram = this->getFram();
if (pFram != nullptr)
{
pFram->saveField(cFramStorage::kNetID, Info.V1.NetID);
pFram->saveField(cFramStorage::kDevAddr, Info.V1.DevAddr);
pFram->saveField(cFramStorage::kNwkSKey, Info.V1.NwkSKey);
pFram->saveField(cFramStorage::kAppSKey, Info.V1.AppSKey);
pFram->saveField(cFramStorage::kFCntUp, Info.V1.FCntUp);
pFram->saveField(cFramStorage::kFCntDown, Info.V1.FCntDown);
}
gLog.printf(
gLog.kAlways,
"NwkID: %08x "
"DevAddr: %08x\n",
Info.V1.NetID,
Info.V1.DevAddr
);
}
/**** end of CatenaBase_NetSave.cpp ****/
| 19.717391
| 66
| 0.723264
|
dhineshkumarmcci
|
447aa6c8ff6b0ec4345b7687a3fc26f3c5f4d156
| 42,601
|
cc
|
C++
|
src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc
|
Sohei-Suzuki-Nexty/sdl_core
|
68f082169e0a40fccd9eb0db3c83911c28870f07
|
[
"BSD-3-Clause"
] | 249
|
2015-01-15T16:50:53.000Z
|
2022-03-24T13:23:34.000Z
|
src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc
|
Sohei-Suzuki-Nexty/sdl_core
|
68f082169e0a40fccd9eb0db3c83911c28870f07
|
[
"BSD-3-Clause"
] | 2,917
|
2015-01-12T16:17:49.000Z
|
2022-03-31T11:57:47.000Z
|
src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc
|
Sohei-Suzuki-Nexty/sdl_core
|
68f082169e0a40fccd9eb0db3c83911c28870f07
|
[
"BSD-3-Clause"
] | 306
|
2015-01-12T09:23:20.000Z
|
2022-01-28T18:06:30.000Z
|
/*
* Copyright (c) 2017, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "config_profile/profile.h"
#include "utils/helpers.h"
#include "utils/logger.h"
#include "utils/timer_task_impl.h"
#include "transport_manager/transport_adapter/client_connection_listener.h"
#include "transport_manager/transport_adapter/device_scanner.h"
#include "transport_manager/transport_adapter/server_connection_factory.h"
#include "transport_manager/transport_adapter/transport_adapter_impl.h"
#include "transport_manager/transport_adapter/transport_adapter_listener.h"
#ifdef WEBSOCKET_SERVER_TRANSPORT_SUPPORT
#include "transport_manager/websocket_server/websocket_device.h"
#endif
namespace transport_manager {
namespace transport_adapter {
const char* tc_enabled = "enabled";
const char* tc_tcp_port = "tcp_port";
const char* tc_tcp_ip_address = "tcp_ip_address";
SDL_CREATE_LOG_VARIABLE("TransportManager")
namespace {
DeviceTypes devicesType = {
std::make_pair(DeviceType::AOA, std::string("USB_AOA")),
std::make_pair(DeviceType::BLUETOOTH, std::string("BLUETOOTH")),
std::make_pair(DeviceType::IOS_BT, std::string("BLUETOOTH_IOS")),
std::make_pair(DeviceType::IOS_USB, std::string("USB_IOS")),
std::make_pair(DeviceType::TCP, std::string("WIFI")),
std::make_pair(DeviceType::IOS_USB_HOST_MODE,
std::string("USB_IOS_HOST_MODE")),
std::make_pair(DeviceType::IOS_USB_DEVICE_MODE,
std::string("USB_IOS_DEVICE_MODE")),
std::make_pair(DeviceType::IOS_CARPLAY_WIRELESS,
std::string("CARPLAY_WIRELESS_IOS")),
std::make_pair(DeviceType::CLOUD_WEBSOCKET, std::string("CLOUD_WEBSOCKET")),
std::make_pair(DeviceType::WEBENGINE_WEBSOCKET,
std::string("WEBENGINE_WEBSOCKET"))};
}
TransportAdapterImpl::TransportAdapterImpl(
DeviceScanner* device_scanner,
ServerConnectionFactory* server_connection_factory,
ClientConnectionListener* client_connection_listener,
resumption::LastStateWrapperPtr last_state_wrapper,
const TransportManagerSettings& settings)
: listeners_()
, initialised_(0)
, devices_()
, devices_mutex_()
, connections_()
, connections_lock_()
,
#ifdef TELEMETRY_MONITOR
metric_observer_(NULL)
,
#endif // TELEMETRY_MONITOR
device_scanner_(device_scanner)
, server_connection_factory_(server_connection_factory)
, client_connection_listener_(client_connection_listener)
, last_state_wrapper_(last_state_wrapper)
, settings_(settings) {
}
TransportAdapterImpl::~TransportAdapterImpl() {
listeners_.clear();
Terminate();
if (device_scanner_) {
SDL_LOG_DEBUG("Deleting device_scanner_ " << device_scanner_);
delete device_scanner_;
SDL_LOG_DEBUG("device_scanner_ deleted.");
}
if (server_connection_factory_) {
SDL_LOG_DEBUG("Deleting server_connection_factory "
<< server_connection_factory_);
delete server_connection_factory_;
SDL_LOG_DEBUG("server_connection_factory deleted.");
}
if (client_connection_listener_) {
SDL_LOG_DEBUG("Deleting client_connection_listener_ "
<< client_connection_listener_);
delete client_connection_listener_;
SDL_LOG_DEBUG("client_connection_listener_ deleted.");
}
}
void TransportAdapterImpl::Terminate() {
if (device_scanner_) {
device_scanner_->Terminate();
SDL_LOG_DEBUG("device_scanner_ " << device_scanner_ << " terminated.");
}
if (server_connection_factory_) {
server_connection_factory_->Terminate();
SDL_LOG_DEBUG("server_connection_factory " << server_connection_factory_
<< " terminated.");
}
if (client_connection_listener_) {
client_connection_listener_->Terminate();
SDL_LOG_DEBUG("client_connection_listener_ " << client_connection_listener_
<< " terminated.");
}
ConnectionMap connections;
connections_lock_.AcquireForWriting();
std::swap(connections, connections_);
connections_lock_.Release();
for (const auto& connection : connections) {
auto& info = connection.second;
if (info.connection) {
info.connection->Terminate();
}
}
connections.clear();
SDL_LOG_DEBUG("Connections deleted");
DeviceMap devices;
devices_mutex_.Acquire();
std::swap(devices, devices_);
devices_mutex_.Release();
devices.clear();
SDL_LOG_DEBUG("Devices deleted");
}
TransportAdapter::Error TransportAdapterImpl::Init() {
SDL_LOG_TRACE("enter");
Error error = OK;
if ((error == OK) && device_scanner_) {
error = device_scanner_->Init();
}
if ((error == OK) && server_connection_factory_) {
error = server_connection_factory_->Init();
}
if ((error == OK) && client_connection_listener_) {
error = client_connection_listener_->Init();
}
initialised_ = (error == OK);
if (get_settings().use_last_state() && initialised_) {
if (!Restore()) {
SDL_LOG_WARN("could not restore transport adapter state");
}
}
SDL_LOG_TRACE("exit with error: " << error);
return error;
}
TransportAdapter::Error TransportAdapterImpl::SearchDevices() {
SDL_LOG_TRACE("enter");
if (device_scanner_ == NULL) {
SDL_LOG_TRACE("exit with NOT_SUPPORTED");
return NOT_SUPPORTED;
} else if (!device_scanner_->IsInitialised()) {
SDL_LOG_TRACE("exit with BAD_STATE");
return BAD_STATE;
}
TransportAdapter::Error er = device_scanner_->Scan();
SDL_LOG_TRACE("exit with error: " << er);
return er;
}
TransportAdapter::Error TransportAdapterImpl::Connect(
const DeviceUID& device_id, const ApplicationHandle& app_handle) {
SDL_LOG_TRACE("enter. DeviceUID " << device_id << " ApplicationHandle "
<< app_handle);
if (server_connection_factory_ == 0) {
SDL_LOG_TRACE("exit with NOT_SUPPORTED");
return NOT_SUPPORTED;
}
if (!server_connection_factory_->IsInitialised()) {
SDL_LOG_TRACE("exit with BAD_STATE");
return BAD_STATE;
}
if (!initialised_) {
SDL_LOG_TRACE("exit with BAD_STATE");
return BAD_STATE;
}
connections_lock_.AcquireForWriting();
std::pair<DeviceUID, ApplicationHandle> connection_key =
std::make_pair(device_id, app_handle);
const bool already_exists =
connections_.end() != connections_.find(connection_key);
ConnectionInfo& info = connections_[connection_key];
if (!already_exists) {
info.app_handle = app_handle;
info.device_id = device_id;
info.state = ConnectionInfo::NEW;
}
const bool pending_app = ConnectionInfo::PENDING == info.state;
connections_lock_.Release();
if (already_exists && !pending_app) {
SDL_LOG_TRACE("exit with ALREADY_EXISTS");
return ALREADY_EXISTS;
}
const TransportAdapter::Error err =
server_connection_factory_->CreateConnection(device_id, app_handle);
if (TransportAdapter::OK != err) {
if (!pending_app) {
RemoveConnection(device_id, app_handle);
}
}
SDL_LOG_TRACE("exit with error: " << err);
return err;
}
TransportAdapter::Error TransportAdapterImpl::ConnectDevice(
const DeviceUID& device_handle) {
SDL_LOG_TRACE("enter with device_handle: " << &device_handle);
DeviceSptr device = FindDevice(device_handle);
if (device) {
TransportAdapter::Error err = ConnectDevice(device);
if (FAIL == err && GetDeviceType() == DeviceType::CLOUD_WEBSOCKET) {
SDL_LOG_TRACE("Error occurred while connecting cloud app: " << err);
// Update retry count
if (device->retry_count() >=
get_settings().cloud_app_max_retry_attempts()) {
device->reset_retry_count();
ConnectionStatusUpdated(device, ConnectionStatus::PENDING);
return err;
} else if (device->connection_status() == ConnectionStatus::PENDING) {
ConnectionStatusUpdated(device, ConnectionStatus::RETRY);
}
device->next_retry();
// Start timer for next retry
TimerSPtr retry_timer(std::make_shared<timer::Timer>(
"RetryConnectionTimer",
new timer::TimerTaskImpl<TransportAdapterImpl>(
this, &TransportAdapterImpl::RetryConnection)));
sync_primitives::AutoLock locker(retry_timer_pool_lock_);
retry_timer_pool_.push(std::make_pair(retry_timer, device_handle));
retry_timer->Start(get_settings().cloud_app_retry_timeout(),
timer::kSingleShot);
} else if (OK == err) {
ConnectionStatusUpdated(device, ConnectionStatus::CONNECTED);
}
SDL_LOG_TRACE("exit with error: " << err);
return err;
} else {
SDL_LOG_TRACE("exit with BAD_PARAM");
return BAD_PARAM;
}
}
void TransportAdapterImpl::RetryConnection() {
ClearCompletedTimers();
const DeviceUID device_id = GetNextRetryDevice();
if (device_id.empty()) {
SDL_LOG_ERROR("Unable to find timer, ignoring RetryConnection request");
return;
}
ConnectDevice(device_id);
}
void TransportAdapterImpl::ClearCompletedTimers() {
// Cleanup any retry timers which have completed execution
sync_primitives::AutoLock locker(completed_timer_pool_lock_);
while (!completed_timer_pool_.empty()) {
auto timer_entry = completed_timer_pool_.front();
if (timer_entry.first->is_completed()) {
completed_timer_pool_.pop();
}
}
}
DeviceUID TransportAdapterImpl::GetNextRetryDevice() {
sync_primitives::AutoLock retry_locker(retry_timer_pool_lock_);
if (retry_timer_pool_.empty()) {
return std::string();
}
auto timer_entry = retry_timer_pool_.front();
retry_timer_pool_.pop();
// Store reference for cleanup later
sync_primitives::AutoLock completed_locker(completed_timer_pool_lock_);
completed_timer_pool_.push(timer_entry);
return timer_entry.second;
}
ConnectionStatus TransportAdapterImpl::GetConnectionStatus(
const DeviceUID& device_handle) const {
DeviceSptr device = FindDevice(device_handle);
return device.use_count() == 0 ? ConnectionStatus::INVALID
: device->connection_status();
}
void TransportAdapterImpl::ConnectionStatusUpdated(DeviceSptr device,
ConnectionStatus status) {
device->set_connection_status(status);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnConnectionStatusUpdated(this);
}
}
TransportAdapter::Error TransportAdapterImpl::Disconnect(
const DeviceUID& device_id, const ApplicationHandle& app_handle) {
SDL_LOG_TRACE("enter. device_id: " << &device_id
<< ", device_id: " << &device_id);
if (!initialised_) {
SDL_LOG_TRACE("exit with BAD_STATE");
return BAD_STATE;
}
ConnectionSPtr connection = FindEstablishedConnection(device_id, app_handle);
if (connection) {
TransportAdapter::Error err = connection->Disconnect();
SDL_LOG_TRACE("exit with error: " << err);
return err;
} else {
SDL_LOG_TRACE("exit with BAD_PARAM");
return BAD_PARAM;
}
}
TransportAdapter::Error TransportAdapterImpl::DisconnectDevice(
const DeviceUID& device_id) {
SDL_LOG_TRACE("enter. device_id: " << &device_id);
if (!initialised_) {
SDL_LOG_TRACE("exit with BAD_STATE");
return BAD_STATE;
}
Error error = OK;
DeviceSptr device = FindDevice(device_id);
if (!device) {
SDL_LOG_WARN("Device with id: " << device_id << " Not found");
return BAD_PARAM;
}
ConnectionStatusUpdated(device, ConnectionStatus::CLOSING);
std::vector<ConnectionInfo> to_disconnect;
connections_lock_.AcquireForReading();
for (ConnectionMap::const_iterator i = connections_.begin();
i != connections_.end();
++i) {
ConnectionInfo info = i->second;
if (info.device_id == device_id &&
info.state != ConnectionInfo::FINALISING) {
to_disconnect.push_back(info);
}
}
connections_lock_.Release();
for (std::vector<ConnectionInfo>::const_iterator j = to_disconnect.begin();
j != to_disconnect.end();
++j) {
ConnectionInfo info = *j;
if (OK != info.connection->Disconnect()) {
error = FAIL;
SDL_LOG_ERROR("Error on disconnect " << error);
}
}
return error;
}
TransportAdapter::Error TransportAdapterImpl::SendData(
const DeviceUID& device_id,
const ApplicationHandle& app_handle,
const ::protocol_handler::RawMessagePtr data) {
SDL_LOG_TRACE("enter. device_id: " << &device_id << ", app_handle: "
<< &app_handle << ", data: " << data);
if (!initialised_) {
SDL_LOG_TRACE("exit with BAD_STATE");
return BAD_STATE;
}
ConnectionSPtr connection = FindEstablishedConnection(device_id, app_handle);
if (connection) {
TransportAdapter::Error err = connection->SendData(data);
SDL_LOG_TRACE("exit with error: " << err);
return err;
} else {
SDL_LOG_TRACE("exit with BAD_PARAM");
return BAD_PARAM;
}
}
TransportAdapter::Error TransportAdapterImpl::ChangeClientListening(
TransportAction required_change) {
SDL_LOG_AUTO_TRACE();
if (client_connection_listener_ == 0) {
SDL_LOG_TRACE("exit with NOT_SUPPORTED");
return NOT_SUPPORTED;
}
if (!client_connection_listener_->IsInitialised()) {
SDL_LOG_TRACE("exit with BAD_STATE");
return BAD_STATE;
}
TransportAdapter::Error err = TransportAdapter::Error::UNKNOWN;
switch (required_change) {
case transport_manager::TransportAction::kVisibilityOn:
err = client_connection_listener_->StartListening();
break;
case transport_manager::TransportAction::kListeningOn:
err = client_connection_listener_->ResumeListening();
break;
case transport_manager::TransportAction::kListeningOff:
err = client_connection_listener_->SuspendListening();
{
sync_primitives::AutoLock locker(devices_mutex_);
for (DeviceMap::iterator it = devices_.begin(); it != devices_.end();
++it) {
it->second->Stop();
}
}
break;
case transport_manager::TransportAction::kVisibilityOff:
err = client_connection_listener_->StopListening();
{
sync_primitives::AutoLock locker(devices_mutex_);
for (DeviceMap::iterator it = devices_.begin(); it != devices_.end();
++it) {
it->second->Stop();
}
}
break;
default:
NOTREACHED();
}
SDL_LOG_TRACE("Exit with error: " << err);
return err;
}
DeviceList TransportAdapterImpl::GetDeviceList() const {
SDL_LOG_AUTO_TRACE();
DeviceList devices;
sync_primitives::AutoLock locker(devices_mutex_);
for (DeviceMap::const_iterator it = devices_.begin(); it != devices_.end();
++it) {
devices.push_back(it->first);
}
SDL_LOG_TRACE("exit with DeviceList. It's' size = " << devices.size());
return devices;
}
DeviceSptr TransportAdapterImpl::GetWebEngineDevice() const {
#ifndef WEBSOCKET_SERVER_TRANSPORT_SUPPORT
SDL_LOG_TRACE("Web engine support is disabled. Device does not exist");
return DeviceSptr();
#else
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoLock locker(devices_mutex_);
auto web_engine_device =
std::find_if(devices_.begin(),
devices_.end(),
[](const std::pair<DeviceUID, DeviceSptr> device) {
return webengine_constants::kWebEngineDeviceName ==
device.second->name();
});
if (devices_.end() != web_engine_device) {
return web_engine_device->second;
}
SDL_LOG_ERROR("WebEngine device not found!");
return std::make_shared<transport_adapter::WebSocketDevice>("", "");
#endif
}
DeviceSptr TransportAdapterImpl::AddDevice(DeviceSptr device) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_TRACE("enter. device: " << device);
DeviceSptr existing_device;
bool same_device_found = false;
devices_mutex_.Acquire();
for (DeviceMap::const_iterator i = devices_.begin(); i != devices_.end();
++i) {
existing_device = i->second;
if (device->IsSameAs(existing_device.get())) {
same_device_found = true;
SDL_LOG_DEBUG("Device " << device << " already exists");
break;
}
}
if (!same_device_found) {
devices_[device->unique_device_id()] = device;
}
devices_mutex_.Release();
if (same_device_found) {
SDL_LOG_TRACE("Exit with TRUE. Condition: same_device_found");
return existing_device;
} else {
device->set_connection_status(ConnectionStatus::PENDING);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnDeviceListUpdated(this);
}
if (ToBeAutoConnected(device)) {
ConnectDevice(device);
}
SDL_LOG_TRACE("exit with DeviceSptr " << device);
return device;
}
}
void TransportAdapterImpl::SearchDeviceDone(const DeviceVector& devices) {
SDL_LOG_TRACE("enter. devices: " << &devices);
DeviceMap new_devices;
for (DeviceVector::const_iterator it = devices.begin(); it != devices.end();
++it) {
DeviceSptr device = *it;
bool device_found = false;
devices_mutex_.Acquire();
for (DeviceMap::iterator iter = devices_.begin(); iter != devices_.end();
++iter) {
DeviceSptr existing_device = iter->second;
if (device->IsSameAs(existing_device.get())) {
existing_device->set_keep_on_disconnect(true);
device_found = true;
SDL_LOG_DEBUG("device found. DeviceSptr" << iter->second);
break;
}
}
devices_mutex_.Release();
if (!device_found) {
SDL_LOG_INFO("Adding new device " << device->unique_device_id() << " (\""
<< device->name() << "\")");
}
device->set_keep_on_disconnect(true);
new_devices[device->unique_device_id()] = device;
}
connections_lock_.AcquireForReading();
std::set<DeviceUID> connected_devices;
for (ConnectionMap::const_iterator it = connections_.begin();
it != connections_.end();
++it) {
const ConnectionInfo& info = it->second;
if (info.state != ConnectionInfo::FINALISING) {
connected_devices.insert(info.device_id);
}
}
connections_lock_.Release();
DeviceMap all_devices = new_devices;
devices_mutex_.Acquire();
for (DeviceMap::iterator it = devices_.begin(); it != devices_.end(); ++it) {
DeviceSptr existing_device = it->second;
if (all_devices.end() == all_devices.find(it->first)) {
if (connected_devices.end() != connected_devices.find(it->first)) {
existing_device->set_keep_on_disconnect(false);
all_devices[it->first] = existing_device;
}
}
}
devices_ = all_devices;
devices_mutex_.Release();
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnDeviceListUpdated(this);
(*it)->OnSearchDeviceDone(this);
}
for (DeviceMap::iterator it = new_devices.begin(); it != new_devices.end();
++it) {
DeviceSptr device = it->second;
if (ToBeAutoConnected(device)) {
ConnectDevice(device);
}
}
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::ApplicationListUpdated(
const DeviceUID& device_handle) {
// default implementation does nothing
// and is reimplemented in MME transport adapter only
}
void TransportAdapterImpl::FindNewApplicationsRequest() {
SDL_LOG_TRACE("enter");
for (TransportAdapterListenerList::iterator i = listeners_.begin();
i != listeners_.end();
++i) {
TransportAdapterListener* listener = *i;
listener->OnFindNewApplicationsRequest(this);
}
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::SearchDeviceFailed(const SearchDeviceError& error) {
SDL_LOG_TRACE("enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnSearchDeviceFailed(this, error);
}
SDL_LOG_TRACE("exit");
}
bool TransportAdapterImpl::IsSearchDevicesSupported() const {
SDL_LOG_AUTO_TRACE();
return device_scanner_ != 0;
}
bool TransportAdapterImpl::IsServerOriginatedConnectSupported() const {
SDL_LOG_AUTO_TRACE();
return server_connection_factory_ != 0;
}
bool TransportAdapterImpl::IsClientOriginatedConnectSupported() const {
SDL_LOG_AUTO_TRACE();
return client_connection_listener_ != 0;
}
void TransportAdapterImpl::ConnectionCreated(
ConnectionSPtr connection,
const DeviceUID& device_id,
const ApplicationHandle& app_handle) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_TRACE("enter connection:" << connection
<< ", device_id: " << &device_id
<< ", app_handle: " << &app_handle);
connections_lock_.AcquireForReading();
ConnectionInfo& info = connections_[std::make_pair(device_id, app_handle)];
info.app_handle = app_handle;
info.device_id = device_id;
info.connection = connection;
info.state = ConnectionInfo::NEW;
connections_lock_.Release();
}
void TransportAdapterImpl::DeviceDisconnected(
const DeviceUID& device_handle, const DisconnectDeviceError& error) {
SDL_LOG_AUTO_TRACE();
const DeviceUID device_uid = device_handle;
SDL_LOG_TRACE("enter. device_handle: " << &device_uid
<< ", error: " << &error);
ApplicationList app_list = GetApplicationList(device_uid);
for (ApplicationList::const_iterator i = app_list.begin();
i != app_list.end();
++i) {
ApplicationHandle app_handle = *i;
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
TransportAdapterListener* listener = *it;
listener->OnUnexpectedDisconnect(
this, device_uid, app_handle, CommunicationError());
}
}
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
TransportAdapterListener* listener = *it;
listener->OnDisconnectDeviceDone(this, device_uid);
}
for (ApplicationList::const_iterator i = app_list.begin();
i != app_list.end();
++i) {
ApplicationHandle app_handle = *i;
RemoveConnection(device_uid, app_handle);
}
RemoveDevice(device_uid);
SDL_LOG_TRACE("exit");
}
bool TransportAdapterImpl::IsSingleApplication(
const DeviceUID& device_uid, const ApplicationHandle& app_uid) {
SDL_LOG_AUTO_TRACE();
sync_primitives::AutoReadLock locker(connections_lock_);
for (ConnectionMap::const_iterator it = connections_.begin();
it != connections_.end();
++it) {
const DeviceUID& current_device_id = it->first.first;
const ApplicationHandle& current_app_handle = it->first.second;
if (current_device_id == device_uid && current_app_handle != app_uid) {
SDL_LOG_DEBUG(
"break. Condition: current_device_id == device_id && "
"current_app_handle != app_handle");
return false;
}
}
return true;
}
void TransportAdapterImpl::DisconnectDone(const DeviceUID& device_handle,
const ApplicationHandle& app_handle) {
SDL_LOG_AUTO_TRACE();
const DeviceUID device_uid = device_handle;
const ApplicationHandle app_uid = app_handle;
SDL_LOG_TRACE("enter. device_id: " << &device_uid
<< ", app_handle: " << &app_uid);
DeviceSptr device = FindDevice(device_handle);
if (!device) {
SDL_LOG_WARN("Device: uid " << &device_uid << " not found");
return;
}
bool device_disconnected =
ToBeAutoDisconnected(device) && IsSingleApplication(device_uid, app_uid);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
TransportAdapterListener* listener = *it;
listener->OnDisconnectDone(this, device_uid, app_uid);
if (device_disconnected) {
listener->OnDisconnectDeviceDone(this, device_uid);
}
}
RemoveConnection(device_uid, app_uid);
if (device_disconnected) {
SDL_LOG_DEBUG("Removing device...");
RemoveDevice(device_uid);
}
Store();
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::DataReceiveDone(
const DeviceUID& device_id,
const ApplicationHandle& app_handle,
::protocol_handler::RawMessagePtr message) {
SDL_LOG_TRACE("enter. device_id: " << &device_id
<< ", app_handle: " << &app_handle
<< ", message: " << message);
#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
metric_observer_->StartRawMsg(message.get());
}
#endif // TELEMETRY_MONITOR
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnDataReceiveDone(this, device_id, app_handle, message);
}
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::DataReceiveFailed(
const DeviceUID& device_id,
const ApplicationHandle& app_handle,
const DataReceiveError& error) {
SDL_LOG_TRACE("enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnDataReceiveFailed(this, device_id, app_handle, error);
}
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::DataSendDone(
const DeviceUID& device_id,
const ApplicationHandle& app_handle,
::protocol_handler::RawMessagePtr message) {
SDL_LOG_TRACE("enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnDataSendDone(this, device_id, app_handle, message);
}
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::DataSendFailed(
const DeviceUID& device_id,
const ApplicationHandle& app_handle,
::protocol_handler::RawMessagePtr message,
const DataSendError& error) {
SDL_LOG_TRACE("enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnDataSendFailed(this, device_id, app_handle, message, error);
}
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::TransportConfigUpdated(
const TransportConfig& new_config) {
SDL_LOG_AUTO_TRACE();
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnTransportConfigUpdated(this);
}
}
void TransportAdapterImpl::DoTransportSwitch() const {
SDL_LOG_AUTO_TRACE();
std::for_each(
listeners_.begin(),
listeners_.end(),
std::bind2nd(
std::mem_fun(&TransportAdapterListener::OnTransportSwitchRequested),
this));
}
void TransportAdapterImpl::DeviceSwitched(const DeviceUID& device_handle) {
SDL_LOG_DEBUG("Switching is not implemented for that adapter type "
<< GetConnectionType().c_str());
UNUSED(device_handle);
}
ConnectionSPtr TransportAdapterImpl::FindPendingConnection(
const DeviceUID& device_id, const ApplicationHandle& app_handle) const {
SDL_LOG_TRACE("enter. device_id: " << &device_id
<< ", app_handle: " << &app_handle);
ConnectionSPtr connection;
connections_lock_.AcquireForReading();
ConnectionMap::const_iterator it =
connections_.find(std::make_pair(device_id, app_handle));
if (it != connections_.end()) {
const ConnectionInfo& info = it->second;
if (info.state == ConnectionInfo::PENDING) {
connection = info.connection;
}
}
connections_lock_.Release();
SDL_LOG_TRACE("exit with Connection: " << connection);
return connection;
}
DeviceSptr TransportAdapterImpl::FindDevice(const DeviceUID& device_id) const {
SDL_LOG_TRACE("enter. device_id: " << &device_id);
DeviceSptr ret;
sync_primitives::AutoLock locker(devices_mutex_);
SDL_LOG_DEBUG("devices_.size() = " << devices_.size());
DeviceMap::const_iterator it = devices_.find(device_id);
if (it != devices_.end()) {
ret = it->second;
} else {
SDL_LOG_WARN("Device " << device_id << " not found.");
}
SDL_LOG_TRACE("exit with DeviceSptr: " << ret);
return ret;
}
void TransportAdapterImpl::ConnectPending(const DeviceUID& device_id,
const ApplicationHandle& app_handle) {
SDL_LOG_AUTO_TRACE();
connections_lock_.AcquireForWriting();
ConnectionMap::iterator it_conn =
connections_.find(std::make_pair(device_id, app_handle));
if (it_conn != connections_.end()) {
ConnectionInfo& info = it_conn->second;
info.state = ConnectionInfo::PENDING;
}
connections_lock_.Release();
DeviceSptr device = FindDevice(device_id);
if (device.use_count() == 0) {
SDL_LOG_ERROR(
"Unable to find device, cannot set connection pending status");
return;
} else {
device->set_connection_status(ConnectionStatus::PENDING);
}
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnConnectPending(this, device_id, app_handle);
}
}
void TransportAdapterImpl::ConnectDone(const DeviceUID& device_id,
const ApplicationHandle& app_handle) {
SDL_LOG_TRACE("enter. device_id: " << &device_id
<< ", app_handle: " << &app_handle);
connections_lock_.AcquireForReading();
ConnectionMap::iterator it_conn =
connections_.find(std::make_pair(device_id, app_handle));
if (it_conn != connections_.end()) {
ConnectionInfo& info = it_conn->second;
info.state = ConnectionInfo::ESTABLISHED;
}
connections_lock_.Release();
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnConnectDone(this, device_id, app_handle);
}
Store();
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::ConnectFailed(const DeviceUID& device_handle,
const ApplicationHandle& app_handle,
const ConnectError& error) {
const DeviceUID device_uid = device_handle;
const ApplicationHandle app_uid = app_handle;
SDL_LOG_TRACE("enter. device_id: " << &device_uid << ", app_handle: "
<< &app_uid << ", error: " << &error);
RemoveConnection(device_uid, app_uid);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnConnectFailed(this, device_uid, app_uid, error);
}
SDL_LOG_TRACE("exit");
}
void TransportAdapterImpl::RemoveFinalizedConnection(
const DeviceUID& device_handle, const ApplicationHandle& app_handle) {
const DeviceUID device_uid = device_handle;
SDL_LOG_AUTO_TRACE();
{
connections_lock_.AcquireForWriting();
auto it_conn = connections_.find(std::make_pair(device_uid, app_handle));
if (connections_.end() == it_conn) {
SDL_LOG_WARN("Device_id: " << &device_uid << ", app_handle: "
<< &app_handle << " connection not found");
connections_lock_.Release();
return;
}
const ConnectionInfo& info = it_conn->second;
if (ConnectionInfo::FINALISING != info.state) {
SDL_LOG_WARN("Device_id: " << &device_uid << ", app_handle: "
<< &app_handle << " connection not finalized");
connections_lock_.Release();
return;
}
// By copying the info.connection shared pointer into this local variable,
// we can delay the connection's destructor until after
// connections_lock_.Release.
SDL_LOG_DEBUG(
"RemoveFinalizedConnection copying connection with Device_id: "
<< &device_uid << ", app_handle: " << &app_handle);
ConnectionSPtr connection = info.connection;
connections_.erase(it_conn);
connections_lock_.Release();
SDL_LOG_DEBUG("RemoveFinalizedConnection Connections Lock Released");
}
DeviceSptr device = FindDevice(device_handle);
if (!device) {
SDL_LOG_WARN("Device: uid " << &device_uid << " not found");
return;
}
if (ToBeAutoDisconnected(device) &&
IsSingleApplication(device_handle, app_handle)) {
RemoveDevice(device_uid);
}
}
void TransportAdapterImpl::RemoveConnection(
const DeviceUID& device_id, const ApplicationHandle& app_handle) {
SDL_LOG_AUTO_TRACE();
ConnectionSPtr connection;
connections_lock_.AcquireForWriting();
ConnectionMap::const_iterator it =
connections_.find(std::make_pair(device_id, app_handle));
if (it != connections_.end()) {
// By copying the connection from the map to this shared pointer,
// we can erase the object from the map without triggering the destructor
SDL_LOG_DEBUG("Copying connection with Device_id: "
<< &device_id << ", app_handle: " << &app_handle);
connection = it->second.connection;
connections_.erase(it);
}
connections_lock_.Release();
SDL_LOG_DEBUG("Connections Lock Released");
// And now, "connection" goes out of scope, triggering the destructor outside
// of the "connections_lock_"
}
void TransportAdapterImpl::AddListener(TransportAdapterListener* listener) {
SDL_LOG_TRACE("enter");
listeners_.push_back(listener);
SDL_LOG_TRACE("exit");
}
ApplicationList TransportAdapterImpl::GetApplicationList(
const DeviceUID& device_id) const {
SDL_LOG_TRACE("enter. device_id: " << &device_id);
DeviceSptr device = FindDevice(device_id);
if (device.use_count() != 0) {
ApplicationList lst = device->GetApplicationList();
SDL_LOG_TRACE("exit with ApplicationList. It's size = "
<< lst.size() << " Condition: device.use_count() != 0");
return lst;
}
SDL_LOG_TRACE(
"exit with empty ApplicationList. Condition: NOT "
"device.use_count() != 0");
return ApplicationList();
}
void TransportAdapterImpl::ConnectionFinished(
const DeviceUID& device_id, const ApplicationHandle& app_handle) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_TRACE("enter. device_id: " << &device_id
<< ", app_handle: " << &app_handle);
connections_lock_.AcquireForReading();
ConnectionMap::iterator it =
connections_.find(std::make_pair(device_id, app_handle));
if (it != connections_.end()) {
ConnectionInfo& info = it->second;
info.state = ConnectionInfo::FINALISING;
}
connections_lock_.Release();
}
void TransportAdapterImpl::ConnectionAborted(
const DeviceUID& device_id,
const ApplicationHandle& app_handle,
const CommunicationError& error) {
SDL_LOG_AUTO_TRACE();
ConnectionFinished(device_id, app_handle);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
(*it)->OnUnexpectedDisconnect(this, device_id, app_handle, error);
}
}
bool TransportAdapterImpl::IsInitialised() const {
SDL_LOG_TRACE("enter");
if (!initialised_) {
SDL_LOG_TRACE("exit with FALSE. Condition: !initialised_");
return false;
}
if (device_scanner_ && !device_scanner_->IsInitialised()) {
SDL_LOG_TRACE(
"exit with FALSE. Condition: device_scanner_ && "
"!device_scanner_->IsInitialised()");
return false;
}
if (server_connection_factory_ &&
!server_connection_factory_->IsInitialised()) {
SDL_LOG_TRACE(
"exit with FALSE. Condition: server_connection_factory_ && "
"!server_connection_factory_->IsInitialised()");
return false;
}
if (client_connection_listener_ &&
!client_connection_listener_->IsInitialised()) {
SDL_LOG_TRACE(
"exit with FALSE. Condition: client_connection_listener_ && "
"!client_connection_listener_->IsInitialised()");
return false;
}
SDL_LOG_TRACE("exit with TRUE");
return true;
}
std::string TransportAdapterImpl::DeviceName(const DeviceUID& device_id) const {
DeviceSptr device = FindDevice(device_id);
if (device.use_count() != 0) {
return device->name();
} else {
return "";
}
}
void TransportAdapterImpl::StopDevice(const DeviceUID& device_id) const {
SDL_LOG_AUTO_TRACE();
DeviceSptr device = FindDevice(device_id);
if (device) {
device->Stop();
}
}
std::string TransportAdapterImpl::GetConnectionType() const {
return devicesType[GetDeviceType()];
}
SwitchableDevices TransportAdapterImpl::GetSwitchableDevices() const {
SDL_LOG_AUTO_TRACE();
SwitchableDevices devices;
sync_primitives::AutoLock locker(devices_mutex_);
for (DeviceMap::const_iterator it = devices_.begin(); it != devices_.end();
++it) {
const auto device_uid = it->first;
const auto device = it->second;
const auto transport_switch_id = device->transport_switch_id();
if (transport_switch_id.empty()) {
SDL_LOG_DEBUG("Device is not suitable for switching: " << device_uid);
continue;
}
SDL_LOG_DEBUG("Device is suitable for switching: " << device_uid);
devices.insert(std::make_pair(device_uid, transport_switch_id));
}
SDL_LOG_INFO("Found number of switchable devices: " << devices.size());
return devices;
}
#ifdef TELEMETRY_MONITOR
void TransportAdapterImpl::SetTelemetryObserver(TMTelemetryObserver* observer) {
metric_observer_ = observer;
}
#endif // TELEMETRY_MONITOR
#ifdef TELEMETRY_MONITOR
TMTelemetryObserver* TransportAdapterImpl::GetTelemetryObserver() {
return metric_observer_;
}
#endif // TELEMETRY_MONITOR
void TransportAdapterImpl::Store() const {}
bool TransportAdapterImpl::Restore() {
return true;
}
bool TransportAdapterImpl::ToBeAutoConnected(DeviceSptr device) const {
return false;
}
bool TransportAdapterImpl::ToBeAutoDisconnected(DeviceSptr device) const {
SDL_LOG_AUTO_TRACE();
return true;
}
ConnectionSPtr TransportAdapterImpl::FindEstablishedConnection(
const DeviceUID& device_id, const ApplicationHandle& app_handle) const {
SDL_LOG_TRACE("enter. device_id: " << &device_id
<< ", app_handle: " << &app_handle);
ConnectionSPtr connection;
connections_lock_.AcquireForReading();
ConnectionMap::const_iterator it =
connections_.find(std::make_pair(device_id, app_handle));
if (it != connections_.end()) {
const ConnectionInfo& info = it->second;
if (info.state == ConnectionInfo::ESTABLISHED) {
connection = info.connection;
}
}
connections_lock_.Release();
SDL_LOG_TRACE("exit with Connection: " << connection);
return connection;
}
TransportAdapter::Error TransportAdapterImpl::ConnectDevice(DeviceSptr device) {
SDL_LOG_TRACE("enter. device: " << device);
DeviceUID device_id = device->unique_device_id();
ApplicationList app_list = device->GetApplicationList();
SDL_LOG_INFO("Device " << device->name() << " has " << app_list.size()
<< " applications.");
bool errors_occurred = false;
for (ApplicationList::iterator it = app_list.begin(); it != app_list.end();
++it) {
const ApplicationHandle app_handle = *it;
SDL_LOG_DEBUG("Attempt to connect device " << device_id << ", channel "
<< app_handle);
const Error error = Connect(device_id, app_handle);
switch (error) {
case OK:
SDL_LOG_DEBUG("error = OK");
break;
case ALREADY_EXISTS:
SDL_LOG_DEBUG("error = ALREADY_EXISTS");
break;
default:
SDL_LOG_ERROR("Connect to device " << device_id << ", channel "
<< app_handle
<< " failed with error " << error);
errors_occurred = true;
SDL_LOG_DEBUG("switch (error), default case");
break;
}
}
if (errors_occurred) {
SDL_LOG_TRACE("exit with error:FAIL");
return FAIL;
} else {
SDL_LOG_TRACE("exit with error:OK");
return OK;
}
}
void TransportAdapterImpl::RunAppOnDevice(const DeviceUID& device_uid,
const std::string& bundle_id) {
SDL_LOG_AUTO_TRACE();
DeviceSptr device = FindDevice(device_uid);
if (!device) {
SDL_LOG_WARN("Device with id: " << device_uid << " Not found"
<< "withing list of connected deviced");
return;
}
device->LaunchApp(bundle_id);
}
void TransportAdapterImpl::RemoveDevice(const DeviceUID& device_handle) {
SDL_LOG_AUTO_TRACE();
SDL_LOG_DEBUG("Remove Device_handle: " << &device_handle);
sync_primitives::AutoLock locker(devices_mutex_);
DeviceMap::iterator i = devices_.find(device_handle);
if (i != devices_.end()) {
DeviceSptr device = i->second;
bool is_cloud_device = (GetDeviceType() == DeviceType::CLOUD_WEBSOCKET);
if (!device->keep_on_disconnect() || is_cloud_device) {
devices_.erase(i);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
it != listeners_.end();
++it) {
TransportAdapterListener* listener = *it;
listener->OnDeviceListUpdated(this);
}
}
}
}
} // namespace transport_adapter
} // namespace transport_manager
| 33.517703
| 80
| 0.682284
|
Sohei-Suzuki-Nexty
|
447c19bf23455320cec4b0192584ed77e70ebf73
| 2,593
|
cpp
|
C++
|
AnnService/src/Core/Common/InstructionUtils.cpp
|
tornado12345/SPTAG
|
067e5d267e73eb26cb6e4195db4f2b174284fd6b
|
[
"MIT"
] | 4,351
|
2019-05-07T06:04:41.000Z
|
2022-03-30T12:46:19.000Z
|
AnnService/src/Core/Common/InstructionUtils.cpp
|
tornado12345/SPTAG
|
067e5d267e73eb26cb6e4195db4f2b174284fd6b
|
[
"MIT"
] | 140
|
2019-05-13T08:55:27.000Z
|
2022-03-29T16:56:16.000Z
|
AnnService/src/Core/Common/InstructionUtils.cpp
|
tornado12345/SPTAG
|
067e5d267e73eb26cb6e4195db4f2b174284fd6b
|
[
"MIT"
] | 552
|
2019-05-15T16:27:52.000Z
|
2022-03-18T15:12:44.000Z
|
#include "inc/Core/Common/InstructionUtils.h"
#include "inc/Core/Common.h"
#ifndef _MSC_VER
void cpuid(int info[4], int InfoType) {
__cpuid_count(InfoType, 0, info[0], info[1], info[2], info[3]);
}
#endif
namespace SPTAG {
namespace COMMON {
const InstructionSet::InstructionSet_Internal InstructionSet::CPU_Rep;
bool InstructionSet::SSE(void) { return CPU_Rep.HW_SSE; }
bool InstructionSet::SSE2(void) { return CPU_Rep.HW_SSE2; }
bool InstructionSet::AVX(void) { return CPU_Rep.HW_AVX; }
bool InstructionSet::AVX2(void) { return CPU_Rep.HW_AVX2; }
void InstructionSet::PrintInstructionSet(void)
{
if (CPU_Rep.HW_AVX2)
LOG(Helper::LogLevel::LL_Info, "Using AVX2 InstructionSet!\n");
else if (CPU_Rep.HW_AVX)
LOG(Helper::LogLevel::LL_Info, "Using AVX InstructionSet!\n");
else if (CPU_Rep.HW_SSE2)
LOG(Helper::LogLevel::LL_Info, "Using SSE2 InstructionSet!\n");
else if (CPU_Rep.HW_SSE)
LOG(Helper::LogLevel::LL_Info, "Using SSE InstructionSet!\n");
else
LOG(Helper::LogLevel::LL_Info, "Using NONE InstructionSet!\n");
}
// from https://stackoverflow.com/a/7495023/5053214
InstructionSet::InstructionSet_Internal::InstructionSet_Internal() :
HW_SSE{ false },
HW_SSE2{ false },
HW_AVX{ false },
HW_AVX2{ false }
{
int info[4];
cpuid(info, 0);
int nIds = info[0];
// Detect Features
if (nIds >= 0x00000001) {
cpuid(info, 0x00000001);
HW_SSE = (info[3] & ((int)1 << 25)) != 0;
HW_SSE2 = (info[3] & ((int)1 << 26)) != 0;
HW_AVX = (info[2] & ((int)1 << 28)) != 0;
}
if (nIds >= 0x00000007) {
cpuid(info, 0x00000007);
HW_AVX2 = (info[1] & ((int)1 << 5)) != 0;
}
if (HW_AVX2)
LOG(Helper::LogLevel::LL_Info, "Using AVX2 InstructionSet!\n");
else if (HW_AVX)
LOG(Helper::LogLevel::LL_Info, "Using AVX InstructionSet!\n");
else if (HW_SSE2)
LOG(Helper::LogLevel::LL_Info, "Using SSE2 InstructionSet!\n");
else if (HW_SSE)
LOG(Helper::LogLevel::LL_Info, "Using SSE InstructionSet!\n");
else
LOG(Helper::LogLevel::LL_Info, "Using NONE InstructionSet!\n");
}
}
}
| 38.132353
| 79
| 0.538758
|
tornado12345
|
4484654fc9ccf6f86d73476a16d233513532cfec
| 2,099
|
cc
|
C++
|
leet_code/Multiply_Strings/solve.cc
|
ldy121/algorithm
|
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
|
[
"Apache-2.0"
] | 1
|
2020-04-11T22:04:23.000Z
|
2020-04-11T22:04:23.000Z
|
leet_code/Multiply_Strings/solve.cc
|
ldy121/algorithm
|
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
|
[
"Apache-2.0"
] | null | null | null |
leet_code/Multiply_Strings/solve.cc
|
ldy121/algorithm
|
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
string multiply(string num1, string num2) {
vector<string> partial_result;
string digit = "";
for_each(num2.rbegin(), num2.rend(), [&num1, &digit, &partial_result](const auto ch2) {
const auto op2 = ch2 - '0';
auto carry = 0;
string val = digit;
for_each(num1.rbegin(), num1.rend(), [&carry, &val, &op2](const auto ch1){
const auto op1 = ch1 - '0';
const auto digit_result = op1 * op2 + carry;
val = val + (char)(digit_result % 10 + '0');
carry = digit_result / 10;
});
if (carry > 0) {
val = val + (char)(carry + '0');
}
partial_result.push_back(val);
digit += "0";
});
string ret = partial_result[partial_result.size() - 1];
for (int i = partial_result.size() - 2; i >= 0; --i) {
auto j = 0;
auto carry = 0;
while (j < ret.length() && j < partial_result[i].length()) {
auto op1 = ret[j] - '0';
auto op2 = partial_result[i][j] - '0';
auto val = op1 + op2 + carry;
carry = val / 10;
ret[j++] = (char)(val % 10 + '0');
}
while (carry > 0) {
if (j == ret.length()) {
ret.push_back((char)(carry + '0'));
break;
} else {
auto op = ret[j] - '0';
auto val = op + carry;
ret[j] = (char)(val % 10 + '0');
carry = val / 10;
}
++j;
}
}
reverse(ret.begin(), ret.end());
for (auto i = 0; i <= ret.length(); ++i) {
if (i == ret.length()) {
ret = "0";
break;
}
if (ret[i] != '0') {
break;
}
}
return ret;
}
};
| 31.80303
| 95
| 0.370176
|
ldy121
|
4486109a504e520bbc6c9c4b99cb015568d3c5c5
| 6,771
|
cpp
|
C++
|
src/p3d/legacy/internal/NL_GameManager.cpp
|
AlexandrSachkov/Prototype3D
|
1cf705973a8d9137014935686b7fcb034ab95123
|
[
"MIT"
] | 7
|
2018-09-10T04:57:48.000Z
|
2020-12-16T12:29:52.000Z
|
src/p3d/legacy/internal/NL_GameManager.cpp
|
AlexandrSachkov/Prototype3D
|
1cf705973a8d9137014935686b7fcb034ab95123
|
[
"MIT"
] | null | null | null |
src/p3d/legacy/internal/NL_GameManager.cpp
|
AlexandrSachkov/Prototype3D
|
1cf705973a8d9137014935686b7fcb034ab95123
|
[
"MIT"
] | 4
|
2015-11-25T07:41:10.000Z
|
2019-06-12T22:30:54.000Z
|
#include "NL_GameManager.h"
#include "NL_RenderingEngine.h"
#include "NL_ScriptingEngine.h"
#include "NL_ThreadLocal.h"
#include "NL_GameObject.h"
#include "NL_EngineServices.h"
#include "NL_SharedData.h"
#include "NL_IWindowManager.h"
#include <fstream>
namespace NLE
{
namespace GAME
{
GameManager::GameManager(
EngineServices eServices,
IWindowManagerSP windowManager,
IO::IFileIOManagerSP file,
SERIALIZATION::ISerializerSP serializer,
GRAPHICS::IRenderingEngineSP renderingEngine,
SCRIPT::IScriptingEngineSP scriptingEngine
) :
_eServices(eServices),
_windowManager(windowManager),
_file(file),
_serializer(serializer),
_renderingEngine(renderingEngine),
_scriptingEngine(scriptingEngine)
{
_execStatus = ExecStatus::CONTINUE;
newGame();
/*
_commandBuffer.addFunction(COMMAND::RESTART_GAME, [&](COMMAND::Data data) { _execStatus = RESTART; });
_commandBuffer.addFunction(COMMAND::ADD_OBJECT, [&](COMMAND::Data data) {
_currentScene->addObject(new GameObject());
});
_commandBuffer.addFunction(COMMAND::UPDATE_OBJECT, [&](COMMAND::Data data) {
_currentScene->addObject(data.gameObject);
});
_commandBuffer.addFunction(COMMAND::LOAD_OBJECT, [&](COMMAND::Data data) {
std::wstring path = TLS::strConverter.local().from_bytes(data.name);
_file->readAsync(path + L".nleobject", [=](std::vector<char>* data) {
GameObject* object = _serializer.deserialize<GameObject>(data);
delete data;
COMMAND::Data updateData;
updateData.gameObject = object;
_commandBuffer.queueCommand(COMMAND::UPDATE_OBJECT, updateData);
}, [=]() {
eServices.console->push(CONSOLE::ERR, L"Failed to load game object " + path);
});
});
_commandBuffer.addFunction(COMMAND::SAVE_OBJECT, [&](COMMAND::Data data) {
auto* objectData = _serializer.serialize<GameObject>(data.gameObject);
_file->writeAsync(data.scene->getName() + L".nleobject", objectData, [=](std::vector<char>* serializedData) {
delete serializedData;
eServices.console->push(CONSOLE::STANDARD, L"Successfully saved game object " + data.gameObject->getName());
}, [=](std::vector<char>* serializedData) {
delete serializedData;
eServices.console->push(CONSOLE::ERR, L"Failed to save game object " + data.gameObject->getName());
});
});*/
}
GameManager::~GameManager()
{
}
void GameManager::update(SystemServices& sServices, double deltaT)
{
NLE::TLS::PerformanceTimer::reference timer = NLE::TLS::performanceTimer.local();
timer.deltaT();
auto& ex = TLS::scriptExecutor.local();
ex.executeContextScript(_game->getScriptingContext(), SCRIPT::ON_UPDATE);
ex.executeContextScript(_currentScene->getScriptingContext(), SCRIPT::ON_UPDATE);
DATA::SharedData& data = _eServices.data->getData();
data.sysExecutionTimes.set(GAME_MANAGER, timer.deltaT());
}
bool GameManager::hasUnsavedChanges()
{
return true;
}
void GameManager::newGame()
{
/*_game = std::make_unique<Game>(_eServices.console);
newScene();
_eServices.console->push(CONSOLE::STANDARD, "Starting new game.");*/
}
void GameManager::newScene()
{
/*_currentScene = std::make_unique<Scene>();
_eServices.console->push(CONSOLE::STANDARD, "Starting new scene.");*/
}
void GameManager::loadGame(std::string path)
{
/*std::vector<char>* data = _file->read(path);
if (data)
{
Game* game = _serializer->deserialize<Game>(data);
delete data;
_eServices.console->push(CONSOLE::STANDARD, "Successfully loaded game: " + path);
updateGame(game);
}
else
{
_eServices.console->push(CONSOLE::ERR, "Failed to load game: " + path);
}*/
}
void GameManager::loadScene(std::string path)
{
/*std::vector<char>* data = _file->read(path);
if (data)
{
Scene* scene = _serializer->deserialize<Scene>(data);
delete data;
_eServices.console->push(CONSOLE::STANDARD, "Successfully loaded scene: " + path);
updateScene(scene);
}
else
{
_eServices.console->push(CONSOLE::ERR, "Failed to load scene: " + path);
}*/
}
void GameManager::loadSceneByName(std::string name)
{
/*auto scenePath = _game->getScenePath(name);
if (scenePath.compare("") != 0)
{
loadScene(scenePath);
}
else
{
_eServices.console->push(CONSOLE::ERR, "Failed to find scene by name: " + name);
}*/
}
void GameManager::updateGame(Game* game)
{
/*game->attachConsole(_eServices.console);
auto& ex = TLS::scriptExecutor.local();
ex.executeContextScript(_game->getScriptingContext(), SCRIPT::ON_EXIT);
_game = std::unique_ptr<Game>(game);
ex.executeContextScript(_game->getScriptingContext(), SCRIPT::ON_INIT);
std::string initialSceneName = game->getInitialScene();
if (initialSceneName.compare("") != 0)
{
loadSceneByName(initialSceneName);
} */
}
void GameManager::updateScene(Scene* scene)
{
auto& ex = TLS::scriptExecutor.local();
ex.executeContextScript(_currentScene->getScriptingContext(), SCRIPT::ON_EXIT);
_currentScene = std::unique_ptr<Scene>(scene);
ex.executeContextScript(_currentScene->getScriptingContext(), SCRIPT::ON_INIT);
}
void GameManager::saveGame(std::string name)
{
/*if (!name.empty()) {
_game->setName(name);
}
auto* gameData = _serializer->serialize<Game>(_game.get());
if (_file->write(_game->getName() + ".nlegame", gameData))
{
delete gameData;
_eServices.console->push(CONSOLE::STANDARD, "Successfully saved game: " + _game->getName());
}
else
{
delete gameData;
_eServices.console->push(CONSOLE::ERR, "Failed to save game: " + _game->getName());
}*/
}
void GameManager::saveScene(std::string name)
{
/*if (!name.empty()) {
_currentScene->setName(name);
}
auto* sceneData = _serializer->serialize<Scene>(_currentScene.get());
if (_file->write(_currentScene->getName() + ".nlescene", sceneData))
{
delete sceneData;
_eServices.console->push(CONSOLE::STANDARD, "Successfully saved scene: " + _currentScene->getName());
}
else
{
delete sceneData;
_eServices.console->push(CONSOLE::ERR, "Failed to save scene: " + _currentScene->getName());
}*/
}
void GameManager::quitGame()
{
auto& ex = TLS::scriptExecutor.local();
ex.executeContextScript(_currentScene->getScriptingContext(), SCRIPT::ON_EXIT);
ex.executeContextScript(_game->getScriptingContext(), SCRIPT::ON_EXIT);
_execStatus = TERMINATE;
}
ExecStatus GameManager::getExecutionStatus()
{
return _execStatus;
}
Game& GameManager::getGame()
{
return *_game;
}
Scene& GameManager::getCurrentScene()
{
return *_currentScene;
}
}
}
| 27.084
| 113
| 0.678925
|
AlexandrSachkov
|
4487e6e1d63b56eea3df6c0d8310d4397d6f3f37
| 7,445
|
cpp
|
C++
|
Map/MapDriver.cpp
|
rmanaem/risk-warzone
|
2d9929543dec0787dbb7d82717e970ead8c2cdb6
|
[
"MIT"
] | null | null | null |
Map/MapDriver.cpp
|
rmanaem/risk-warzone
|
2d9929543dec0787dbb7d82717e970ead8c2cdb6
|
[
"MIT"
] | null | null | null |
Map/MapDriver.cpp
|
rmanaem/risk-warzone
|
2d9929543dec0787dbb7d82717e970ead8c2cdb6
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "Map.h"
#include <vector>
#include <stack>
using namespace std;
/*
Quick instruction:
If you want to see the third illustation being validated, the second one should be fixed.
To do so, just remove the comment from line 88 (i.e. establish the brazil --> north africa connection).
*/
int main()
{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ valid Map illustration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
Map *validMap = new Map();
//create the South America continent
Continent *southAmerica = validMap->createContinent("South America", 10);
Territory *venzuela = new Territory("Venzuela", southAmerica);
Territory *brazil = new Territory("Brazil", southAmerica);
Territory *argentina = new Territory("Argentina", southAmerica);
Territory *peru = new Territory("Peru", southAmerica);
validMap->insertAndConnectTwoTerritories(*venzuela, *brazil); // venzuela --> brazil
validMap->insertAndConnectTwoTerritories(*argentina, *peru); // argentina --> peru
validMap->connectTwoNodes(validMap->getV()[0], validMap->getV().end()[-1]); //venzuela --> peru
validMap->connectTwoNodes(validMap->getV().end()[-1], validMap->getV()[1]); //peru --> brazil
//create the Africa continent
Continent *africa = validMap->createContinent("Africa", 10);
Territory *northAfrica = new Territory("North Africa", africa);
Territory *egypt = new Territory("Egypt", africa);
Territory *eastAfrica = new Territory("East Africa", africa);
Territory *congo = new Territory("Congo", africa);
Territory *southAfrica = new Territory("South Africa", africa);
Territory *mdagascar = new Territory("Mdagascar", africa);
validMap->insertAndConnectTwoTerritories(*northAfrica, *egypt); //north africa --> egypt
validMap->insertAndConnectTwoTerritories(*eastAfrica, *congo); //east africa --> congo
validMap->insertAndConnectTwoTerritories(*southAfrica, *mdagascar); //south africa --> mdagascar
validMap->connectTwoNodes(validMap->getV()[4], validMap->getV()[7]); //north africa --> congo
validMap->connectTwoNodes(validMap->getV()[7], validMap->getV().end()[-2]); //congo --> south africa
validMap->connectTwoNodes(validMap->getV()[5], validMap->getV()[6]); //egypt --> east africa
//connect between south america and africa
validMap->connectTwoNodes(validMap->getV()[1], validMap->getV()[4]); //brazil --> north africa
// for(Node* territory : validMap->getV()){
// cout<<territory->getData().getTerritoryName() + " belongs to " + territory->getData().getContinent()->getContinentName()
// + " has the following edges:"<<endl;
// for(string edge : territory->getE()){
// cout<<edge<<"\t";
// }
// cout<<endl;
// }
validMap->validate();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ invalid Map illustration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Unconnected graph
Map *invalidMap = new Map();
//create the South America continent
Continent *southAmericaInvalid = invalidMap->createContinent("South America", 10);
Territory *venzuelaInvalid = new Territory("Venzuela", southAmericaInvalid);
Territory *brazilInvalid = new Territory("Brazil", southAmericaInvalid);
Territory *argentinaInvalid = new Territory("Argentina", southAmericaInvalid);
Territory *peruInvalid = new Territory("Peru", southAmericaInvalid);
invalidMap->insertAndConnectTwoTerritories(*venzuelaInvalid, *brazilInvalid); // venzuela --> brazil
invalidMap->insertAndConnectTwoTerritories(*argentinaInvalid, *peruInvalid); // argentina --> peru
invalidMap->connectTwoNodes(invalidMap->getV()[0], invalidMap->getV().end()[-1]); //venzuela --> peru
invalidMap->connectTwoNodes(invalidMap->getV().end()[-1], invalidMap->getV()[1]); //peru --> brazil
//create the Africa continent
Continent *africaInvalid = invalidMap->createContinent("Africa", 10);
Territory *northAfricaInvalid = new Territory("North Africa", africaInvalid);
Territory *egyptInvalid = new Territory("Egypt", africaInvalid);
Territory *eastAfricaInvalid = new Territory("East Africa", africaInvalid);
Territory *congoInvalid = new Territory("Congo", africaInvalid);
Territory *southAfricaInvalid = new Territory("South Africa", africaInvalid);
Territory *mdagascarInvalid = new Territory("Mdagascar", africaInvalid);
invalidMap->insertAndConnectTwoTerritories(*northAfricaInvalid, *egyptInvalid); //north africa --> egypt
invalidMap->insertAndConnectTwoTerritories(*eastAfricaInvalid, *congoInvalid); //east africa --> congo
invalidMap->insertAndConnectTwoTerritories(*southAfricaInvalid, *mdagascarInvalid); //south africa --> mdagascar
invalidMap->connectTwoNodes(invalidMap->getV()[4], invalidMap->getV()[7]); //north africa --> congo
invalidMap->connectTwoNodes(invalidMap->getV()[7], invalidMap->getV().end()[-2]); //congo --> south africa
invalidMap->connectTwoNodes(invalidMap->getV()[5], invalidMap->getV()[6]); //egypt --> east africa
// No connection between south america and africa
invalidMap->connectTwoNodes(invalidMap->getV()[1], invalidMap->getV()[4]); //brazil --> north africa
// for(Node* territory : invalidMap->getV()){
// cout<<territory->getData().getTerritoryName() + " belongs to " + territory->getData().getContinent()->getContinentName()
// + " has the following edges:"<<endl;
// for(string edge : territory->getE()){
// cout<<edge<<"\t";
// }
// cout<<endl;
// }
invalidMap->validate();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ invalid Map illustration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Unconnected sub-graph
Map *Invalid11Map = new Map();
//create the South America continent
Continent *southAmericaInvalid1 = Invalid11Map->createContinent("South America", 10);
Territory *venzuelaInvalid1 = new Territory("Venzuela", southAmericaInvalid1);
Territory *brazilInvalid1 = new Territory("Brazil", southAmericaInvalid1);
Territory *argentinaInvalid1 = new Territory("Argentina", southAmericaInvalid1);
Territory *peruInvalid1 = new Territory("Peru", southAmericaInvalid1);
Invalid11Map->insertAndConnectTwoTerritories(*venzuelaInvalid1, *brazilInvalid1); // venzuela --> brazil
// Invalid11Map->insertATerritory(*venzuelaInvalid1);
// Invalid11Map->insertATerritory(*brazilInvalid1);
Invalid11Map->insertAndConnectTwoTerritories(*argentinaInvalid1, *peruInvalid1); // argentina --> peru
Invalid11Map->connectTwoNodes(Invalid11Map->getV()[0], Invalid11Map->getV().end()[-1]); //venzuela --> peru
Invalid11Map->connectTwoNodes(Invalid11Map->getV().end()[-1], Invalid11Map->getV()[1]); //peru --> brazil
// for(Node* territory : Invalid11Map->getV()){
// cout<<territory->getData().getTerritoryName() + " belongs to " + territory->getData().getContinent()->getContinentName()
// + " has the following edges:"<<endl;
// for(string edge : territory->getE()){
// cout<<edge<<"\t";
// }
// cout<<endl;
// }
Invalid11Map->validate();
delete validMap;
validMap = nullptr;
delete invalidMap;
invalidMap = nullptr;
delete Invalid11Map;
Invalid11Map = nullptr;
return 0;
}
| 53.561151
| 131
| 0.658831
|
rmanaem
|
44880f86d0d5604e40a1f2a807b1b29becbc23f0
| 5,080
|
hpp
|
C++
|
src/multimap.hpp
|
nfagan/categorical
|
4a309a07debd654d4e69cb80b58fd9c31cf888cc
|
[
"MIT"
] | null | null | null |
src/multimap.hpp
|
nfagan/categorical
|
4a309a07debd654d4e69cb80b58fd9c31cf888cc
|
[
"MIT"
] | null | null | null |
src/multimap.hpp
|
nfagan/categorical
|
4a309a07debd654d4e69cb80b58fd9c31cf888cc
|
[
"MIT"
] | null | null | null |
//
// multimap.hpp
// bit_array-test
//
// Created by Nick Fagan on 3/12/18.
//
#pragma once
#include <unordered_map>
#include <stdexcept>
#include <vector>
#include <cstdint>
namespace util {
template<typename K, typename V>
class multimap;
}
template<typename K, typename V>
class util::multimap
{
public:
multimap() = default;
~multimap() = default;
multimap(const util::multimap<K, V>& other);
multimap(multimap&& rhs) noexcept;
multimap& operator=(const multimap& other);
multimap& operator=(multimap&& rhs) noexcept;
auto find(const K& key) const;
auto find(const V& key) const;
auto endk() const;
auto endv() const;
std::vector<K> keys() const;
std::vector<V> values() const;
V at(const K& key) const;
K at(const V& key) const;
const V& ref_at(const K& key) const;
const K& ref_at(const V& key) const;
size_t erase(K key);
size_t erase(V key);
size_t size() const;
bool contains(const K& key) const;
bool contains(const V& key) const;
void insert(K key, V value);
private:
std::unordered_map<K, V> m_kv;
std::unordered_map<V, K> m_vk;
};
//
// impl
//
template<typename K, typename V>
util::multimap<K, V>::multimap(const util::multimap<K, V>& rhs) :
m_kv(rhs.m_kv),
m_vk(rhs.m_vk)
{
//
}
template<typename K, typename V>
util::multimap<K, V>& util::multimap<K, V>::operator=(const util::multimap<K, V>& rhs)
{
util::multimap<K, V> tmp(rhs);
*this = std::move(tmp);
return *this;
}
template<typename K, typename V>
util::multimap<K, V>::multimap(util::multimap<K, V>&& rhs) noexcept :
m_kv(std::move(rhs.m_kv)),
m_vk(std::move(rhs.m_vk))
{
//
}
template<typename K, typename V>
util::multimap<K, V>& util::multimap<K, V>::operator=(util::multimap<K, V>&& rhs) noexcept
{
m_kv = std::move(rhs.m_kv);
m_vk = std::move(rhs.m_vk);
return *this;
}
template<typename K, typename V>
V util::multimap<K, V>::at(const K& key) const
{
auto it = m_kv.find(key);
if (it == m_kv.end())
{
throw std::runtime_error("key does not exist.");
}
return it->second;
}
template<typename K, typename V>
K util::multimap<K, V>::at(const V& key) const
{
auto it = m_vk.find(key);
if (it == m_vk.end())
{
throw std::runtime_error("key does not exist.");
}
return it->second;
}
template<typename K, typename V>
const V& util::multimap<K, V>::ref_at(const K &key) const
{
const auto it = m_kv.find(key);
if (it == m_kv.end())
{
throw std::runtime_error("key does not exist.");
}
return it->second;
}
template<typename K, typename V>
const K& util::multimap<K, V>::ref_at(const V &key) const
{
const auto it = m_vk.find(key);
if (it == m_vk.end())
{
throw std::runtime_error("key does not exist.");
}
return it->second;
}
template<typename K, typename V>
void util::multimap<K, V>::insert(K key, V value)
{
auto ita = m_kv.find(key);
auto itb = m_vk.find(value);
if (ita != m_kv.end())
{
m_vk.erase(ita->second);
}
if (itb != m_vk.end())
{
m_kv.erase(itb->second);
}
m_kv[key] = value;
m_vk[value] = key;
}
template<typename K, typename V>
bool util::multimap<K, V>::contains(const K& key) const
{
return m_kv.find(key) != m_kv.end();
}
template<typename K, typename V>
bool util::multimap<K, V>::contains(const V& key) const
{
return m_vk.find(key) != m_vk.end();
}
template<typename K, typename V>
std::vector<K> util::multimap<K, V>::keys() const
{
std::vector<K> res;
for (const auto& it : m_kv)
{
res.push_back(it.first);
}
return res;
}
template<typename K, typename V>
std::vector<V> util::multimap<K, V>::values() const
{
std::vector<V> res;
for (const auto& it : m_kv)
{
res.push_back(it.second);
}
return res;
}
template<typename K, typename V>
size_t util::multimap<K, V>::erase(K key)
{
auto it = m_kv.find(key);
if (it == m_kv.end())
{
return 0;
}
m_vk.erase(it->second);
m_kv.erase(key);
return 1;
}
template<typename K, typename V>
size_t util::multimap<K, V>::erase(V key)
{
auto it = m_vk.find(key);
if (it == m_vk.end())
{
return 0;
}
m_kv.erase(it->second);
m_vk.erase(key);
return 1;
}
template<typename K, typename V>
size_t util::multimap<K, V>::size() const
{
return m_kv.size();
}
template<typename K, typename V>
auto util::multimap<K, V>::find(const K& key) const
{
return m_kv.find(key);
}
template<typename K, typename V>
auto util::multimap<K, V>::find(const V& key) const
{
return m_vk.find(key);
}
template<typename K, typename V>
auto util::multimap<K, V>::endk() const
{
return m_kv.end();
}
template<typename K, typename V>
auto util::multimap<K, V>::endv() const
{
return m_vk.end();
}
| 18.608059
| 90
| 0.58878
|
nfagan
|
44893b29c83a6e917f4d6f2b35baf0c92b912a41
| 6,472
|
cpp
|
C++
|
external/rapidcheck/test/state/IntegrationTests.cpp
|
XzoRit/cpp_rapidcheck
|
292c9943569e52e29fbd11abd31a965efc699a8e
|
[
"BSL-1.0"
] | 876
|
2015-01-29T00:48:46.000Z
|
2022-03-23T00:24:34.000Z
|
test/state/IntegrationTests.cpp
|
wuerges/rapidcheck
|
d2e0481b28b77fcd0c7ead9af1e8227ee9982739
|
[
"BSD-2-Clause"
] | 199
|
2015-05-18T07:04:40.000Z
|
2022-03-23T02:37:15.000Z
|
test/state/IntegrationTests.cpp
|
wuerges/rapidcheck
|
d2e0481b28b77fcd0c7ead9af1e8227ee9982739
|
[
"BSD-2-Clause"
] | 162
|
2015-03-12T20:19:31.000Z
|
2022-03-14T08:42:52.000Z
|
#include <catch2/catch.hpp>
#include <rapidcheck/catch.h>
#include <rapidcheck/state.h>
#include "util/GenUtils.h"
using namespace rc;
using namespace rc::test;
namespace {
struct Bag {
std::vector<int> items;
bool open = false;
};
using BagCommand = state::Command<Bag, Bag>;
struct Open : public BagCommand {
void checkPreconditions(const Model &s0) const override { RC_PRE(!s0.open); }
void apply(Model &s0) const override { s0.open = true; }
void run(const Model &s0, Sut &sut) const override { sut.open = true; }
void show(std::ostream &os) const override { os << "Open"; }
};
struct Close : public BagCommand {
void checkPreconditions(const Model &s0) const override { RC_PRE(s0.open); }
void apply(Model &s0) const override { s0.open = false; }
void run(const Model &s0, Sut &sut) const override { sut.open = false; }
void show(std::ostream &os) const override { os << "Close"; }
};
struct Add : public BagCommand {
int item = *gen::inRange<int>(0, 10);
void checkPreconditions(const Model &s0) const override { RC_PRE(s0.open); }
void apply(Model &s0) const override { s0.items.push_back(item); }
void run(const Model &s0, Sut &sut) const override {
sut.items.push_back(item);
}
void show(std::ostream &os) const override { os << "Add(" << item << ")"; }
};
struct Del : public BagCommand {
std::size_t index;
explicit Del(const Bag &s0) {
index = *gen::inRange<std::size_t>(0, s0.items.size());
}
void checkPreconditions(const Model &s0) const override {
RC_PRE(s0.open);
RC_PRE(index < s0.items.size());
}
void apply(Model &s0) const override {
auto s1 = s0;
s0.items.erase(begin(s0.items) + index);
}
void run(const Model &s0, Sut &sut) const override {
sut.items.erase(begin(sut.items) + index);
}
void show(std::ostream &os) const override { os << "Del(" << index << ")"; }
};
struct BuggyGet : public BagCommand {
std::size_t index;
explicit BuggyGet(const Bag &s0) {
index = *gen::inRange<std::size_t>(0, s0.items.size());
}
void checkPreconditions(const Model &s0) const override {
RC_PRE(s0.open);
RC_PRE(index < s0.items.size());
}
void run(const Model &s0, Sut &sut) const override {
RC_ASSERT(sut.items.size() < 2U);
RC_ASSERT(sut.items[index] == s0.items[index]);
}
void show(std::ostream &os) const override {
os << "BuggyGet(" << index << ")";
}
};
struct BuggyDelAll : public BagCommand {
int value;
explicit BuggyDelAll(const Bag &s0) { value = *gen::elementOf(s0.items); }
void checkPreconditions(const Model &s0) const override {
RC_PRE(s0.open);
RC_PRE(std::find(begin(s0.items), end(s0.items), value) != end(s0.items));
}
void apply(Model &s0) const override {
s0.items.erase(std::remove(begin(s0.items), end(s0.items), value),
end(s0.items));
}
void run(const Model &s0, Sut &sut) const override { RC_FAIL("Bug!"); }
void show(std::ostream &os) const override {
os << "BuggyDelAll(" << value << ")";
}
};
struct SneakyBuggyGet : public BagCommand {
int value;
explicit SneakyBuggyGet(const Bag &s0) { value = *gen::elementOf(s0.items); }
void checkPreconditions(const Model &s0) const override {
RC_PRE(s0.open);
RC_PRE(std::find(begin(s0.items), end(s0.items), value) != end(s0.items));
}
void run(const Model &s0, Sut &sut) const override { RC_ASSERT(value != 2); }
void show(std::ostream &os) const override {
os << "SneakyBuggyGet(" << value << ")";
}
};
template <typename Cmd>
std::vector<std::string> showCommands(const state::Commands<Cmd> &commands) {
std::vector<std::string> cmdStrings;
cmdStrings.reserve(commands.size());
for (const auto &cmd : commands) {
std::ostringstream ss;
cmd->show(ss);
cmdStrings.push_back(ss.str());
}
return cmdStrings;
}
template <typename Cmd>
state::Commands<Cmd> findMinCommands(const GenParams ¶ms,
const Gen<state::Commands<Cmd>> &gen,
const typename Cmd::Model &s0) {
return searchGen(params.random,
params.size,
gen,
[=](const state::Commands<Cmd> &cmds) {
try {
typename Cmd::Sut sut;
runAll(cmds, s0, sut);
} catch (...) {
return true;
}
return false;
});
}
} // namespace
TEST_CASE("state integration tests") {
prop(
"should find minimum when some commands might fail to generate while "
"shrinking",
[](const GenParams ¶ms) {
Bag s0;
const auto gen = state::gen::commands(
s0,
state::gen::execOneOfWithArgs<Open, Close, Add, Del, BuggyGet>());
const auto commands = findMinCommands(params, gen, s0);
const auto cmdStrings = showCommands(commands);
RC_ASSERT(cmdStrings.size() == 4U);
RC_ASSERT(cmdStrings[0] == "Open");
RC_ASSERT(cmdStrings[1] == "Add(0)");
RC_ASSERT(cmdStrings[2] == "Add(0)");
RC_ASSERT((cmdStrings[3] == "BuggyGet(0)") ||
(cmdStrings[3] == "BuggyGet(1)"));
});
prop(
"should find minimum when later commands depend on the shrunk values of "
"previous commands",
[](const GenParams ¶ms) {
Bag s0;
const auto gen = state::gen::commands(
s0,
state::gen::
execOneOfWithArgs<Open, Close, Add, Del, BuggyDelAll>());
const auto commands = findMinCommands(params, gen, s0);
const auto cmdStrings = showCommands(commands);
std::vector<std::string> expected{"Open", "Add(0)", "BuggyDelAll(0)"};
RC_ASSERT(cmdStrings == expected);
});
prop(
"should find minimum when later commands depend on the specific values "
"of previous commands",
[](const GenParams ¶ms) {
Bag s0;
const auto gen = state::gen::commands(
s0,
state::gen::
execOneOfWithArgs<Open, Close, Add, Del, SneakyBuggyGet>());
const auto commands = findMinCommands(params, gen, s0);
const auto cmdStrings = showCommands(commands);
std::vector<std::string> expected{
"Open", "Add(2)", "SneakyBuggyGet(2)"};
RC_ASSERT(cmdStrings == expected);
});
}
| 29.285068
| 79
| 0.599197
|
XzoRit
|
448974faa03164e424ded9451b92a2d0f1423ab7
| 10,608
|
hpp
|
C++
|
source/Leaderboard.hpp
|
acodcha/catan-stratification
|
12c45cbf0f97727cc1c8d8c243ce5d0f2468843b
|
[
"MIT"
] | 1
|
2020-10-07T01:03:32.000Z
|
2020-10-07T01:03:32.000Z
|
source/Leaderboard.hpp
|
acodcha/catan-stratification
|
12c45cbf0f97727cc1c8d8c243ce5d0f2468843b
|
[
"MIT"
] | null | null | null |
source/Leaderboard.hpp
|
acodcha/catan-stratification
|
12c45cbf0f97727cc1c8d8c243ce5d0f2468843b
|
[
"MIT"
] | 1
|
2021-09-22T03:02:41.000Z
|
2021-09-22T03:02:41.000Z
|
#pragma once
#include "DataFileWriter.hpp"
#include "GlobalAveragePointsGnuplotFileWriter.hpp"
#include "GlobalEloRatingGnuplotFileWriter.hpp"
#include "GlobalPlacePercentageGnuplotFileWriter.hpp"
#include "IndividualAveragePointsGnuplotFileWriter.hpp"
#include "IndividualEloRatingGnuplotFileWriter.hpp"
#include "IndividualPlacePercentageGnuplotFileWriter.hpp"
#include "LeaderboardGlobalFileWriter.hpp"
#include "LeaderboardIndividualFileWriter.hpp"
namespace CatanRanker {
/// \brief Class that writes all leaderboard files given games and players data.
class Leaderboard {
public:
Leaderboard(const std::experimental::filesystem::path& base_directory, const Games& games, const Players& players) {
if (!base_directory.empty()) {
create_directories(base_directory, players);
write_data_files(base_directory, players);
write_global_gnuplot_files(base_directory, players);
write_player_gnuplot_files(base_directory, players);
write_global_leaderboard_file(base_directory, games, players);
write_player_leaderboard_files(base_directory, games, players);
generate_global_plots(base_directory);
generate_player_plots(base_directory, players);
}
}
protected:
void create_directories(const std::experimental::filesystem::path& base_directory, const Players& players) {
create(base_directory);
create(base_directory / Path::PlayersDirectoryName);
create(base_directory / Path::MainPlotsDirectoryName);
for (const Player& player : players) {
create(base_directory / player.name().directory_name());
create(base_directory / player.name().directory_name() / Path::PlayerDataDirectoryName);
create(base_directory / player.name().directory_name() / Path::PlayerPlotsDirectoryName);
}
}
void write_data_files(const std::experimental::filesystem::path& base_directory, const Players& players) noexcept {
for (const Player& player : players) {
for (const GameCategory game_category : GameCategories) {
if (!player[game_category].empty()) {
DataFileWriter{
base_directory / player.name().directory_name() / Path::PlayerDataDirectoryName / Path::player_data_file_name(game_category),
player_table(player, game_category)
};
}
}
}
message("Wrote the data files.");
}
void write_global_gnuplot_files(const std::experimental::filesystem::path& base_directory, const Players& players) noexcept {
for (const GameCategory game_category : GameCategories) {
std::map<PlayerName, std::experimental::filesystem::path, PlayerName::sort> data_paths;
for (const Player& player : players) {
if (!player[game_category].empty() && !player.color().empty()) {
data_paths.insert({
player.name(),
base_directory / player.name().directory_name() / Path::PlayerDataDirectoryName / Path::player_data_file_name(game_category)
});
}
}
if (!data_paths.empty()) {
GlobalEloRatingVsGameNumberGnuplotFileWriter{
base_directory / Path::MainPlotsDirectoryName / Path::global_elo_rating_vs_game_number_file_name(game_category),
players, data_paths, game_category
};
GlobalAveragePointsVsGameNumberGnuplotFileWriter{
base_directory / Path::MainPlotsDirectoryName / Path::global_average_points_vs_game_number_file_name(game_category),
players, data_paths
};
GlobalPlacePercentageVsGameNumberGnuplotFileWriter{
base_directory / Path::MainPlotsDirectoryName / Path::global_place_percentage_vs_game_number_file_name(game_category, {1}),
players, data_paths, game_category, {1}
};
}
}
message("Wrote the global Gnuplot files.");
}
void write_player_gnuplot_files(const std::experimental::filesystem::path& base_directory, const Players& players) noexcept {
for (const Player& player : players) {
std::map<GameCategory, std::experimental::filesystem::path> data_paths;
for (const GameCategory game_category : GameCategories) {
// Only generate a plot if this player has at least 2 games in this game category.
if (player[game_category].size() >= 2) {
data_paths.insert({
game_category,
base_directory / player.name().directory_name() / Path::PlayerDataDirectoryName / Path::player_data_file_name(game_category)
});
}
}
if (!data_paths.empty()) {
IndividualEloRatingVsGameNumberGnuplotFileWriter{
base_directory / player.name().directory_name() / Path::PlayerPlotsDirectoryName / Path::PlayerEloRatingVsGameNumberFileName,
data_paths, player.lowest_elo_rating(), player.highest_elo_rating()
};
IndividualAveragePointsVsGameNumberGnuplotFileWriter{
base_directory / player.name().directory_name() / Path::PlayerPlotsDirectoryName / Path::PlayerAveragePointsVsGameNumberFileName,
data_paths
};
}
if (player[GameCategory::AnyNumberOfPlayers].size() >= 2) {
IndividualPlacePercentageVsGameNumberGnuplotFileWriter{
base_directory / player.name().directory_name() / Path::PlayerPlotsDirectoryName / Path::individual_place_percentage_vs_game_number_file_name(GameCategory::AnyNumberOfPlayers),
base_directory / player.name().directory_name() / Path::PlayerDataDirectoryName / Path::player_data_file_name(GameCategory::AnyNumberOfPlayers),
GameCategory::AnyNumberOfPlayers
};
}
}
message("Wrote the individual player Gnuplot files.");
}
void write_global_leaderboard_file(const std::experimental::filesystem::path& base_directory, const Games& games, const Players& players) noexcept {
LeaderboardGlobalFileWriter{base_directory, games, players};
message("Wrote the global leaderboard Markdown file.");
}
void write_player_leaderboard_files(const std::experimental::filesystem::path& base_directory, const Games& games, const Players& players) noexcept {
for (const Player& player : players) {
LeaderboardIndividualFileWriter{base_directory, games, player};
}
message("Wrote the individual player leaderboard Markdown files.");
}
void generate_global_plots(const std::experimental::filesystem::path& base_directory) const {
message("Generating the global plots...");
for (const GameCategory game_category : GameCategories) {
generate_plot(base_directory / Path::MainPlotsDirectoryName / Path::global_elo_rating_vs_game_number_file_name(game_category));
generate_plot(base_directory / Path::MainPlotsDirectoryName / Path::global_average_points_vs_game_number_file_name(game_category));
for (const Place& place : PlacesFirstSecondThird) {
generate_plot(base_directory / Path::MainPlotsDirectoryName / Path::global_place_percentage_vs_game_number_file_name(game_category, place));
}
}
message("Generated the global plots.");
}
void generate_player_plots(const std::experimental::filesystem::path& base_directory, const Players& players) const {
message("Generating the individual player plots...");
for (const Player& player : players) {
generate_plot(base_directory / player.name().directory_name() / Path::PlayerPlotsDirectoryName / Path::PlayerAveragePointsVsGameNumberFileName);
generate_plot(base_directory / player.name().directory_name() / Path::PlayerPlotsDirectoryName / Path::PlayerEloRatingVsGameNumberFileName);
for (const GameCategory game_category : GameCategories) {
generate_plot(base_directory / player.name().directory_name() / Path::PlayerPlotsDirectoryName / Path::individual_place_percentage_vs_game_number_file_name(game_category));
}
}
message("Generated the individual player plots.");
}
/// \brief Generate a plot using Gnuplot. If the path points to a file that does not exist, no plot is generated.
void generate_plot(const std::experimental::filesystem::path& path) const {
if (std::experimental::filesystem::exists(path)) {
const std::string command{"gnuplot " + path.string()};
const int outcome{std::system(command.c_str())};
if (outcome != 0) {
error("Could not run the command: " + command);
}
}
}
Table player_table(const Player& player, const GameCategory game_category) const noexcept {
Column game_number{"Game#"};
Column game_category_game_number{"GameCategory#"};
Column player_game_number{"PlayerGame#"};
Column player_game_category_game_number{"PlayerCategoryGame#"};
Column date{"Date"};
Column average_elo_rating{"AvgRating"};
Column elo_rating{"CurrentRating"};
Column average_points_per_game{"AvgPoints"};
Column first_place_percentage{"1stPlace%"};
Column second_place_percentage{"2ndPlace%"};
Column third_place_percentage{"3rdPlace%"};
Column first_or_second_place_percentage{"1stOr2ndPlace%"};
Column first_or_second_or_third_place_percentage{"1stOr2ndOr3rdPlace%"};
if (!player[game_category].empty()) {
for (const PlayerProperties& properties : player[game_category]) {
game_number.add_row(properties.game_number());
game_category_game_number.add_row(properties.game_category_game_number());
player_game_number.add_row(properties.player_game_number());
player_game_category_game_number.add_row(properties.player_game_category_game_number());
date.add_row(properties.date());
average_elo_rating.add_row(properties.average_elo_rating());
elo_rating.add_row(properties.elo_rating());
average_points_per_game.add_row(properties.average_points_per_game(), 7);
first_place_percentage.add_row(properties.place_percentage({1}), 5);
second_place_percentage.add_row(properties.place_percentage({2}), 5);
third_place_percentage.add_row(properties.place_percentage({3}), 5);
first_or_second_place_percentage.add_row(properties.place_percentage({1}) + properties.place_percentage({2}), 5);
first_or_second_or_third_place_percentage.add_row(properties.place_percentage({1}) + properties.place_percentage({2}) + properties.place_percentage({3}), 5);
}
}
return {{game_number, game_category_game_number, player_game_number, player_game_category_game_number, date, average_elo_rating, elo_rating, average_points_per_game, first_place_percentage, second_place_percentage, third_place_percentage, first_or_second_place_percentage, first_or_second_or_third_place_percentage}};
}
};
} // namespace CatanRanker
| 51.495146
| 321
| 0.737651
|
acodcha
|
44899f636f113100199f92c07fd982e9ff82d266
| 2,160
|
cpp
|
C++
|
src/energy/soft_volume_constraint.cpp
|
Conrekatsu/repulsive-surfaces
|
74d6a16e6ca55c8296fa5a49757c2318bea62a84
|
[
"MIT"
] | 35
|
2021-12-13T09:58:08.000Z
|
2022-03-30T11:03:01.000Z
|
src/energy/soft_volume_constraint.cpp
|
Conrekatsu/repulsive-surfaces
|
74d6a16e6ca55c8296fa5a49757c2318bea62a84
|
[
"MIT"
] | null | null | null |
src/energy/soft_volume_constraint.cpp
|
Conrekatsu/repulsive-surfaces
|
74d6a16e6ca55c8296fa5a49757c2318bea62a84
|
[
"MIT"
] | 3
|
2022-02-25T06:46:34.000Z
|
2022-03-16T05:46:53.000Z
|
#include "energy/soft_volume_constraint.h"
#include "matrix_utils.h"
#include "surface_derivatives.h"
namespace rsurfaces
{
SoftVolumeConstraint::SoftVolumeConstraint(MeshPtr mesh_, GeomPtr geom_, double weight_)
{
mesh = mesh_;
geom = geom_;
weight = weight_;
initialVolume = totalVolume(geom, mesh);
}
inline double volumeDeviation(MeshPtr mesh, GeomPtr geom, double initialValue)
{
return (totalVolume(geom, mesh) - initialValue) / initialValue;
}
// Returns the current value of the energy.
double SoftVolumeConstraint::Value()
{
double volDev = volumeDeviation(mesh, geom, initialVolume);
return weight * (volDev * volDev);
}
// Returns the current differential of the energy, stored in the given
// V x 3 matrix, where each row holds the differential (a 3-vector) with
// respect to the corresponding vertex.
void SoftVolumeConstraint::Differential(Eigen::MatrixXd &output)
{
double volDev = volumeDeviation(mesh, geom, initialVolume);
VertexIndices inds = mesh->getVertexIndices();
for (size_t i = 0; i < mesh->nVertices(); i++)
{
GCVertex v_i = mesh->vertex(i);
// Derivative of local volume is just the area weighted normal
Vector3 deriv_v = areaWeightedNormal(geom, v_i);
// Derivative of V^2 = 2 V (dV/dx)
deriv_v = 2 * volDev * deriv_v / initialVolume;
MatrixUtils::addToRow(output, inds[v_i], weight * deriv_v);
}
}
// Get the exponents of this energy; only applies to tangent-point energies.
Vector2 SoftVolumeConstraint::GetExponents()
{
return Vector2{1, 0};
}
// Get a pointer to the current BVH for this energy.
// Return 0 if the energy doesn't use a BVH.
OptimizedClusterTree *SoftVolumeConstraint::GetBVH()
{
return 0;
}
// Return the separation parameter for this energy.
// Return 0 if this energy doesn't do hierarchical approximation.
double SoftVolumeConstraint::GetTheta()
{
return 0;
}
} // namespace rsurfaces
| 32.238806
| 92
| 0.647222
|
Conrekatsu
|
448bc7db01bcfd3c2d5c1a5c6fcb052917d460a5
| 5,934
|
cpp
|
C++
|
src/planner/Query.cpp
|
yixinglu/nebula-graph
|
faf9cd44d818b953da98b5c922999560c89867bd
|
[
"Apache-2.0"
] | 1
|
2021-08-23T05:55:55.000Z
|
2021-08-23T05:55:55.000Z
|
src/planner/Query.cpp
|
yixinglu/nebula-graph
|
faf9cd44d818b953da98b5c922999560c89867bd
|
[
"Apache-2.0"
] | null | null | null |
src/planner/Query.cpp
|
yixinglu/nebula-graph
|
faf9cd44d818b953da98b5c922999560c89867bd
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "planner/Query.h"
#include <folly/String.h>
#include "common/interface/gen-cpp2/graph_types.h"
#include "util/ToJson.h"
using folly::stringPrintf;
namespace nebula {
namespace graph {
std::unique_ptr<cpp2::PlanNodeDescription> Explore::explain() const {
auto desc = SingleInputNode::explain();
addDescription("space", folly::to<std::string>(space_), desc.get());
addDescription("dedup", util::toJson(dedup_), desc.get());
addDescription("limit", folly::to<std::string>(limit_), desc.get());
auto filter = filter_.empty() ? filter_ : Expression::decode(filter_)->toString();
addDescription("filter", filter, desc.get());
addDescription("orderBy", folly::toJson(util::toJson(orderBy_)), desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> GetNeighbors::explain() const {
auto desc = Explore::explain();
addDescription("src", src_ ? src_->toString() : "", desc.get());
addDescription("edgeTypes", folly::toJson(util::toJson(edgeTypes_)), desc.get());
addDescription("edgeDirection",
storage::cpp2::_EdgeDirection_VALUES_TO_NAMES.at(edgeDirection_),
desc.get());
addDescription(
"vertexProps", vertexProps_ ? folly::toJson(util::toJson(*vertexProps_)) : "", desc.get());
addDescription(
"edgeProps", edgeProps_ ? folly::toJson(util::toJson(*edgeProps_)) : "", desc.get());
addDescription(
"statProps", statProps_ ? folly::toJson(util::toJson(*statProps_)) : "", desc.get());
addDescription("exprs", exprs_ ? folly::toJson(util::toJson(*exprs_)) : "", desc.get());
addDescription("random", util::toJson(random_), desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> GetVertices::explain() const {
auto desc = Explore::explain();
addDescription("src", src_ ? src_->toString() : "", desc.get());
addDescription("props", folly::toJson(util::toJson(props_)), desc.get());
addDescription("exprs", folly::toJson(util::toJson(exprs_)), desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> GetEdges::explain() const {
auto desc = Explore::explain();
addDescription("src", src_ ? src_->toString() : "", desc.get());
addDescription("type", util::toJson(type_), desc.get());
addDescription("ranking", ranking_ ? ranking_->toString() : "", desc.get());
addDescription("dst", dst_ ? dst_->toString() : "", desc.get());
addDescription("props", folly::toJson(util::toJson(props_)), desc.get());
addDescription("exprs", folly::toJson(util::toJson(exprs_)), desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> IndexScan::explain() const {
auto desc = Explore::explain();
// TODO
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> Filter::explain() const {
auto desc = SingleInputNode::explain();
addDescription("condition", condition_ ? condition_->toString() : "", desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> Project::explain() const {
auto desc = SingleInputNode::explain();
addDescription("columns", cols_ ? cols_->toString() : "", desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> Sort::explain() const {
auto desc = SingleInputNode::explain();
addDescription("factors", folly::toJson(util::toJson(factors_)), desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> Limit::explain() const {
auto desc = SingleInputNode::explain();
addDescription("offset", folly::to<std::string>(offset_), desc.get());
addDescription("count", folly::to<std::string>(count_), desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> Aggregate::explain() const {
auto desc = SingleInputNode::explain();
addDescription("groupKeys", folly::toJson(util::toJson(groupKeys_)), desc.get());
folly::dynamic itemArr = folly::dynamic::array();
for (const auto &item : groupItems_) {
folly::dynamic itemObj = folly::dynamic::object();
itemObj.insert("distinct", util::toJson(item.distinct));
itemObj.insert("funcType", static_cast<uint8_t>(item.func));
itemObj.insert("expr", item.expr ? item.expr->toString() : "");
itemArr.push_back(itemObj);
}
addDescription("groupItems", folly::toJson(itemArr), desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> SwitchSpace::explain() const {
auto desc = SingleInputNode::explain();
addDescription("space", spaceName_, desc.get());
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> DataCollect::explain() const {
auto desc = SingleDependencyNode::explain();
addDescription("inputVars", folly::toJson(util::toJson(inputVars_)), desc.get());
switch (collectKind_) {
case CollectKind::kSubgraph: {
addDescription("kind", "subgraph", desc.get());
break;
}
case CollectKind::kRowBasedMove: {
addDescription("kind", "row", desc.get());
break;
}
case CollectKind::kMToN: {
addDescription("kind", "m to n", desc.get());
break;
}
}
return desc;
}
std::unique_ptr<cpp2::PlanNodeDescription> DataJoin::explain() const {
auto desc = SingleDependencyNode::explain();
addDescription("leftVar", folly::toJson(util::toJson(leftVar_)), desc.get());
addDescription("rightVar", folly::toJson(util::toJson(rightVar_)), desc.get());
addDescription("hashKeys", folly::toJson(util::toJson(hashKeys_)), desc.get());
addDescription("probeKeys", folly::toJson(util::toJson(probeKeys_)), desc.get());
return desc;
}
} // namespace graph
} // namespace nebula
| 39.825503
| 99
| 0.663128
|
yixinglu
|
448f176819f901ec6ed652d795b5faf80dd21c2f
| 1,312
|
cpp
|
C++
|
MMOCoreORB/src/server/zone/objects/creature/ai/variables/CreatureTemplateReference.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 18
|
2017-02-09T15:36:05.000Z
|
2021-12-21T04:22:15.000Z
|
MMOCoreORB/src/server/zone/objects/creature/ai/variables/CreatureTemplateReference.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 61
|
2016-12-30T21:51:10.000Z
|
2021-12-10T20:25:56.000Z
|
MMOCoreORB/src/server/zone/objects/creature/ai/variables/CreatureTemplateReference.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 71
|
2017-01-01T05:34:38.000Z
|
2022-03-29T01:04:00.000Z
|
/*
* CreatureTemplateReference.cpp
*
* Created on: 29/04/2012
* Author: victor
*/
#include "CreatureTemplateReference.h"
#include "server/zone/managers/creature/CreatureTemplateManager.h"
bool CreatureTemplateReference::toBinaryStream(ObjectOutputStream* stream) {
#ifdef ODB_SERIALIZATION
templateString.toBinaryStream(stream);
#else
CreatureTemplate* obj = get();
if (obj != nullptr) {
obj->getTemplateName().toBinaryStream(stream);
} else
stream->writeShort(0);
#endif
return true;
}
bool CreatureTemplateReference::parseFromBinaryStream(ObjectInputStream* stream) {
#ifdef ODB_SERIALIZATION
templateString.parseFromBinaryStream(stream);
return true;
#else
String templateName;
templateName.parseFromBinaryStream(stream);
CreatureTemplate* obj = CreatureTemplateManager::instance()->getTemplate(templateName);
if (obj != nullptr) {
updateObject(obj);
return true;
}
updateObject(obj);
return false;
#endif
}
CreatureTemplate* CreatureTemplateReference::operator=(CreatureTemplate* obj) {
updateObject(obj);
return obj;
}
void to_json(nlohmann::json& j, const CreatureTemplateReference& r) {
#ifdef ODB_SERIALIZATION
j = r.templateString;
#else
CreatureTemplate* obj = r.get();
if (obj != nullptr) {
j = obj->getTemplateName();
} else
j = "";
#endif
}
| 19.58209
| 88
| 0.749238
|
V-Fib
|
4494ba2054004393acc4da4168c1d9dbaa900028
| 8,034
|
cpp
|
C++
|
test/test_split.cpp
|
ShotaAk/rcutils
|
308663f1582c4e3a9b170d9ed413f76f368ed1c1
|
[
"Apache-2.0"
] | null | null | null |
test/test_split.cpp
|
ShotaAk/rcutils
|
308663f1582c4e3a9b170d9ed413f76f368ed1c1
|
[
"Apache-2.0"
] | 2
|
2020-04-08T08:42:06.000Z
|
2020-04-08T09:36:52.000Z
|
test/test_split.cpp
|
ShotaAk/rcutils
|
308663f1582c4e3a9b170d9ed413f76f368ed1c1
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2017 Open Source Robotics Foundation, 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.
#include "gtest/gtest.h"
#include "./allocator_testing_utils.h"
#include "rcutils/error_handling.h"
#include "rcutils/split.h"
#include "rcutils/types/string_array.h"
#define ENABLE_LOGGING 1
#if ENABLE_LOGGING
#define LOG(expected, actual) { \
printf("Expected: %s Actual: %s\n", expected, actual);}
#else
#define LOG(X, arg) {}
#endif
rcutils_string_array_t test_split(const char * str, char delimiter, size_t expected_token_size)
{
rcutils_string_array_t tokens = rcutils_get_zero_initialized_string_array();
rcutils_ret_t ret = rcutils_split(
str, delimiter, rcutils_get_default_allocator(), &tokens);
EXPECT_EQ(RCUTILS_RET_OK, ret);
fprintf(stderr, "Received %zu tokens\n", tokens.size);
EXPECT_EQ(expected_token_size, tokens.size);
for (size_t i = 0; i < tokens.size; ++i) {
EXPECT_NE((size_t)0, strlen(tokens.data[i]));
}
return tokens;
}
rcutils_string_array_t test_split_last(
const char * str, char delimiter, size_t expected_token_size)
{
rcutils_string_array_t tokens = rcutils_get_zero_initialized_string_array();
rcutils_ret_t ret = rcutils_split_last(
str, delimiter, rcutils_get_default_allocator(), &tokens);
EXPECT_EQ(RCUTILS_RET_OK, ret);
EXPECT_EQ(expected_token_size, tokens.size);
for (size_t i = 0; i < tokens.size; ++i) {
EXPECT_NE((size_t)0, strlen(tokens.data[i]));
}
return tokens;
}
TEST(test_split, split) {
rcutils_ret_t ret = RCUTILS_RET_OK;
rcutils_string_array_t tokens_fail;
EXPECT_EQ(
RCUTILS_RET_INVALID_ARGUMENT,
rcutils_split("Test", '/', rcutils_get_default_allocator(), NULL));
EXPECT_EQ(
RCUTILS_RET_ERROR,
rcutils_split("Test", '/', get_failing_allocator(), &tokens_fail));
rcutils_string_array_t tokens0 = test_split("", '/', 0);
ret = rcutils_string_array_fini(&tokens0);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens00 = test_split(NULL, '/', 0);
ret = rcutils_string_array_fini(&tokens00);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens1 = test_split("hello_world", '/', 1);
EXPECT_STREQ("hello_world", tokens1.data[0]);
ret = rcutils_string_array_fini(&tokens1);
ASSERT_EQ(RCUTILS_RET_OK, ret) << rcutils_get_error_string().str;
rcutils_string_array_t tokens2 = test_split("hello/world", '/', 2);
EXPECT_STREQ("hello", tokens2.data[0]);
EXPECT_STREQ("world", tokens2.data[1]);
ret = rcutils_string_array_fini(&tokens2);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens3 = test_split("/hello/world", '/', 2);
EXPECT_STREQ("hello", tokens3.data[0]);
EXPECT_STREQ("world", tokens3.data[1]);
ret = rcutils_string_array_fini(&tokens3);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens4 = test_split("hello/world/", '/', 2);
EXPECT_STREQ("hello", tokens4.data[0]);
EXPECT_STREQ("world", tokens4.data[1]);
ret = rcutils_string_array_fini(&tokens4);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens5 = test_split("hello//world", '/', 2);
EXPECT_STREQ("hello", tokens5.data[0]);
EXPECT_STREQ("world", tokens5.data[1]);
ret = rcutils_string_array_fini(&tokens5);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens6 = test_split("/hello//world", '/', 2);
EXPECT_STREQ("hello", tokens6.data[0]);
EXPECT_STREQ("world", tokens6.data[1]);
ret = rcutils_string_array_fini(&tokens6);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens7 = test_split("my/hello/world", '/', 3);
EXPECT_STREQ("my", tokens7.data[0]);
EXPECT_STREQ("hello", tokens7.data[1]);
EXPECT_STREQ("world", tokens7.data[2]);
ret = rcutils_string_array_fini(&tokens7);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens8 = test_split("/my/hello/world", '/', 3);
EXPECT_STREQ("my", tokens8.data[0]);
EXPECT_STREQ("hello", tokens8.data[1]);
EXPECT_STREQ("world", tokens8.data[2]);
ret = rcutils_string_array_fini(&tokens8);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens9 = test_split("/my/hello/world/", '/', 3);
EXPECT_STREQ("my", tokens9.data[0]);
EXPECT_STREQ("hello", tokens9.data[1]);
EXPECT_STREQ("world", tokens9.data[2]);
ret = rcutils_string_array_fini(&tokens9);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens10 = test_split("/my//hello//world//", '/', 3);
EXPECT_STREQ("my", tokens10.data[0]);
EXPECT_STREQ("hello", tokens10.data[1]);
EXPECT_STREQ("world", tokens10.data[2]);
ret = rcutils_string_array_fini(&tokens10);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens11 = test_split("///my//hello//world/////", '/', 3);
EXPECT_STREQ("my", tokens11.data[0]);
EXPECT_STREQ("hello", tokens11.data[1]);
EXPECT_STREQ("world", tokens11.data[2]);
ret = rcutils_string_array_fini(&tokens11);
ASSERT_EQ(RCUTILS_RET_OK, ret);
}
TEST(test_split, split_last) {
rcutils_ret_t ret = RCUTILS_RET_OK;
rcutils_string_array_t tokens_fail;
EXPECT_EQ(
RCUTILS_RET_BAD_ALLOC,
rcutils_split_last("Test", '/', get_failing_allocator(), &tokens_fail));
rcutils_string_array_t tokens0 = test_split_last("", '/', 0);
ret = rcutils_string_array_fini(&tokens0);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens00 = test_split_last(NULL, '/', 0);
ret = rcutils_string_array_fini(&tokens00);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens1 = test_split_last("hello_world", '/', 1);
LOG("hello_world", tokens1.data[0]);
EXPECT_STREQ("hello_world", tokens1.data[0]);
ret = rcutils_string_array_fini(&tokens1);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens2 = test_split_last("hello/world", '/', 2);
EXPECT_STREQ("hello", tokens2.data[0]);
LOG("hello", tokens2.data[0]);
EXPECT_STREQ("world", tokens2.data[1]);
LOG("world", tokens2.data[1]);
ret = rcutils_string_array_fini(&tokens2);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens3 = test_split_last("/hello/world", '/', 2);
EXPECT_STREQ("hello", tokens3.data[0]);
LOG("hello", tokens3.data[0]);
EXPECT_STREQ("world", tokens3.data[1]);
ret = rcutils_string_array_fini(&tokens3);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens4 = test_split_last("hello/world/", '/', 2);
EXPECT_STREQ("hello", tokens4.data[0]);
EXPECT_STREQ("world", tokens4.data[1]);
ret = rcutils_string_array_fini(&tokens4);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens5 = test_split_last("hello//world/", '/', 2);
EXPECT_STREQ("hello", tokens5.data[0]);
LOG("hello", tokens5.data[0]);
EXPECT_STREQ("world", tokens5.data[1]);
LOG("world", tokens5.data[1]);
ret = rcutils_string_array_fini(&tokens5);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens6 = test_split_last("/hello//world", '/', 2);
EXPECT_STREQ("hello", tokens6.data[0]);
EXPECT_STREQ("world", tokens6.data[1]);
ret = rcutils_string_array_fini(&tokens6);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens7 = test_split_last("my/hello//world", '/', 2);
EXPECT_STREQ("my/hello", tokens7.data[0]);
EXPECT_STREQ("world", tokens7.data[1]);
ret = rcutils_string_array_fini(&tokens7);
ASSERT_EQ(RCUTILS_RET_OK, ret);
rcutils_string_array_t tokens8 = test_split_last("/my/hello//world/", '/', 2);
EXPECT_STREQ("my/hello", tokens8.data[0]);
EXPECT_STREQ("world", tokens8.data[1]);
ret = rcutils_string_array_fini(&tokens8);
ASSERT_EQ(RCUTILS_RET_OK, ret);
}
| 37.023041
| 95
| 0.726413
|
ShotaAk
|
449594da108811f393c3c76f017cb3d93176f619
| 4,594
|
cpp
|
C++
|
isis/src/kaguya/objs/KaguyaMiCamera/KaguyaMiCamera.cpp
|
ihumphrey-usgs/ISIS3_old
|
284cc442b773f8369d44379ee29a9b46961d8108
|
[
"Unlicense"
] | 1
|
2019-10-13T15:31:33.000Z
|
2019-10-13T15:31:33.000Z
|
isis/src/kaguya/objs/KaguyaMiCamera/KaguyaMiCamera.cpp
|
ihumphrey-usgs/ISIS3_old
|
284cc442b773f8369d44379ee29a9b46961d8108
|
[
"Unlicense"
] | null | null | null |
isis/src/kaguya/objs/KaguyaMiCamera/KaguyaMiCamera.cpp
|
ihumphrey-usgs/ISIS3_old
|
284cc442b773f8369d44379ee29a9b46961d8108
|
[
"Unlicense"
] | 1
|
2021-07-12T06:05:03.000Z
|
2021-07-12T06:05:03.000Z
|
/**
* @file
*
* Unless noted otherwise, the portions of Isis written by the USGS are public
* domain. See individual third-party library and package descriptions for
* intellectual property information,user agreements, and related information.
*
* Although Isis has been used by the USGS, no warranty, expressed or implied,
* is made by the USGS as to the accuracy and functioning of such software
* and related material nor shall the fact of distribution constitute any such
* warranty, and no responsibility is assumed by the USGS in connection
* therewith.
*
* For additional information, launch
* $ISISROOT/doc//documents/Disclaimers/Disclaimers.html in a browser or see
* the Privacy & Disclaimers page on the Isis website,
* http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
* http://www.usgs.gov/privacy.html.
*/
#include "KaguyaMiCamera.h"
#include <iomanip>
#include <QString>
#include "CameraFocalPlaneMap.h"
#include "IException.h"
#include "IString.h"
#include "iTime.h"
#include "LineScanCameraDetectorMap.h"
#include "LineScanCameraGroundMap.h"
#include "LineScanCameraSkyMap.h"
#include "KaguyaMiCameraDistortionMap.h"
#include "NaifStatus.h"
using namespace std;
namespace Isis {
/**
* Constructor for the Kaguya MI Camera Model
*
* @param lab Pvl Label to create the camera model from
*
* @internal
* @history 2012-06-14 Orrin Thomas - original version
*/
KaguyaMiCamera::KaguyaMiCamera(Cube &cube) : LineScanCamera(cube) {
m_spacecraftNameLong = "Kaguya";
m_spacecraftNameShort = "Kaguya";
int ikCode = naifIkCode();
// https://darts.isas.jaxa.jp/pub/spice/SELENE/kernels/ik/SEL_MI_V01.TI
// MI-VIS instrument kernel codes -131331 through -131335
if (ikCode <= -131331 && ikCode >= -131335) {
m_instrumentNameLong = "Multi Band Imager Visible";
m_instrumentNameShort = "MI-VIS";
}
// MI-NIR instrument kernel codes -131341 through -131344
else if (ikCode <= -131341 && ikCode >= -131344) {
m_instrumentNameLong = "Multi Band Imager Infrared";
m_instrumentNameShort = "MI-NIR";
}
else {
QString msg = QString::number(ikCode);
msg += " is not a supported instrument kernel code for Kaguya.";
throw IException(IException::Programmer, msg, _FILEINFO_);
}
NaifStatus::CheckErrors();
// Set up the camera info from ik/iak kernels
SetFocalLength();
//Kaguya IK kernal uses INS-131???_PIXEL_SIZE instead of PIXEL_PITCH
QString ikernKey = "INS" + toString(naifIkCode()) + "_PIXEL_SIZE";
SetPixelPitch(getDouble(ikernKey));
// Get the start time from labels
Pvl &lab = *cube.label();
PvlGroup &inst = lab.findGroup("Instrument", Pvl::Traverse);
QString stime = (QString)inst["StartTime"];
SpiceDouble etStart=0;
if(stime != "NULL") {
etStart = iTime(stime).Et();
}
else {
//TODO throw an error if "StartTime" keyword is absent
}
NaifStatus::CheckErrors();
// Get other info from labels
double lineRate = (double) inst["CorrectedSamplingInterval"] / 1000.0;
setTime(etStart);
// Setup detector map
LineScanCameraDetectorMap *detectorMap = new LineScanCameraDetectorMap(this, etStart, lineRate);
detectorMap->SetDetectorSampleSumming(1.0);
detectorMap->SetStartingDetectorSample(1.0);
// Setup focal plane map
CameraFocalPlaneMap *focalMap = new CameraFocalPlaneMap(this, naifIkCode());
// Retrieve boresight location from instrument kernel (IK) (addendum?)
ikernKey = "INS" + toString(naifIkCode()) + "_CENTER";
double sampleBoreSight = getDouble(ikernKey,0);
double lineBoreSight = getDouble(ikernKey,1)-1.0;
focalMap->SetDetectorOrigin(sampleBoreSight, lineBoreSight);
focalMap->SetDetectorOffset(0.0, 0.0);
KaguyaMiCameraDistortionMap *distMap = new KaguyaMiCameraDistortionMap(this);
//LroNarrowAngleDistortionMap *distMap = new LroNarrowAngleDistortionMap(this);
distMap->SetDistortion(naifIkCode());
// Setup the ground and sky map
new LineScanCameraGroundMap(this);
new LineScanCameraSkyMap(this);
LoadCache();
NaifStatus::CheckErrors();
}
}
/**
* This is the function that is called in order to instantiate a
* KaguyaMi object.
*
* @param lab Cube labels
*
* @return Isis::Camera* KaguyaMiCamera
* @internal
* @history 2012-06-14 Orrin Thomas - original version
*/
extern "C" Isis::Camera *KaguyaMiCameraPlugin(Isis::Cube &cube) {
return new Isis::KaguyaMiCamera(cube);
}
| 32.58156
| 100
| 0.702003
|
ihumphrey-usgs
|
4496bfac111c43a836b8eff2037fcb70f625be3a
| 2,743
|
cpp
|
C++
|
thread/appl_thread_descriptor.cpp
|
fboucher9/appl
|
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
|
[
"MIT"
] | null | null | null |
thread/appl_thread_descriptor.cpp
|
fboucher9/appl
|
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
|
[
"MIT"
] | null | null | null |
thread/appl_thread_descriptor.cpp
|
fboucher9/appl
|
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
|
[
"MIT"
] | null | null | null |
/* See LICENSE for license details */
/*
*/
#include <appl_status.h>
#include <appl_types.h>
#include <thread/appl_thread_descriptor.h>
#include <object/appl_object.h>
#include <buf/appl_buf.h>
#include <thread/appl_thread_descriptor_impl.h>
#include <heap/appl_heap_handle.h>
//
//
//
enum appl_status
appl_thread_descriptor_create(
struct appl_context * const
p_context,
struct appl_thread_descriptor * * const
r_thread_descriptor)
{
enum appl_status
e_status;
e_status =
appl_new(
p_context,
r_thread_descriptor);
return
e_status;
} // _create()
//
//
//
enum appl_status
appl_thread_descriptor_destroy(
struct appl_thread_descriptor * const
p_thread_descriptor)
{
enum appl_status
e_status;
struct appl_context * const
p_context =
p_thread_descriptor->get_context();
e_status =
appl_delete(
p_context,
p_thread_descriptor);
return
e_status;
} // _destroy()
/*
*/
void
appl_thread_descriptor_set_callback(
struct appl_thread_descriptor * const
p_thread_descriptor,
void (* const p_entry)(
void * const
p_thread_context),
void * const
p_context)
{
struct appl_thread_callback
o_callback;
o_callback.p_entry =
p_entry;
o_callback.p_context =
p_context;
p_thread_descriptor->f_set_callback(
&(
o_callback));
} /* appl_thread_descriptor_set_callback() */
//
//
//
void
appl_thread_descriptor_set_name(
struct appl_thread_descriptor * const
p_thread_descriptor,
unsigned char const * const
p_name_min,
unsigned char const * const
p_name_max)
{
struct appl_buf
o_name;
o_name.o_min.pc_uchar =
p_name_min;
o_name.o_max.pc_uchar =
p_name_max;
p_thread_descriptor->f_set_name(
&(
o_name));
} // _set_name()
//
//
//
char
appl_thread_descriptor_get_callback(
struct appl_thread_descriptor const * const
p_thread_descriptor,
struct appl_thread_callback * const
p_thread_callback)
{
return
p_thread_descriptor->f_get_callback(
p_thread_callback) ? 1 : 0;
} // _get_callback()
//
//
//
char
appl_thread_descriptor_get_name(
struct appl_thread_descriptor const * const
p_thread_descriptor,
struct appl_buf * const
p_name)
{
return
p_thread_descriptor->f_get_name(
p_name) ? 1 : 0;
} // _get_name()
/* end-of-file: appl_thread_descriptor.cpp */
| 17.471338
| 51
| 0.61502
|
fboucher9
|
44970b07e76cabf703195cc926a81dceb9e636af
| 806
|
hpp
|
C++
|
higan/gba/cartridge/cartridge.hpp
|
13824125580/higan
|
fbdd3f980b65412c362096579869ae76730e4118
|
[
"Intel",
"ISC"
] | 10
|
2019-12-19T01:19:41.000Z
|
2021-02-18T16:30:29.000Z
|
higan/gba/cartridge/cartridge.hpp
|
13824125580/higan
|
fbdd3f980b65412c362096579869ae76730e4118
|
[
"Intel",
"ISC"
] | null | null | null |
higan/gba/cartridge/cartridge.hpp
|
13824125580/higan
|
fbdd3f980b65412c362096579869ae76730e4118
|
[
"Intel",
"ISC"
] | null | null | null |
struct Cartridge {
#include "memory.hpp"
auto pathID() const -> uint { return information.pathID; }
auto hash() const -> string { return information.sha256; }
auto manifest() const -> string { return information.manifest; }
auto title() const -> string { return information.title; }
struct Information {
uint pathID = 0;
string sha256;
string manifest;
string title;
} information;
Cartridge();
~Cartridge();
auto load() -> bool;
auto save() -> void;
auto unload() -> void;
auto power() -> void;
auto read(uint mode, uint32 addr) -> uint32;
auto write(uint mode, uint32 addr, uint32 word) -> void;
auto serialize(serializer&) -> void;
private:
bool hasSRAM = false;
bool hasEEPROM = false;
bool hasFLASH = false;
};
extern Cartridge cartridge;
| 22.388889
| 66
| 0.66005
|
13824125580
|
449a467a172e2e329612297dd5855788d6efc379
| 7,518
|
cc
|
C++
|
third_party/webrtc/src/webrtc/modules/audio_coding/main/acm2/codec_owner.cc
|
bopopescu/webrtc-streaming-node
|
727a441204344ff596401b0253caac372b714d91
|
[
"MIT"
] | 8
|
2016-02-08T11:59:31.000Z
|
2020-05-31T15:19:54.000Z
|
third_party/webrtc/src/webrtc/modules/audio_coding/main/acm2/codec_owner.cc
|
bopopescu/webrtc-streaming-node
|
727a441204344ff596401b0253caac372b714d91
|
[
"MIT"
] | 1
|
2021-05-05T11:11:31.000Z
|
2021-05-05T11:11:31.000Z
|
third_party/webrtc/src/webrtc/modules/audio_coding/main/acm2/codec_owner.cc
|
bopopescu/webrtc-streaming-node
|
727a441204344ff596401b0253caac372b714d91
|
[
"MIT"
] | 7
|
2016-02-09T09:28:14.000Z
|
2020-07-25T19:03:36.000Z
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/audio_coding/main/acm2/codec_owner.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/audio_coding/codecs/cng/include/audio_encoder_cng.h"
#include "webrtc/modules/audio_coding/codecs/g711/include/audio_encoder_pcm.h"
#ifdef WEBRTC_CODEC_G722
#include "webrtc/modules/audio_coding/codecs/g722/include/audio_encoder_g722.h"
#endif
#ifdef WEBRTC_CODEC_ILBC
#include "webrtc/modules/audio_coding/codecs/ilbc/interface/audio_encoder_ilbc.h"
#endif
#ifdef WEBRTC_CODEC_ISACFX
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_decoder_isacfix.h"
#include "webrtc/modules/audio_coding/codecs/isac/fix/interface/audio_encoder_isacfix.h"
#endif
#ifdef WEBRTC_CODEC_ISAC
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_decoder_isac.h"
#include "webrtc/modules/audio_coding/codecs/isac/main/interface/audio_encoder_isac.h"
#endif
#ifdef WEBRTC_CODEC_OPUS
#include "webrtc/modules/audio_coding/codecs/opus/interface/audio_encoder_opus.h"
#endif
#include "webrtc/modules/audio_coding/codecs/pcm16b/include/audio_encoder_pcm16b.h"
#ifdef WEBRTC_CODEC_RED
#include "webrtc/modules/audio_coding/codecs/red/audio_encoder_copy_red.h"
#endif
namespace webrtc {
namespace acm2 {
CodecOwner::CodecOwner() : external_speech_encoder_(nullptr) {
}
CodecOwner::~CodecOwner() = default;
namespace {
rtc::scoped_ptr<AudioDecoder> CreateIsacDecoder(
LockedIsacBandwidthInfo* bwinfo) {
#if defined(WEBRTC_CODEC_ISACFX)
return rtc_make_scoped_ptr(new AudioDecoderIsacFix(bwinfo));
#elif defined(WEBRTC_CODEC_ISAC)
return rtc_make_scoped_ptr(new AudioDecoderIsac(bwinfo));
#else
FATAL() << "iSAC is not supported.";
return rtc::scoped_ptr<AudioDecoder>();
#endif
}
// Returns a new speech encoder, or null on error.
// TODO(kwiberg): Don't handle errors here (bug 5033)
rtc::scoped_ptr<AudioEncoder> CreateSpeechEncoder(
const CodecInst& speech_inst,
LockedIsacBandwidthInfo* bwinfo) {
#if defined(WEBRTC_CODEC_ISACFX)
if (STR_CASE_CMP(speech_inst.plname, "isac") == 0)
return rtc_make_scoped_ptr(new AudioEncoderIsacFix(speech_inst, bwinfo));
#endif
#if defined(WEBRTC_CODEC_ISAC)
if (STR_CASE_CMP(speech_inst.plname, "isac") == 0)
return rtc_make_scoped_ptr(new AudioEncoderIsac(speech_inst, bwinfo));
#endif
#ifdef WEBRTC_CODEC_OPUS
if (STR_CASE_CMP(speech_inst.plname, "opus") == 0)
return rtc_make_scoped_ptr(new AudioEncoderOpus(speech_inst));
#endif
if (STR_CASE_CMP(speech_inst.plname, "pcmu") == 0)
return rtc_make_scoped_ptr(new AudioEncoderPcmU(speech_inst));
if (STR_CASE_CMP(speech_inst.plname, "pcma") == 0)
return rtc_make_scoped_ptr(new AudioEncoderPcmA(speech_inst));
if (STR_CASE_CMP(speech_inst.plname, "l16") == 0)
return rtc_make_scoped_ptr(new AudioEncoderPcm16B(speech_inst));
#ifdef WEBRTC_CODEC_ILBC
if (STR_CASE_CMP(speech_inst.plname, "ilbc") == 0)
return rtc_make_scoped_ptr(new AudioEncoderIlbc(speech_inst));
#endif
#ifdef WEBRTC_CODEC_G722
if (STR_CASE_CMP(speech_inst.plname, "g722") == 0)
return rtc_make_scoped_ptr(new AudioEncoderG722(speech_inst));
#endif
LOG_F(LS_ERROR) << "Could not create encoder of type " << speech_inst.plname;
return rtc::scoped_ptr<AudioEncoder>();
}
AudioEncoder* CreateRedEncoder(int red_payload_type,
AudioEncoder* encoder,
rtc::scoped_ptr<AudioEncoder>* red_encoder) {
#ifdef WEBRTC_CODEC_RED
if (red_payload_type != -1) {
AudioEncoderCopyRed::Config config;
config.payload_type = red_payload_type;
config.speech_encoder = encoder;
red_encoder->reset(new AudioEncoderCopyRed(config));
return red_encoder->get();
}
#endif
red_encoder->reset();
return encoder;
}
void CreateCngEncoder(int cng_payload_type,
ACMVADMode vad_mode,
AudioEncoder* encoder,
rtc::scoped_ptr<AudioEncoder>* cng_encoder) {
if (cng_payload_type == -1) {
cng_encoder->reset();
return;
}
AudioEncoderCng::Config config;
config.num_channels = encoder->NumChannels();
config.payload_type = cng_payload_type;
config.speech_encoder = encoder;
switch (vad_mode) {
case VADNormal:
config.vad_mode = Vad::kVadNormal;
break;
case VADLowBitrate:
config.vad_mode = Vad::kVadLowBitrate;
break;
case VADAggr:
config.vad_mode = Vad::kVadAggressive;
break;
case VADVeryAggr:
config.vad_mode = Vad::kVadVeryAggressive;
break;
default:
FATAL();
}
cng_encoder->reset(new AudioEncoderCng(config));
}
} // namespace
bool CodecOwner::SetEncoders(const CodecInst& speech_inst,
int cng_payload_type,
ACMVADMode vad_mode,
int red_payload_type) {
speech_encoder_ = CreateSpeechEncoder(speech_inst, &isac_bandwidth_info_);
if (!speech_encoder_)
return false;
external_speech_encoder_ = nullptr;
ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
return true;
}
void CodecOwner::SetEncoders(AudioEncoder* external_speech_encoder,
int cng_payload_type,
ACMVADMode vad_mode,
int red_payload_type) {
external_speech_encoder_ = external_speech_encoder;
speech_encoder_.reset();
ChangeCngAndRed(cng_payload_type, vad_mode, red_payload_type);
}
void CodecOwner::ChangeCngAndRed(int cng_payload_type,
ACMVADMode vad_mode,
int red_payload_type) {
AudioEncoder* speech_encoder = SpeechEncoder();
if (cng_payload_type != -1 || red_payload_type != -1) {
// The RED and CNG encoders need to be in sync with the speech encoder, so
// reset the latter to ensure its buffer is empty.
speech_encoder->Reset();
}
AudioEncoder* encoder =
CreateRedEncoder(red_payload_type, speech_encoder, &red_encoder_);
CreateCngEncoder(cng_payload_type, vad_mode, encoder, &cng_encoder_);
RTC_DCHECK_EQ(!!speech_encoder_ + !!external_speech_encoder_, 1);
}
AudioDecoder* CodecOwner::GetIsacDecoder() {
if (!isac_decoder_)
isac_decoder_ = CreateIsacDecoder(&isac_bandwidth_info_);
return isac_decoder_.get();
}
AudioEncoder* CodecOwner::Encoder() {
const auto& const_this = *this;
return const_cast<AudioEncoder*>(const_this.Encoder());
}
const AudioEncoder* CodecOwner::Encoder() const {
if (cng_encoder_)
return cng_encoder_.get();
if (red_encoder_)
return red_encoder_.get();
return SpeechEncoder();
}
AudioEncoder* CodecOwner::SpeechEncoder() {
const auto* const_this = this;
return const_cast<AudioEncoder*>(const_this->SpeechEncoder());
}
const AudioEncoder* CodecOwner::SpeechEncoder() const {
RTC_DCHECK(!speech_encoder_ || !external_speech_encoder_);
return external_speech_encoder_ ? external_speech_encoder_
: speech_encoder_.get();
}
} // namespace acm2
} // namespace webrtc
| 35.130841
| 88
| 0.727188
|
bopopescu
|
449a6d2d1ed94330435edd5a25ba9ac3845b028c
| 2,019
|
cc
|
C++
|
l95/src/lorenz95/ObservationL95.cc
|
andreapiacentini/oops
|
48c923c210a75773e2457eea8b1a8eee29837bb5
|
[
"Apache-2.0"
] | null | null | null |
l95/src/lorenz95/ObservationL95.cc
|
andreapiacentini/oops
|
48c923c210a75773e2457eea8b1a8eee29837bb5
|
[
"Apache-2.0"
] | null | null | null |
l95/src/lorenz95/ObservationL95.cc
|
andreapiacentini/oops
|
48c923c210a75773e2457eea8b1a8eee29837bb5
|
[
"Apache-2.0"
] | null | null | null |
/*
* (C) Copyright 2009-2016 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include "lorenz95/ObservationL95.h"
#include <string>
#include <vector>
#include "eckit/config/Configuration.h"
#include "lorenz95/GomL95.h"
#include "lorenz95/LocsL95.h"
#include "lorenz95/ObsBias.h"
#include "lorenz95/ObsDiags1D.h"
#include "lorenz95/ObsVec1D.h"
#include "oops/base/Variables.h"
#include "oops/util/Logger.h"
// -----------------------------------------------------------------------------
namespace lorenz95 {
// -----------------------------------------------------------------------------
ObservationL95::ObservationL95(const ObsTable & ot, const eckit::Configuration &)
: obsdb_(ot), inputs_(std::vector<std::string>{"x"})
{}
// -----------------------------------------------------------------------------
ObservationL95::~ObservationL95() {}
// -----------------------------------------------------------------------------
void ObservationL95::simulateObs(const GomL95 & gom, ObsVec1D & ovec,
const ObsBias & bias, ObsDiags1D &) const {
for (size_t jj = 0; jj < gom.size(); ++jj) {
ovec[jj] = gom[jj] + bias.value();
}
}
// -----------------------------------------------------------------------------
std::unique_ptr<LocsL95> ObservationL95::locations() const {
return std::unique_ptr<LocsL95>(new LocsL95(obsdb_.locations(), obsdb_.times()));
}
// -----------------------------------------------------------------------------
void ObservationL95::print(std::ostream & os) const {
os << "Lorenz 95: Identity obs operator";
}
// -----------------------------------------------------------------------------
} // namespace lorenz95
| 33.098361
| 83
| 0.505201
|
andreapiacentini
|
449b75bc73a0098cc1f0cccc849e41486eabfcba
| 853
|
cpp
|
C++
|
sdk/test_hls_polling.cpp
|
zhiyb/SVM_hls
|
e1223c8528eccd8d48e52c4614c8596db4c253da
|
[
"MIT"
] | 3
|
2020-11-11T13:04:52.000Z
|
2021-03-03T06:30:18.000Z
|
sdk/test_hls_polling.cpp
|
zhiyb/SVM_hls
|
e1223c8528eccd8d48e52c4614c8596db4c253da
|
[
"MIT"
] | null | null | null |
sdk/test_hls_polling.cpp
|
zhiyb/SVM_hls
|
e1223c8528eccd8d48e52c4614c8596db4c253da
|
[
"MIT"
] | 1
|
2019-04-11T03:05:59.000Z
|
2019-04-11T03:05:59.000Z
|
#include <stdio.h>
#include <xtime_l.h>
#include "test.h"
void test_cls_hls_polling_pre()
{
// Disable interrupt
interrupt_enable(false);
}
unsigned int test_cls_hls_polling()
{
XTime tick[4], perf[3] = {0, 0, 0};
unsigned int err = 0;
int *label = &testDataLabel[0];
int16_t *x = &testDataI[0][0];
for (size_t ix = ASIZE(testDataLabel); ix != 0; ix--) {
XTime_GetTime(&tick[0]);
XClassifier_Set_x_V(&cls, *(XClassifier_X_v *)x);
XTime_GetTime(&tick[1]);
XClassifier_Start(&cls);
XTime_GetTime(&tick[2]);
while (!XClassifier_IsReady(&cls));
XTime_GetTime(&tick[3]);
err += (!XClassifier_Get_output_r(&cls)) != (!*label++);
perf[0] += tick[1] - tick[0];
perf[1] += tick[2] - tick[1];
perf[2] += tick[3] - tick[2];
x += N;
}
printf("Data %llu, starting %llu, result %llu\r\n", perf[0], perf[1], perf[2]);
return err;
}
| 25.088235
| 80
| 0.635404
|
zhiyb
|
44a4de86e7ff78b545ac8453af5ad0882b5fb51a
| 61,160
|
cpp
|
C++
|
src/sksl/SkSLLexer.cpp
|
wan-nyan-wan/skia
|
bf2a6ff1b570821a906f11a2046215789b51d41a
|
[
"BSD-3-Clause"
] | null | null | null |
src/sksl/SkSLLexer.cpp
|
wan-nyan-wan/skia
|
bf2a6ff1b570821a906f11a2046215789b51d41a
|
[
"BSD-3-Clause"
] | null | null | null |
src/sksl/SkSLLexer.cpp
|
wan-nyan-wan/skia
|
bf2a6ff1b570821a906f11a2046215789b51d41a
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*****************************************************************************************
******************** This file was generated by sksllex. Do not edit. *******************
*****************************************************************************************/
#include "src/sksl/SkSLLexer.h"
namespace SkSL {
using State = uint16_t;
static const uint8_t INVALID_CHAR = 18;
static const int8_t kMappings[127] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 4, 3, 5, 6, 7, 8, 3, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25, 26, 27, 28, 29, 30, 31,
31, 32, 33, 34, 31, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 36, 37, 35, 38, 35, 35,
39, 35, 35, 40, 3, 41, 42, 43, 3, 44, 45, 46, 47, 48, 49, 50, 51, 52, 35, 53, 54, 55,
56, 57, 58, 35, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71};
struct IndexEntry {
uint16_t type : 2;
uint16_t pos : 14;
};
struct FullEntry {
State data[72];
};
struct CompactEntry {
State v0 : 6;
State v1 : 9;
State v2 : 9;
uint8_t data[18];
};
static constexpr FullEntry kFull[] = {
{
0, 2, 3, 4, 5, 7, 9, 14, 16, 19, 20, 21, 23, 26, 27,
30, 35, 41, 60, 60, 60, 60, 60, 60, 62, 63, 64, 68, 70, 74,
75, 84, 84, 84, 84, 84, 84, 84, 84, 84, 85, 86, 87, 84, 90,
100, 105, 121, 141, 153, 169, 174, 182, 84, 206, 216, 223, 249, 254, 270,
276, 348, 365, 381, 393, 84, 84, 84, 398, 399, 402, 403,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 50, 50, 50, 50, 50, 50, 51,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 57, 58, 0, 0, 0, 0, 0, 0, 0, 0,
52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 58, 0, 0, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 50, 50, 50, 50, 50, 50, 51,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 51, 51, 51, 51, 51, 51, 51,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 0, 61, 61, 61, 61, 61, 61, 61,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 57, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57, 0, 0, 0, 0, 0, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 106, 10, 10, 10, 10, 10, 10, 10, 10, 10,
109, 10, 10, 112, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 122, 10, 10, 10, 128, 10,
10, 10, 10, 134, 10, 10, 10, 10, 10, 138, 10, 10, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
142, 10, 145, 10, 10, 10, 10, 10, 10, 10, 10, 147, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 154, 10, 10, 10, 10, 10, 10, 10, 158, 10,
161, 10, 10, 164, 10, 10, 10, 10, 10, 166, 10, 10, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
185, 10, 10, 189, 192, 10, 10, 194, 10, 200, 10, 10, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 255, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 259, 10, 10, 266, 10, 10, 10, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 277, 10, 10, 10, 10, 10, 10, 10, 309, 313,
10, 10, 10, 10, 10, 10, 10, 331, 339, 10, 343, 10, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
283, 290, 301, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 306, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 0, 0, 0, 0,
},
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10,
10, 10, 10, 10, 10, 10, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10,
10, 10, 10, 10, 0, 0, 0, 10, 10, 10, 10, 10, 349, 10, 10, 355, 10, 10,
10, 10, 10, 10, 10, 357, 10, 10, 10, 10, 10, 10, 360, 10, 0, 0, 0, 0,
},
};
static constexpr CompactEntry kCompact[] = {
{0,
0,
3,
{
60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
6,
{
0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
8,
{
0, 0, 0, 0, 0, 0, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0,
}},
{0,
0,
8,
{
0, 0, 0, 0, 252, 255, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0,
}},
{0,
10,
11,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
0,
10,
{
0, 0, 0, 0, 252, 255, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0,
}},
{0,
10,
12,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
13,
{
0, 0, 0, 0, 168, 171, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
0,
15,
{
0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
17,
18,
{
0, 0, 2, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
22,
{
0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
24,
25,
{
0, 0, 0, 2, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
28,
29,
{
0, 0, 0, 32, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
31,
{
0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
31,
32,
{
0, 0, 0, 0, 168, 170, 0, 0, 48, 0, 0, 0, 3, 0, 0, 0, 0, 0,
}},
{0,
33,
34,
{
0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
34,
{
0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{36,
39,
40,
{
0, 0, 64, 0, 2, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
36,
37,
{
168,
170,
234,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
}},
{0,
36,
38,
{
168,
170,
170,
170,
171,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
170,
}},
{0,
0,
39,
{
204,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
255,
}},
{0,
43,
47,
{
0, 0, 0, 0, 168, 170, 0, 0, 48, 0, 0, 0, 3, 0, 0, 0, 0, 0,
}},
{0,
43,
44,
{
0, 0, 0, 0, 168, 170, 0, 0, 48, 0, 0, 0, 3, 0, 0, 0, 0, 0,
}},
{0,
45,
46,
{
0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
46,
{
0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
48,
49,
{
0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
49,
{
0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
53,
54,
{
0, 0, 0, 34, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
54,
{
0, 0, 0, 0, 252, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
59,
{
0, 0, 0, 0, 252, 255, 0, 192, 63, 0, 0, 255, 15, 0, 0, 0, 0, 0,
}},
{0,
57,
59,
{
0, 0, 0, 0, 252, 255, 0, 192, 63, 32, 0, 255, 15, 0, 0, 32, 0, 0,
}},
{0,
65,
67,
{
0, 0, 0, 0, 0, 0, 224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
66,
{
0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
69,
{
0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
71,
72,
{
0, 0, 0, 0, 0, 0, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
73,
{
0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
}},
{0,
76,
78,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0,
}},
{0,
0,
77,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0,
}},
{0,
0,
79,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0,
}},
{0,
0,
80,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0,
}},
{0,
0,
81,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0,
}},
{0,
0,
82,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0,
}},
{0,
0,
83,
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0,
}},
{0,
88,
89,
{
0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0,
}},
{10,
91,
93,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 85, 94, 85, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0,
}},
{0,
10,
94,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
95,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
96,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
97,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
98,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
99,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
101,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
102,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
103,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
104,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 174, 170, 170, 170, 0,
}},
{0,
10,
107,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{10,
92,
108,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 87, 85, 85, 89, 85, 0,
}},
{0,
10,
110,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
111,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
113,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{10,
114,
116,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 85, 94, 85, 0,
}},
{0,
10,
115,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
117,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
118,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
119,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
120,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
123,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0,
}},
{0,
10,
124,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
125,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
126,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
127,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
129,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
130,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
131,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
132,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
133,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
135,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
136,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
137,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
139,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
140,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 232, 175, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
143,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
144,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
146,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
148,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
149,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
150,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
151,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
152,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
155,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
156,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
157,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
159,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 174, 0,
}},
{0,
10,
160,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
162,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
163,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
165,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
167,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
168,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{10,
170,
172,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 101, 93, 85, 85, 0,
}},
{0,
10,
171,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
0,
171,
{
0, 0, 0, 0, 252, 255, 0, 192, 255, 255, 192, 255, 255, 255, 255, 255, 255, 0,
}},
{0,
10,
173,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0,
}},
{10,
175,
179,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 86, 85, 213, 85, 0,
}},
{0,
10,
176,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 186, 170, 170, 170, 170, 0,
}},
{0,
10,
177,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0,
}},
{0,
10,
178,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
180,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
181,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{10,
183,
184,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 89, 85, 87, 85, 85, 0,
}},
{0,
10,
186,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
187,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
188,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
190,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
191,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
193,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
195,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
196,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
197,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0,
}},
{0,
10,
198,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
199,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
201,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
202,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
203,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
204,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
205,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{10,
207,
212,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 93, 85, 85, 0,
}},
{0,
10,
208,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 186, 0,
}},
{0,
10,
209,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0,
}},
{0,
10,
210,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
211,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{10,
213,
214,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 86, 85, 87, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 186, 170, 170, 170, 170, 0,
}},
{0,
10,
215,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
217,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
218,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
219,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
220,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
221,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0,
}},
{0,
10,
222,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{10,
224,
231,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 93, 85, 85, 0,
}},
{0,
10,
225,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0,
}},
{0,
10,
226,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
227,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
228,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
229,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
230,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{10,
232,
238,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 86, 117, 85, 85, 0,
}},
{0,
10,
233,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
234,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
235,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
236,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
237,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
239,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
240,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
241,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
242,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
243,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
244,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
245,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
246,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
247,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 234, 170, 0,
}},
{0,
10,
248,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
250,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
251,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
252,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
253,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
256,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
257,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 174, 170, 170, 170, 0,
}},
{0,
10,
258,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
260,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
261,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
262,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
263,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
264,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
265,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
267,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
268,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
269,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
271,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
272,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
273,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
274,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
275,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
278,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0,
}},
{0,
10,
279,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
280,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
281,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
282,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
284,
{
0, 0, 0, 0, 168, 170, 0, 128, 174, 170, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
285,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 174, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
286,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0,
}},
{0,
10,
287,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
288,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
289,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 171, 0,
}},
{0,
10,
291,
{
0, 0, 0, 0, 168, 170, 0, 128, 174, 170, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{10,
285,
292,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 91, 64, 85, 85, 85, 85, 85, 85, 0,
}},
{0,
10,
293,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
294,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
295,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
296,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 174, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
297,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0,
}},
{0,
10,
298,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
299,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
300,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0,
}},
{0,
10,
302,
{
0, 0, 0, 0, 168, 170, 0, 128, 174, 170, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
303,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 171, 128, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
304,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
305,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
307,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
308,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 174, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
310,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 234, 0,
}},
{0,
10,
311,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
312,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0,
}},
{0,
10,
314,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
315,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0,
}},
{0,
10,
316,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
317,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
318,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
319,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{0,
10,
320,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
321,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
322,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
323,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 192, 170, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
324,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
325,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0,
}},
{0,
10,
326,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 174, 170, 170, 170, 170, 0,
}},
{0,
10,
327,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
328,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
329,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
330,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 171, 170, 0,
}},
{10,
332,
335,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 213, 85, 85, 0,
}},
{0,
10,
333,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
334,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
336,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
337,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
338,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
340,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
341,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
342,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
92,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
344,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
345,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
346,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 186, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
347,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0,
}},
{0,
10,
350,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0,
}},
{0,
10,
351,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
352,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
353,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
354,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
356,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
358,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 186, 170, 0,
}},
{0,
10,
359,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
361,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 186, 170, 170, 0,
}},
{0,
10,
362,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
363,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 234, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
364,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{10,
366,
378,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 85, 86, 87, 85, 0,
}},
{10,
367,
373,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 85, 86, 85, 87, 85, 0,
}},
{10,
368,
372,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 85, 89, 85, 93, 85, 85, 0,
}},
{0,
10,
369,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 174, 170, 170, 0,
}},
{0,
10,
370,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
371,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 234, 170, 170, 170, 0,
}},
{0,
10,
374,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
375,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 186, 170, 170, 170, 170, 0,
}},
{0,
10,
376,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
377,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
10,
379,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
380,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{10,
382,
387,
{
0, 0, 0, 0, 84, 85, 0, 64, 85, 85, 64, 86, 85, 85, 93, 85, 85, 0,
}},
{0,
10,
383,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 234, 170, 170, 0,
}},
{0,
10,
384,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 170, 186, 0,
}},
{0,
10,
385,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
386,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 171, 170, 170, 0,
}},
{0,
10,
388,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
389,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 171, 170, 170, 170, 170, 170, 0,
}},
{0,
10,
390,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 170, 170, 174, 170, 0,
}},
{0,
10,
391,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
392,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
394,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 234, 170, 170, 170, 170, 0,
}},
{0,
10,
395,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 171, 170, 170, 170, 0,
}},
{0,
10,
396,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 170, 186, 170, 170, 170, 0,
}},
{0,
10,
397,
{
0, 0, 0, 0, 168, 170, 0, 128, 170, 170, 128, 170, 171, 170, 170, 170, 170, 0,
}},
{0,
400,
401,
{
0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12,
}},
};
static constexpr IndexEntry kIndices[] = {
{0, 0}, {1, 0}, {2, 0}, {2, 0}, {0, 0}, {2, 1}, {0, 0}, {2, 2}, {2, 3},
{2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 5}, {2, 8}, {0, 0}, {2, 9}, {0, 0},
{0, 0}, {0, 0}, {0, 0}, {2, 10}, {0, 0}, {2, 11}, {0, 0}, {0, 0}, {0, 0},
{2, 12}, {0, 0}, {0, 0}, {2, 13}, {2, 14}, {2, 15}, {2, 16}, {2, 16}, {2, 17},
{2, 18}, {2, 19}, {0, 0}, {2, 20}, {0, 0}, {1, 1}, {2, 21}, {2, 22}, {2, 23},
{2, 24}, {2, 24}, {2, 25}, {2, 26}, {2, 26}, {1, 2}, {1, 3}, {2, 27}, {2, 28},
{2, 28}, {0, 0}, {0, 0}, {0, 0}, {2, 29}, {2, 30}, {1, 4}, {1, 4}, {0, 0},
{0, 0}, {2, 31}, {2, 32}, {0, 0}, {0, 0}, {2, 33}, {0, 0}, {2, 34}, {0, 0},
{2, 35}, {0, 0}, {0, 0}, {2, 36}, {2, 37}, {0, 0}, {2, 38}, {2, 39}, {2, 40},
{2, 41}, {2, 42}, {0, 0}, {2, 5}, {0, 0}, {0, 0}, {2, 43}, {0, 0}, {0, 0},
{2, 44}, {2, 45}, {2, 5}, {2, 46}, {2, 47}, {2, 48}, {2, 49}, {2, 50}, {2, 51},
{2, 52}, {2, 53}, {2, 54}, {2, 55}, {2, 56}, {2, 5}, {1, 5}, {2, 57}, {2, 58},
{2, 5}, {2, 59}, {2, 60}, {2, 61}, {2, 62}, {2, 63}, {2, 64}, {2, 5}, {2, 65},
{2, 66}, {2, 67}, {2, 68}, {2, 5}, {1, 6}, {2, 69}, {2, 70}, {2, 71}, {2, 72},
{2, 73}, {2, 5}, {2, 74}, {2, 75}, {2, 76}, {2, 77}, {2, 78}, {2, 5}, {2, 79},
{2, 80}, {2, 81}, {2, 52}, {2, 82}, {2, 83}, {2, 84}, {1, 7}, {2, 85}, {2, 86},
{2, 5}, {2, 87}, {2, 45}, {2, 88}, {2, 89}, {2, 90}, {2, 91}, {2, 92}, {2, 93},
{1, 8}, {2, 94}, {2, 95}, {2, 96}, {2, 5}, {2, 97}, {2, 98}, {2, 99}, {2, 100},
{2, 101}, {2, 5}, {2, 102}, {2, 5}, {2, 103}, {2, 104}, {2, 84}, {2, 105}, {2, 106},
{2, 107}, {2, 108}, {2, 109}, {2, 110}, {2, 111}, {2, 112}, {2, 113}, {2, 5}, {2, 114},
{2, 115}, {2, 84}, {2, 116}, {2, 5}, {1, 9}, {2, 117}, {2, 118}, {2, 119}, {2, 5},
{2, 120}, {2, 121}, {2, 5}, {2, 122}, {2, 123}, {2, 124}, {2, 125}, {2, 126}, {2, 127},
{2, 128}, {2, 52}, {2, 129}, {2, 130}, {2, 131}, {2, 132}, {2, 133}, {2, 123}, {2, 134},
{2, 135}, {2, 136}, {2, 137}, {2, 138}, {2, 5}, {2, 139}, {2, 140}, {2, 141}, {2, 5},
{2, 142}, {2, 143}, {2, 144}, {2, 145}, {2, 146}, {2, 147}, {2, 5}, {2, 148}, {2, 149},
{2, 150}, {2, 151}, {2, 152}, {2, 153}, {2, 154}, {2, 52}, {2, 155}, {2, 156}, {2, 157},
{2, 158}, {2, 159}, {2, 160}, {2, 5}, {2, 161}, {2, 162}, {2, 163}, {2, 164}, {2, 165},
{2, 166}, {2, 167}, {2, 168}, {2, 169}, {2, 170}, {2, 5}, {2, 171}, {2, 172}, {2, 173},
{2, 174}, {2, 123}, {1, 10}, {2, 175}, {2, 176}, {2, 177}, {2, 99}, {2, 178}, {2, 179},
{2, 180}, {2, 181}, {2, 182}, {2, 183}, {2, 184}, {2, 185}, {2, 186}, {2, 187}, {2, 188},
{2, 189}, {2, 190}, {2, 191}, {2, 192}, {2, 193}, {2, 5}, {1, 11}, {2, 194}, {2, 195},
{2, 196}, {2, 197}, {2, 198}, {1, 12}, {2, 199}, {2, 200}, {2, 201}, {2, 202}, {2, 203},
{2, 204}, {2, 205}, {2, 206}, {2, 207}, {2, 208}, {2, 209}, {2, 210}, {2, 211}, {2, 212},
{2, 213}, {2, 214}, {2, 215}, {2, 205}, {2, 216}, {2, 217}, {2, 218}, {2, 219}, {2, 123},
{2, 220}, {2, 221}, {2, 52}, {2, 222}, {2, 223}, {2, 224}, {2, 225}, {2, 226}, {2, 227},
{2, 228}, {2, 229}, {2, 230}, {2, 231}, {2, 232}, {2, 233}, {2, 234}, {2, 235}, {2, 236},
{2, 237}, {2, 238}, {2, 239}, {2, 240}, {2, 241}, {2, 242}, {2, 5}, {2, 243}, {2, 244},
{2, 245}, {2, 188}, {2, 246}, {2, 247}, {2, 248}, {2, 5}, {2, 249}, {2, 250}, {2, 251},
{2, 252}, {2, 253}, {2, 254}, {2, 255}, {2, 256}, {2, 5}, {1, 13}, {2, 257}, {2, 258},
{2, 259}, {2, 260}, {2, 261}, {2, 52}, {2, 262}, {2, 61}, {2, 263}, {2, 264}, {2, 5},
{2, 265}, {2, 266}, {2, 267}, {2, 268}, {2, 225}, {2, 269}, {2, 270}, {2, 271}, {2, 272},
{2, 273}, {2, 274}, {2, 5}, {2, 184}, {2, 275}, {2, 276}, {2, 277}, {2, 278}, {2, 99},
{2, 279}, {2, 280}, {2, 140}, {2, 281}, {2, 282}, {2, 283}, {2, 284}, {2, 285}, {2, 140},
{2, 286}, {2, 287}, {2, 288}, {2, 289}, {2, 290}, {2, 52}, {2, 291}, {2, 292}, {2, 293},
{2, 294}, {2, 5}, {0, 0}, {2, 295}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
};
State get_transition(int transition, int state) {
IndexEntry index = kIndices[state];
if (index.type == 0) {
return 0;
}
if (index.type == 1) {
return kFull[index.pos].data[transition];
}
const CompactEntry& entry = kCompact[index.pos];
int value = entry.data[transition >> 2];
value >>= 2 * (transition & 3);
value &= 3;
State table[] = {0, entry.v0, entry.v1, entry.v2};
return table[value];
}
static const int8_t kAccepts[404] = {
-1, -1, 84, 84, 87, 63, 68, 87, 38, 37, 37, 37, 37, 35, 53, 77, 58, 62, 82, 39, 40, 51, 75,
49, 47, 73, 46, 50, 48, 74, 45, 1, -1, -1, 1, 52, -1, -1, 86, 85, 76, 2, 1, 1, -1, -1,
1, -1, -1, 1, 2, 3, -1, -1, 1, 3, 2, 2, -1, 2, 2, 2, 65, 83, 70, 54, 78, 72, 66,
67, 69, 71, 55, 79, 64, 87, -1, 7, -1, -1, -1, -1, -1, 13, 37, 43, 44, 57, 81, 61, 37, 37,
36, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 16, 37, 37, 37, 14, 37, 37, 37, 37, 37, 37,
24, 37, 37, 37, 37, 17, 37, 37, 37, 37, 37, 37, 15, 37, 37, 37, 37, 37, 18, 11, 37, 37, 37,
37, 37, 37, 37, 37, 37, 8, 37, 37, 37, 37, 37, 37, 36, 37, 37, 37, 37, 37, 5, 37, 37, 37,
37, 37, 25, 37, 9, 37, 37, 37, 37, 37, 36, 37, 37, 37, 37, 37, 37, 32, 37, 37, 37, 37, 6,
20, 37, 37, 37, 27, 37, 37, 22, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 37, 31, 37, 37, 37, 34, 37, 37, 37, 37, 37, 37, 33, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 37, 37, 37, 37, 28, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 26, 37, 37, 21, 37,
37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 19,
37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 37, 37, 37, 37, 37, 29, 37, 37, 37, 37, 37, 37, 37, 30, 37, 37, 37, 37, 37, 37,
37, 37, 12, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 4, 37, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 23, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
37, 37, 37, 37, 37, 37, 10, 41, 56, 80, 60, 42, 59,
};
Token Lexer::next() {
// note that we cheat here: normally a lexer needs to worry about the case
// where a token has a prefix which is not itself a valid token - for instance,
// maybe we have a valid token 'while', but 'w', 'wh', etc. are not valid
// tokens. Our grammar doesn't have this property, so we can simplify the logic
// a bit.
int32_t startOffset = fOffset;
if (startOffset == (int32_t)fText.length()) {
return Token(Token::Kind::TK_END_OF_FILE, startOffset, 0);
}
State state = 1;
for (;;) {
if (fOffset >= (int32_t)fText.length()) {
if (kAccepts[state] == -1) {
return Token(Token::Kind::TK_END_OF_FILE, startOffset, 0);
}
break;
}
uint8_t c = (uint8_t)fText[fOffset];
if (c <= 8 || c >= 127) {
c = INVALID_CHAR;
}
State newState = get_transition(kMappings[c], state);
if (!newState) {
break;
}
state = newState;
++fOffset;
}
Token::Kind kind = (Token::Kind)kAccepts[state];
return Token(kind, startOffset, fOffset - startOffset);
}
} // namespace SkSL
| 29.617433
| 99
| 0.303123
|
wan-nyan-wan
|
44a5d961d22e97232f26109ab917d3badb1fa340
| 885
|
hpp
|
C++
|
externals/boost/boost/beast/http/file_body.hpp
|
YuukiTsuchida/v8_embeded
|
c6e18f4e91fcc50607f8e3edc745a3afa30b2871
|
[
"MIT"
] | 32
|
2019-02-27T06:57:07.000Z
|
2021-08-29T10:56:19.000Z
|
jeff/common/include/boost/beast/http/file_body.hpp
|
jeffphi/advent-of-code-2018
|
8e54bd23ebfe42fcbede315f0ab85db903551532
|
[
"MIT"
] | 1
|
2018-04-18T16:33:00.000Z
|
2018-04-18T16:33:00.000Z
|
jeff/common/include/boost/beast/http/file_body.hpp
|
jeffphi/advent-of-code-2018
|
8e54bd23ebfe42fcbede315f0ab85db903551532
|
[
"MIT"
] | 5
|
2019-08-20T13:45:04.000Z
|
2022-03-01T18:23:49.000Z
|
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BOOST_BEAST_HTTP_FILE_BODY_HPP
#define BOOST_BEAST_HTTP_FILE_BODY_HPP
#include <boost/beast/core/file.hpp>
#include <boost/beast/http/basic_file_body.hpp>
#include <boost/assert.hpp>
#include <boost/optional.hpp>
#include <algorithm>
#include <cstdio>
#include <cstdint>
#include <utility>
namespace boost {
namespace beast {
namespace http {
/// A message body represented by a file on the filesystem.
using file_body = basic_file_body<file>;
} // http
} // beast
} // boost
#include <boost/beast/http/impl/file_body_win32.ipp>
#endif
| 24.583333
| 80
| 0.723164
|
YuukiTsuchida
|
44a67743169ec9c8eb4adb03d18cd5374f2ac3e9
| 2,797
|
cpp
|
C++
|
llvm/lib/DebugInfo/CodeView/CVSymbolVisitor.cpp
|
NoamDev/TON-Compiler
|
f76aa2084c7f09a228afef4a6e073c37b350c8f3
|
[
"Apache-2.0"
] | 171
|
2018-09-17T13:15:12.000Z
|
2022-03-18T03:47:04.000Z
|
llvm/lib/DebugInfo/CodeView/CVSymbolVisitor.cpp
|
NoamDev/TON-Compiler
|
f76aa2084c7f09a228afef4a6e073c37b350c8f3
|
[
"Apache-2.0"
] | 51
|
2019-10-23T11:55:08.000Z
|
2021-12-21T06:32:11.000Z
|
llvm/lib/DebugInfo/CodeView/CVSymbolVisitor.cpp
|
NoamDev/TON-Compiler
|
f76aa2084c7f09a228afef4a6e073c37b350c8f3
|
[
"Apache-2.0"
] | 55
|
2018-02-01T07:11:49.000Z
|
2022-03-04T01:20:23.000Z
|
//===- CVSymbolVisitor.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/CodeView/CVSymbolVisitor.h"
#include "llvm/DebugInfo/CodeView/CodeViewError.h"
#include "llvm/DebugInfo/CodeView/SymbolVisitorCallbacks.h"
using namespace llvm;
using namespace llvm::codeview;
CVSymbolVisitor::CVSymbolVisitor(SymbolVisitorCallbacks &Callbacks)
: Callbacks(Callbacks) {}
template <typename T>
static Error visitKnownRecord(CVSymbol &Record,
SymbolVisitorCallbacks &Callbacks) {
SymbolRecordKind RK = static_cast<SymbolRecordKind>(Record.Type);
T KnownRecord(RK);
if (auto EC = Callbacks.visitKnownRecord(Record, KnownRecord))
return EC;
return Error::success();
}
static Error finishVisitation(CVSymbol &Record,
SymbolVisitorCallbacks &Callbacks) {
switch (Record.Type) {
default:
if (auto EC = Callbacks.visitUnknownSymbol(Record))
return EC;
break;
#define SYMBOL_RECORD(EnumName, EnumVal, Name) \
case EnumName: { \
if (auto EC = visitKnownRecord<Name>(Record, Callbacks)) \
return EC; \
break; \
}
#define SYMBOL_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName) \
SYMBOL_RECORD(EnumVal, EnumVal, AliasName)
#include "llvm/DebugInfo/CodeView/CodeViewSymbols.def"
}
if (auto EC = Callbacks.visitSymbolEnd(Record))
return EC;
return Error::success();
}
Error CVSymbolVisitor::visitSymbolRecord(CVSymbol &Record) {
if (auto EC = Callbacks.visitSymbolBegin(Record))
return EC;
return finishVisitation(Record, Callbacks);
}
Error CVSymbolVisitor::visitSymbolRecord(CVSymbol &Record, uint32_t Offset) {
if (auto EC = Callbacks.visitSymbolBegin(Record, Offset))
return EC;
return finishVisitation(Record, Callbacks);
}
Error CVSymbolVisitor::visitSymbolStream(const CVSymbolArray &Symbols) {
for (auto I : Symbols) {
if (auto EC = visitSymbolRecord(I))
return EC;
}
return Error::success();
}
Error CVSymbolVisitor::visitSymbolStream(const CVSymbolArray &Symbols,
uint32_t InitialOffset) {
for (auto I : Symbols) {
if (auto EC = visitSymbolRecord(I, InitialOffset))
return EC;
InitialOffset += I.length();
}
return Error::success();
}
| 33.297619
| 80
| 0.602789
|
NoamDev
|
44a7e0dfb470e479320807c8e67c9895122e1cf4
| 1,198
|
cpp
|
C++
|
libcxx/test/std/utilities/tuple/tuple.tuple/tuple.cnstr/dtor.pass.cpp
|
mkinsner/llvm
|
589d48844edb12cd357b3024248b93d64b6760bf
|
[
"Apache-2.0"
] | 2,338
|
2018-06-19T17:34:51.000Z
|
2022-03-31T11:00:37.000Z
|
libcxx/test/std/utilities/tuple/tuple.tuple/tuple.cnstr/dtor.pass.cpp
|
mkinsner/llvm
|
589d48844edb12cd357b3024248b93d64b6760bf
|
[
"Apache-2.0"
] | 3,740
|
2019-01-23T15:36:48.000Z
|
2022-03-31T22:01:13.000Z
|
libcxx/test/std/utilities/tuple/tuple.tuple/tuple.cnstr/dtor.pass.cpp
|
mkinsner/llvm
|
589d48844edb12cd357b3024248b93d64b6760bf
|
[
"Apache-2.0"
] | 500
|
2019-01-23T07:49:22.000Z
|
2022-03-30T02:59:37.000Z
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03
// <tuple>
// template <class... Types> class tuple;
// ~tuple();
// C++17 added:
// The destructor of tuple shall be a trivial destructor
// if (is_trivially_destructible_v<Types> && ...) is true.
#include <tuple>
#include <string>
#include <cassert>
#include <type_traits>
#include "test_macros.h"
int main(int, char**)
{
static_assert(std::is_trivially_destructible<
std::tuple<> >::value, "");
static_assert(std::is_trivially_destructible<
std::tuple<void*> >::value, "");
static_assert(std::is_trivially_destructible<
std::tuple<int, float> >::value, "");
static_assert(!std::is_trivially_destructible<
std::tuple<std::string> >::value, "");
static_assert(!std::is_trivially_destructible<
std::tuple<int, std::string> >::value, "");
return 0;
}
| 27.860465
| 80
| 0.583472
|
mkinsner
|
44a924d90f8efaa1a45f8184676a3ef0cf65cd88
| 5,538
|
cpp
|
C++
|
Samples/SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp
|
dujianxin/Windows-universal-samples
|
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
|
[
"MIT"
] | 2,504
|
2019-05-07T06:56:42.000Z
|
2022-03-31T19:37:59.000Z
|
Samples/SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp
|
dujianxin/Windows-universal-samples
|
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
|
[
"MIT"
] | 314
|
2019-05-08T16:56:30.000Z
|
2022-03-21T07:13:45.000Z
|
Samples/SpatialSound/cpp/Scenario2_CardioidSound.xaml.cpp
|
dujianxin/Windows-universal-samples
|
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
|
[
"MIT"
] | 2,219
|
2019-05-07T00:47:26.000Z
|
2022-03-30T21:12:31.000Z
|
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario2_CardioidSound.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
Scenario2_CardioidSound::Scenario2_CardioidSound() : _rootPage(MainPage::Current)
{
InitializeComponent();
auto hr = _cardioidSound.Initialize(L"assets//MonoSound.wav");
if (SUCCEEDED(hr))
{
_timer = ref new DispatcherTimer();
_timerEventToken = _timer->Tick += ref new EventHandler<Platform::Object^>(this, &Scenario2_CardioidSound::OnTimerTick);
TimeSpan timespan;
timespan.Duration = 10000 / 30;
_timer->Interval = timespan;
EnvironmentComboBox->SelectedIndex = static_cast<int>(_cardioidSound.GetEnvironment());
_rootPage->NotifyUser("Stopped", NotifyType::StatusMessage);
}
else
{
if (hr == E_NOTIMPL)
{
_rootPage->NotifyUser("HRTF API is not supported on this platform. Use X3DAudio API instead - https://code.msdn.microsoft.com/XAudio2-Win32-Samples-024b3933", NotifyType::ErrorMessage);
}
else
{
throw ref new COMException(hr);
}
}
_initialized = SUCCEEDED(hr);
}
Scenario2_CardioidSound::~Scenario2_CardioidSound()
{
if (_timerEventToken.Value != 0)
{
_timer->Tick -= _timerEventToken;
}
}
void SDKTemplate::Scenario2_CardioidSound::EnvironmentComboBox_SelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
{
if (_initialized)
{
_cardioidSound.SetEnvironment(static_cast<HrtfEnvironment>(EnvironmentComboBox->SelectedIndex));
}
}
void SDKTemplate::Scenario2_CardioidSound::ScalingSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
UpdateScalingAndOrder();
}
void SDKTemplate::Scenario2_CardioidSound::OrderSlider_ValudChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
UpdateScalingAndOrder();
}
void SDKTemplate::Scenario2_CardioidSound::YawSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
_yaw = static_cast<float>(e->NewValue);
}
void SDKTemplate::Scenario2_CardioidSound::PitchSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
_pitch = static_cast<float>(e->NewValue);
}
void SDKTemplate::Scenario2_CardioidSound::RollSlider_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
_roll = static_cast<float>(e->NewValue);
}
void SDKTemplate::Scenario2_CardioidSound::PlayButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
if (_initialized)
{
_cardioidSound.Start();
_state = PlayState::Playing;
_rootPage->NotifyUser("Playing", NotifyType::StatusMessage);
}
}
void SDKTemplate::Scenario2_CardioidSound::StopButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
if (_initialized)
{
_cardioidSound.Stop();
_state = PlayState::Stopped;
_rootPage->NotifyUser("Stopped", NotifyType::StatusMessage);
}
}
void SDKTemplate::Scenario2_CardioidSound::OnTimerTick(Object^ sender, Object^ e)
{
// Update the sound position and orientation on every dispatcher timer tick.
_cardioidSound.OnUpdate(_x, _y, _z, _pitch, _yaw, _roll);
}
void SDKTemplate::Scenario2_CardioidSound::UpdateScalingAndOrder()
{
if (_initialized)
{
_timer->Stop();
_cardioidSound.ConfigureApo(static_cast<float>(ScalingSlider->Value), static_cast<float>(OrderSlider->Value));
_timer->Start();
if (_state == PlayState::Playing)
{
_cardioidSound.Start();
}
}
}
void SDKTemplate::Scenario2_CardioidSound::SourcePositionX_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
_x = static_cast<float>(e->NewValue);
}
void SDKTemplate::Scenario2_CardioidSound::SourcePositionY_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
_y = static_cast<float>(e->NewValue);
}
void SDKTemplate::Scenario2_CardioidSound::SourcePositionZ_ValueChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::Primitives::RangeBaseValueChangedEventArgs^ e)
{
_z = static_cast<float>(e->NewValue);
}
| 35.5
| 198
| 0.693933
|
dujianxin
|
44a97b9b35f7fe7e27b06f96d1ec813a685a9b18
| 14,906
|
cpp
|
C++
|
deps/src/boost_1_65_1/libs/utility/test/call_traits_test.cpp
|
shreyasvj25/turicreate
|
32e84ca16aef8d04aff3d49ae9984bd49326bffd
|
[
"BSD-3-Clause"
] | 11,356
|
2017-12-08T19:42:32.000Z
|
2022-03-31T16:55:25.000Z
|
deps/src/boost_1_65_1/libs/utility/test/call_traits_test.cpp
|
shreyasvj25/turicreate
|
32e84ca16aef8d04aff3d49ae9984bd49326bffd
|
[
"BSD-3-Clause"
] | 2,402
|
2017-12-08T22:31:01.000Z
|
2022-03-28T19:25:52.000Z
|
deps/src/boost_1_65_1/libs/utility/test/call_traits_test.cpp
|
shreyasvj25/turicreate
|
32e84ca16aef8d04aff3d49ae9984bd49326bffd
|
[
"BSD-3-Clause"
] | 1,343
|
2017-12-08T19:47:19.000Z
|
2022-03-26T11:31:36.000Z
|
// boost::compressed_pair test program
// (C) Copyright John Maddock 2000.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
// standalone test program for <boost/call_traits.hpp>
// 18 Mar 2002:
// Changed some names to prevent conflicts with some new type_traits additions.
// 03 Oct 2000:
// Enabled extra tests for VC6.
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <typeinfo>
#include <boost/call_traits.hpp>
#include <libs/type_traits/test/test.hpp>
#include <libs/type_traits/test/check_type.hpp>
#ifdef BOOST_MSVC
#pragma warning(disable:4181) // : warning C4181: qualifier applied to reference type; ignored
#endif
// a way prevent warnings for unused variables
template<class T> inline void unused_variable(const T&) {}
//
// struct contained models a type that contains a type (for example std::pair)
// arrays are contained by value, and have to be treated as a special case:
//
template <class T>
struct contained
{
// define our typedefs first, arrays are stored by value
// so value_type is not the same as result_type:
typedef typename boost::call_traits<T>::param_type param_type;
typedef typename boost::call_traits<T>::reference reference;
typedef typename boost::call_traits<T>::const_reference const_reference;
typedef T value_type;
typedef typename boost::call_traits<T>::value_type result_type;
// stored value:
value_type v_;
// constructors:
contained() {}
contained(param_type p) : v_(p){}
// return byval:
result_type value()const { return v_; }
// return by_ref:
reference get() { return v_; }
const_reference const_get()const { return v_; }
// pass value:
void call(param_type){}
private:
contained& operator=(const contained&);
};
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
template <class T, std::size_t N>
struct contained<T[N]>
{
typedef typename boost::call_traits<T[N]>::param_type param_type;
typedef typename boost::call_traits<T[N]>::reference reference;
typedef typename boost::call_traits<T[N]>::const_reference const_reference;
typedef T value_type[N];
typedef typename boost::call_traits<T[N]>::value_type result_type;
value_type v_;
contained(param_type p)
{
std::copy(p, p+N, v_);
}
// return byval:
result_type value()const { return v_; }
// return by_ref:
reference get() { return v_; }
const_reference const_get()const { return v_; }
void call(param_type){}
private:
contained& operator=(const contained&);
};
#endif
template <class T>
contained<typename boost::call_traits<T>::value_type> test_wrap_type(const T& t)
{
typedef typename boost::call_traits<T>::value_type ct;
return contained<ct>(t);
}
namespace test{
template <class T1, class T2>
std::pair<
typename boost::call_traits<T1>::value_type,
typename boost::call_traits<T2>::value_type>
make_pair(const T1& t1, const T2& t2)
{
return std::pair<
typename boost::call_traits<T1>::value_type,
typename boost::call_traits<T2>::value_type>(t1, t2);
}
} // namespace test
using namespace std;
//
// struct call_traits_checker:
// verifies behaviour of contained example:
//
template <class T>
struct call_traits_checker
{
typedef typename boost::call_traits<T>::param_type param_type;
void operator()(param_type);
};
template <class T>
void call_traits_checker<T>::operator()(param_type p)
{
T t(p);
contained<T> c(t);
cout << "checking contained<" << typeid(T).name() << ">..." << endl;
BOOST_CHECK(t == c.value());
BOOST_CHECK(t == c.get());
BOOST_CHECK(t == c.const_get());
#ifndef __ICL
//cout << "typeof contained<" << typeid(T).name() << ">::v_ is: " << typeid(&contained<T>::v_).name() << endl;
cout << "typeof contained<" << typeid(T).name() << ">::value() is: " << typeid(&contained<T>::value).name() << endl;
cout << "typeof contained<" << typeid(T).name() << ">::get() is: " << typeid(&contained<T>::get).name() << endl;
cout << "typeof contained<" << typeid(T).name() << ">::const_get() is: " << typeid(&contained<T>::const_get).name() << endl;
cout << "typeof contained<" << typeid(T).name() << ">::call() is: " << typeid(&contained<T>::call).name() << endl;
cout << endl;
#endif
}
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
template <class T, std::size_t N>
struct call_traits_checker<T[N]>
{
typedef typename boost::call_traits<T[N]>::param_type param_type;
void operator()(param_type t)
{
contained<T[N]> c(t);
cout << "checking contained<" << typeid(T[N]).name() << ">..." << endl;
unsigned int i = 0;
for(i = 0; i < N; ++i)
BOOST_CHECK(t[i] == c.value()[i]);
for(i = 0; i < N; ++i)
BOOST_CHECK(t[i] == c.get()[i]);
for(i = 0; i < N; ++i)
BOOST_CHECK(t[i] == c.const_get()[i]);
cout << "typeof contained<" << typeid(T[N]).name() << ">::v_ is: " << typeid(&contained<T[N]>::v_).name() << endl;
cout << "typeof contained<" << typeid(T[N]).name() << ">::value is: " << typeid(&contained<T[N]>::value).name() << endl;
cout << "typeof contained<" << typeid(T[N]).name() << ">::get is: " << typeid(&contained<T[N]>::get).name() << endl;
cout << "typeof contained<" << typeid(T[N]).name() << ">::const_get is: " << typeid(&contained<T[N]>::const_get).name() << endl;
cout << "typeof contained<" << typeid(T[N]).name() << ">::call is: " << typeid(&contained<T[N]>::call).name() << endl;
cout << endl;
}
};
#endif
//
// check_wrap:
template <class W, class U>
void check_wrap(const W& w, const U& u)
{
cout << "checking " << typeid(W).name() << "..." << endl;
BOOST_CHECK(w.value() == u);
}
//
// check_make_pair:
// verifies behaviour of "make_pair":
//
template <class T, class U, class V>
void check_make_pair(T c, U u, V v)
{
cout << "checking std::pair<" << typeid(c.first).name() << ", " << typeid(c.second).name() << ">..." << endl;
BOOST_CHECK(c.first == u);
BOOST_CHECK(c.second == v);
cout << endl;
}
struct comparible_UDT
{
int i_;
comparible_UDT() : i_(2){}
comparible_UDT(const comparible_UDT& other) : i_(other.i_){}
comparible_UDT& operator=(const comparible_UDT& other)
{
i_ = other.i_;
return *this;
}
bool operator == (const comparible_UDT& v){ return v.i_ == i_; }
};
int main()
{
call_traits_checker<comparible_UDT> c1;
comparible_UDT u;
c1(u);
call_traits_checker<int> c2;
call_traits_checker<enum_UDT> c2b;
int i = 2;
c2(i);
c2b(one);
int* pi = &i;
int a[2] = {1,2};
#if defined(BOOST_MSVC6_MEMBER_TEMPLATES) && !defined(__ICL)
call_traits_checker<int*> c3;
c3(pi);
call_traits_checker<int&> c4;
c4(i);
call_traits_checker<const int&> c5;
c5(i);
#if !defined (BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(__MWERKS__) && !defined(__SUNPRO_CC)
call_traits_checker<int[2]> c6;
c6(a);
#endif
#endif
check_wrap(test_wrap_type(2), 2);
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(__SUNPRO_CC)
check_wrap(test_wrap_type(a), a);
check_make_pair(test::make_pair(a, a), a, a);
#endif
// cv-qualifiers applied to reference types should have no effect
// declare these here for later use with is_reference and remove_reference:
typedef int& r_type;
typedef const r_type cr_type;
BOOST_CHECK_TYPE(comparible_UDT, boost::call_traits<comparible_UDT>::value_type);
BOOST_CHECK_TYPE(comparible_UDT&, boost::call_traits<comparible_UDT>::reference);
BOOST_CHECK_TYPE(const comparible_UDT&, boost::call_traits<comparible_UDT>::const_reference);
BOOST_CHECK_TYPE(const comparible_UDT&, boost::call_traits<comparible_UDT>::param_type);
BOOST_CHECK_TYPE(int, boost::call_traits<int>::value_type);
BOOST_CHECK_TYPE(int&, boost::call_traits<int>::reference);
BOOST_CHECK_TYPE(const int&, boost::call_traits<int>::const_reference);
BOOST_CHECK_TYPE(const int, boost::call_traits<int>::param_type);
BOOST_CHECK_TYPE(int*, boost::call_traits<int*>::value_type);
BOOST_CHECK_TYPE(int*&, boost::call_traits<int*>::reference);
BOOST_CHECK_TYPE(int*const&, boost::call_traits<int*>::const_reference);
BOOST_CHECK_TYPE(int*const, boost::call_traits<int*>::param_type);
#if defined(BOOST_MSVC6_MEMBER_TEMPLATES)
BOOST_CHECK_TYPE(int&, boost::call_traits<int&>::value_type);
BOOST_CHECK_TYPE(int&, boost::call_traits<int&>::reference);
BOOST_CHECK_TYPE(const int&, boost::call_traits<int&>::const_reference);
BOOST_CHECK_TYPE(int&, boost::call_traits<int&>::param_type);
#if !(defined(__GNUC__) && ((__GNUC__ < 3) || (__GNUC__ == 3) && (__GNUC_MINOR__ < 1)))
BOOST_CHECK_TYPE(int&, boost::call_traits<cr_type>::value_type);
BOOST_CHECK_TYPE(int&, boost::call_traits<cr_type>::reference);
BOOST_CHECK_TYPE(const int&, boost::call_traits<cr_type>::const_reference);
BOOST_CHECK_TYPE(int&, boost::call_traits<cr_type>::param_type);
#else
std::cout << "Your compiler cannot instantiate call_traits<int&const>, skipping four tests (4 errors)" << std::endl;
#endif
BOOST_CHECK_TYPE(const int&, boost::call_traits<const int&>::value_type);
BOOST_CHECK_TYPE(const int&, boost::call_traits<const int&>::reference);
BOOST_CHECK_TYPE(const int&, boost::call_traits<const int&>::const_reference);
BOOST_CHECK_TYPE(const int&, boost::call_traits<const int&>::param_type);
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
BOOST_CHECK_TYPE(const int*, boost::call_traits<int[3]>::value_type);
BOOST_CHECK_TYPE(int(&)[3], boost::call_traits<int[3]>::reference);
BOOST_CHECK_TYPE(const int(&)[3], boost::call_traits<int[3]>::const_reference);
BOOST_CHECK_TYPE(const int*const, boost::call_traits<int[3]>::param_type);
BOOST_CHECK_TYPE(const int*, boost::call_traits<const int[3]>::value_type);
BOOST_CHECK_TYPE(const int(&)[3], boost::call_traits<const int[3]>::reference);
BOOST_CHECK_TYPE(const int(&)[3], boost::call_traits<const int[3]>::const_reference);
BOOST_CHECK_TYPE(const int*const, boost::call_traits<const int[3]>::param_type);
// test with abstract base class:
BOOST_CHECK_TYPE(test_abc1, boost::call_traits<test_abc1>::value_type);
BOOST_CHECK_TYPE(test_abc1&, boost::call_traits<test_abc1>::reference);
BOOST_CHECK_TYPE(const test_abc1&, boost::call_traits<test_abc1>::const_reference);
BOOST_CHECK_TYPE(const test_abc1&, boost::call_traits<test_abc1>::param_type);
#else
std::cout << "You're compiler does not support partial template specialiation, skipping 8 tests (8 errors)" << std::endl;
#endif
#else
std::cout << "You're compiler does not support partial template specialiation, skipping 20 tests (20 errors)" << std::endl;
#endif
// test with an incomplete type:
BOOST_CHECK_TYPE(incomplete_type, boost::call_traits<incomplete_type>::value_type);
BOOST_CHECK_TYPE(incomplete_type&, boost::call_traits<incomplete_type>::reference);
BOOST_CHECK_TYPE(const incomplete_type&, boost::call_traits<incomplete_type>::const_reference);
BOOST_CHECK_TYPE(const incomplete_type&, boost::call_traits<incomplete_type>::param_type);
// test enum:
BOOST_CHECK_TYPE(enum_UDT, boost::call_traits<enum_UDT>::value_type);
BOOST_CHECK_TYPE(enum_UDT&, boost::call_traits<enum_UDT>::reference);
BOOST_CHECK_TYPE(const enum_UDT&, boost::call_traits<enum_UDT>::const_reference);
BOOST_CHECK_TYPE(const enum_UDT, boost::call_traits<enum_UDT>::param_type);
return 0;
}
//
// define call_traits tests to check that the assertions in the docs do actually work
// this is an compile-time only set of tests:
//
template <typename T, bool isarray = false>
struct call_traits_test
{
typedef ::boost::call_traits<T> ct;
typedef typename ct::param_type param_type;
typedef typename ct::reference reference;
typedef typename ct::const_reference const_reference;
typedef typename ct::value_type value_type;
static void assert_construct(param_type val);
};
template <typename T, bool isarray>
void call_traits_test<T, isarray>::assert_construct(typename call_traits_test<T, isarray>::param_type val)
{
//
// this is to check that the call_traits assertions are valid:
T t(val);
value_type v(t);
reference r(t);
const_reference cr(t);
param_type p(t);
value_type v2(v);
value_type v3(r);
value_type v4(p);
reference r2(v);
reference r3(r);
const_reference cr2(v);
const_reference cr3(r);
const_reference cr4(cr);
const_reference cr5(p);
param_type p2(v);
param_type p3(r);
param_type p4(p);
unused_variable(v2);
unused_variable(v3);
unused_variable(v4);
unused_variable(r2);
unused_variable(r3);
unused_variable(cr2);
unused_variable(cr3);
unused_variable(cr4);
unused_variable(cr5);
unused_variable(p2);
unused_variable(p3);
unused_variable(p4);
}
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
template <typename T>
struct call_traits_test<T, true>
{
typedef ::boost::call_traits<T> ct;
typedef typename ct::param_type param_type;
typedef typename ct::reference reference;
typedef typename ct::const_reference const_reference;
typedef typename ct::value_type value_type;
static void assert_construct(param_type val);
};
template <typename T>
void call_traits_test<T, true>::assert_construct(typename boost::call_traits<T>::param_type val)
{
//
// this is to check that the call_traits assertions are valid:
T t;
value_type v(t);
value_type v5(val);
reference r = t;
const_reference cr = t;
reference r2 = r;
#ifndef __BORLANDC__
// C++ Builder buglet:
const_reference cr2 = r;
#endif
param_type p(t);
value_type v2(v);
const_reference cr3 = cr;
value_type v3(r);
value_type v4(p);
param_type p2(v);
param_type p3(r);
param_type p4(p);
unused_variable(v2);
unused_variable(v3);
unused_variable(v4);
unused_variable(v5);
#ifndef __BORLANDC__
unused_variable(r2);
unused_variable(cr2);
#endif
unused_variable(cr3);
unused_variable(p2);
unused_variable(p3);
unused_variable(p4);
}
#endif //BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
//
// now check call_traits assertions by instantiating call_traits_test:
template struct call_traits_test<int>;
template struct call_traits_test<const int>;
template struct call_traits_test<int*>;
#if defined(BOOST_MSVC6_MEMBER_TEMPLATES)
template struct call_traits_test<int&>;
template struct call_traits_test<const int&>;
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(__SUNPRO_CC)
template struct call_traits_test<int[2], true>;
#endif
#endif
| 35.660287
| 135
| 0.69254
|
shreyasvj25
|
44aa3fbd0c080d40d8dbf27fabe522e18fa6f5f3
| 4,499
|
cpp
|
C++
|
tools/map_maker/test_helper/src/StringTestHelper.cpp
|
seowwj/map
|
2afacd50e1b732395c64b1884ccfaeeca0040ee7
|
[
"MIT"
] | 61
|
2019-12-19T20:57:24.000Z
|
2022-03-29T15:20:51.000Z
|
tools/map_maker/test_helper/src/StringTestHelper.cpp
|
seowwj/map
|
2afacd50e1b732395c64b1884ccfaeeca0040ee7
|
[
"MIT"
] | 54
|
2020-04-05T05:32:47.000Z
|
2022-03-15T18:42:33.000Z
|
tools/map_maker/test_helper/src/StringTestHelper.cpp
|
seowwj/map
|
2afacd50e1b732395c64b1884ccfaeeca0040ee7
|
[
"MIT"
] | 31
|
2019-12-20T07:37:39.000Z
|
2022-03-16T13:06:16.000Z
|
// ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// Copyright (C) 2017-2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
//
// ----------------- END LICENSE BLOCK -----------------------------------
#include "ad/map/maker/test_helper/StringTestHelper.hpp"
#include <stdio.h>
namespace ad {
namespace map {
namespace maker {
namespace test_helper {
static bool useColorForComparison{false};
/* the color mode has to be set at least once
* Either this was done by user-code (which called setColorMode)
* or from testStringAndPrintDifference
*/
static bool colorModeInitiallySet{false};
static void setInitialColorMode()
{
if (!colorModeInitiallySet)
{
setColorMode(ColorMode::On);
}
}
static void adustColorModeForConsole()
{
if (useColorForComparison)
{
const char *term = getenv("TERM");
if (term)
{
// if it starts with 'xterm' we assume that is supports color
if ((term[0] == 'x') && (term[1] == 't') && (term[2] == 'e') && (term[3] == 'r') && (term[4] == 'm'))
{
return;
}
}
// turn off coloring if the console doesn't support this
useColorForComparison = false;
}
}
void setColorMode(ColorMode mode)
{
colorModeInitiallySet = true;
useColorForComparison = (mode == ColorMode::On);
adustColorModeForConsole();
}
void turnColorOn(const char *const color)
{
if (useColorForComparison)
{
printf("%s", color); // turn color on
}
}
void turnColorOff()
{
if (useColorForComparison)
{
printf("\x1b[0m"); // turn to normal
}
}
size_t getMaxLengthOfStrings(std::string const &s1, std::string const &s2)
{
size_t len = s1.length();
if (s2.length() < len)
{
len = s2.length();
}
return len;
}
void printDifferenceOfString(std::string const &toPrint,
std::string const &toCompare,
const char *const color,
size_t const len)
{
for (size_t i = 0; i < len; i++)
{
if (toPrint[i] != toCompare[i])
{
turnColorOn(color);
}
printf("%c", toPrint[i]);
if (toPrint[i] != toCompare[i])
{
turnColorOff();
}
}
}
void printStringDifferences(std::string const &expected, std::string const &actual)
{
const size_t len = getMaxLengthOfStrings(expected, actual);
if (expected == actual)
{
return;
}
if (len > 0)
{
printf("Expected:\n");
printDifferenceOfString(expected, actual, "\x1b[32m", len);
printf("\nActual:\n");
printDifferenceOfString(actual, expected, "\x1b[31m", len);
}
else
{
printf("Either exected (size: %lu) or actual (size: %lu) is empty\n", expected.size(), actual.size());
}
}
// make this a macro similar to gtest ASSERT_STREQ, maybe ASSERT_STREQ_PRINT_DIFF
bool testStringAndPrintDifference(std::string const &expected, std::string const &actual)
{
if (expected != actual)
{
setInitialColorMode();
printStringDifferences(expected, actual);
// print missing parts if strings have different sizes
if (expected.length() != actual.length())
{
if (expected.size() > actual.size())
{
printf("\nMissing part from expected:\n");
turnColorOn("\x1b[32m");
if (actual.size() > 0)
{
printf("%s", &expected.c_str()[actual.size()]);
}
else
{
printf("%s", expected.c_str());
}
turnColorOff();
}
else
{
printf("\nAdditional part from actual:\n");
turnColorOn("\x1b[31m");
if (expected.size() > 0)
{
printf("%s", &actual.c_str()[expected.size()]);
}
else
{
printf("%s", actual.c_str());
}
turnColorOff();
}
printf("\n");
}
return false;
}
return true;
}
bool readFile(char const *fileName, std::string &fileContent)
{
FILE *input = fopen(fileName, "r");
if (input == nullptr)
{
return false;
}
if (fseek(input, 0, SEEK_END) != 0)
{
return false;
}
size_t fileSize = static_cast<size_t>(ftell(input));
rewind(input);
char *content = new char[fileSize + 1];
size_t readCount = fread(content, sizeof(char), fileSize, input);
if (readCount != fileSize)
{
delete[] content;
content = nullptr;
return false;
}
content[fileSize] = 0;
fileContent.assign(content);
return true;
}
} // namespace test_helper
} // namespace maker
} // namespace map
} // namespace ad
| 22.053922
| 107
| 0.58613
|
seowwj
|
44aa9cf1340691f42635075713e82bcfdb942e00
| 1,003
|
hpp
|
C++
|
Engine/Graphics/FontHandler.hpp
|
artur-kink/nhns
|
bc1ccef4e4a9cba9047051d73202ee2b1482066f
|
[
"Apache-2.0"
] | null | null | null |
Engine/Graphics/FontHandler.hpp
|
artur-kink/nhns
|
bc1ccef4e4a9cba9047051d73202ee2b1482066f
|
[
"Apache-2.0"
] | null | null | null |
Engine/Graphics/FontHandler.hpp
|
artur-kink/nhns
|
bc1ccef4e4a9cba9047051d73202ee2b1482066f
|
[
"Apache-2.0"
] | null | null | null |
#ifndef _FONTHANDLER_
#define _FONTHANDLER_
#include <cstring>
#include "Types.hpp"
#include "Color.hpp"
#include "BaseRenderTarget.hpp"
#include "Utilities/FileHandler.hpp"
#ifdef _PC_
#include <SFML/Graphics.hpp>
#endif
/**
* Class used to draw fonts.
* The FontHandler is designed to use only one font,
* if more fonts are needed then separate FontHandlers
* should be initialized.
*/
class FontHandler{
private:
/** Name of font. */
char fontName[25];
/** Is the font loaded and ready to use. */
bool initialized;
/** Size of font. */
byte fontSize;
/** Font color. */
Color color;
public:
#ifdef _PC_
/** SFML Font implementation. */
sf::Font font;
#endif
FontHandler();
bool loadFont(const char* name);
unsigned short getStringWidth(const char* str);
void setFontSize(byte size);
void setFontColor(Color color);
#ifdef _PC_
void drawString(sf::RenderTarget& dst, RenderObject& obj, const char* str);
#endif
};
#endif
| 18.924528
| 79
| 0.678963
|
artur-kink
|
44ad1bf3102a5861df1af96ac4881741c9f3b3ea
| 1,753
|
hpp
|
C++
|
src/optimization/models/NNLS/ADMM.hpp
|
justusc/Elemental
|
145ccb28411f3f0c65ca30ecea776df33297e4ff
|
[
"BSD-3-Clause"
] | null | null | null |
src/optimization/models/NNLS/ADMM.hpp
|
justusc/Elemental
|
145ccb28411f3f0c65ca30ecea776df33297e4ff
|
[
"BSD-3-Clause"
] | null | null | null |
src/optimization/models/NNLS/ADMM.hpp
|
justusc/Elemental
|
145ccb28411f3f0c65ca30ecea776df33297e4ff
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2009-2015, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"
namespace El {
namespace nnls {
// Transform each problem
//
// min || A x - b ||_2
// s.t. x >= 0
//
// into the explicit QP
//
// min (1/2) x^T (A^T A) x + (-A^T b)^T x
// s.t. x >= 0
//
// and solve the sequence of problems simultaneously with ADMM.
//
template<typename Real>
Int ADMM
( const Matrix<Real>& A, const Matrix<Real>& B, Matrix<Real>& X,
const qp::box::ADMMCtrl<Real>& ctrl )
{
DEBUG_ONLY(CSE cse("nnls::ADMM"))
if( IsComplex<Real>::val )
LogicError("The datatype was assumed to be real");
const Real maxReal = std::numeric_limits<Real>::max();
Matrix<Real> Q, C;
Herk( LOWER, ADJOINT, Real(1), A, Q );
Gemm( ADJOINT, NORMAL, Real(-1), A, B, C );
return qp::box::ADMM( Q, C, Real(0), maxReal, X, ctrl );
}
template<typename Real>
Int ADMM
( const AbstractDistMatrix<Real>& APre, const AbstractDistMatrix<Real>& B,
AbstractDistMatrix<Real>& X,
const qp::box::ADMMCtrl<Real>& ctrl )
{
DEBUG_ONLY(CSE cse("nnls::ADMM"))
if( IsComplex<Real>::val )
LogicError("The datatype was assumed to be real");
const Real maxReal = std::numeric_limits<Real>::max();
auto APtr = ReadProxy<Real,MC,MR>( &APre );
auto& A = *APtr;
DistMatrix<Real> Q(A.Grid()), C(A.Grid());
Herk( LOWER, ADJOINT, Real(1), A, Q );
Gemm( ADJOINT, NORMAL, Real(-1), A, B, C );
return qp::box::ADMM( Q, C, Real(0), maxReal, X, ctrl );
}
} // namespace nnls
} // namespace El
| 26.164179
| 75
| 0.617228
|
justusc
|
44ade3c2f3c34f4e78555be6d489cf5c3df1bf46
| 866
|
hpp
|
C++
|
libs/boost_1_72_0/boost/type_erasure/config.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/type_erasure/config.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/type_erasure/config.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
// Boost.TypeErasure library
//
// Copyright 2011 Steven Watanabe
//
// Distributed under the Boost Software License Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// $Id$
#ifndef BOOST_TYPE_ERASURE_CONFIG_HPP_INCLUDED
#define BOOST_TYPE_ERASURE_CONFIG_HPP_INCLUDED
#ifndef BOOST_TYPE_ERASURE_MAX_FUNCTIONS
/** The maximum number of functions that an @ref boost::type_erasure::any "any"
* can have. */
#define BOOST_TYPE_ERASURE_MAX_FUNCTIONS 50
#endif
#ifndef BOOST_TYPE_ERASURE_MAX_ARITY
/** The maximum number of arguments that functions in the library support. */
#define BOOST_TYPE_ERASURE_MAX_ARITY 5
#endif
#ifndef BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE
/** The maximum number of elements in a @ref boost::type_erasure::tuple "tuple".
*/
#define BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE 5
#endif
#endif
| 28.866667
| 80
| 0.794457
|
henrywarhurst
|
44ae27d2b61165557a78299577983cafe1c8bf5b
| 2,339
|
cpp
|
C++
|
server/src/session.cpp
|
silverthreadk/Mafia2
|
275f7e9fb63a98bcb5781c4d388a63da16a63213
|
[
"BSL-1.0"
] | null | null | null |
server/src/session.cpp
|
silverthreadk/Mafia2
|
275f7e9fb63a98bcb5781c4d388a63da16a63213
|
[
"BSL-1.0"
] | null | null | null |
server/src/session.cpp
|
silverthreadk/Mafia2
|
275f7e9fb63a98bcb5781c4d388a63da16a63213
|
[
"BSL-1.0"
] | null | null | null |
#include "session.h"
#include <memory>
#include <boost/lexical_cast.hpp>
#include "room.h"
#include "player.h"
#include "request_handler.h"
Session::Session(boost::asio::ip::tcp::socket socket, const Room& room)
: socket_(std::move(socket)),
room_(const_cast<Room&>(room)),
player_(std::make_shared<Player>(*this, room_, boost::lexical_cast<std::string>(socket_.remote_endpoint()))) {
}
void Session::start() {
room_.join(shared_from_this());
do_read_header();
}
void Session::deliver(const Message& msg) {
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress) {
do_write();
}
}
void Session::do_read_header() {
auto self(shared_from_this());
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), Message::kHeaderLength),
[this, self](boost::system::error_code ec, std::size_t /*length*/) {
if (!ec && read_msg_.decode_header()) {
do_read_body();
} else {
if (room_.exist(shared_from_this())) {
player_->leave();
room_.leave(shared_from_this());
}
}
});
}
void Session::do_read_body() {
auto self(shared_from_this());
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
[this, self](boost::system::error_code ec, std::size_t /*length*/) {
if (!ec) {
RequestHandler::handleRequest(read_msg_, player_);
do_read_header();
} else {
if (room_.exist(shared_from_this())) {
player_->leave();
room_.leave(shared_from_this());
}
}
});
}
void Session::do_write() {
auto self(shared_from_this());
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(),
write_msgs_.front().length()),
[this, self](boost::system::error_code ec, std::size_t /*length*/) {
if (!ec) {
write_msgs_.pop_front();
if (!write_msgs_.empty()) {
do_write();
}
} else {
if (room_.exist(shared_from_this())) {
player_->leave();
room_.leave(shared_from_this());
}
}
});
}
| 28.52439
| 114
| 0.567336
|
silverthreadk
|
44af582b4fe1df8f558f26ca56c19b8527c8a82f
| 9,382
|
cpp
|
C++
|
fourr_kazerounian_controller/src/fourr_kazerounian_controller.cpp
|
unisa-acg/moveit_dp_redundancy_resolution
|
37f2f7bd3d786bc7d5ce0dde9d69772cd65b041e
|
[
"BSD-3-Clause"
] | 3
|
2020-12-31T02:46:15.000Z
|
2021-05-31T12:05:58.000Z
|
fourr_kazerounian_controller/src/fourr_kazerounian_controller.cpp
|
unisa-acg/moveit_dp_redundancy_resolution
|
37f2f7bd3d786bc7d5ce0dde9d69772cd65b041e
|
[
"BSD-3-Clause"
] | null | null | null |
fourr_kazerounian_controller/src/fourr_kazerounian_controller.cpp
|
unisa-acg/moveit_dp_redundancy_resolution
|
37f2f7bd3d786bc7d5ce0dde9d69772cd65b041e
|
[
"BSD-3-Clause"
] | 2
|
2020-11-14T11:33:13.000Z
|
2021-08-12T05:36:53.000Z
|
/*********************************************************************************
* Copyright (c) 2018, Università degli Studi di Salerno, ALTEC S.p.A.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*********************************************************************************/
/* -------------------------------------------------------------------
*
* This module has been developed as part of a collaboration between
* the Automatic Control Group @ UNISA and ALTEC.
*
* Title: fourr_kazerounian_controller.cpp
* Author: Enrico Ferrentino
* Org.: UNISA - Automatic Control Group
* Date: Jul 16, 2018
*
* This file implements a ROS node to control the 4R planar
* manipulator first proposed by Kazerounian & Wang, whose
* configuration is included in the ROS module
* fourr_kazerounian_moveit_config. It follows the model of the
* move_group_interface_tutorial.
*
* -------------------------------------------------------------------
*/
#include <ros/ros.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/move_group_interface/move_group_interface.h>
#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_visual_tools/moveit_visual_tools.h>
#include <geometry_msgs/Pose.h>
#include <moveit_dp_redundancy_resolution/workspace_trajectory.h>
#include <moveit_dp_redundancy_resolution/dp_redundancy_resolution_capability.h>
int main(int argc, char** argv)
{
// Initializing the node and the move_grou interface
ros::init(argc, argv, "fourr_kazerounian_controller");
ros::NodeHandle node_handle;
/*
* The async spinner spawns a new thread in charge of calling callbacks
* when needed. Uncomment the lines below if, as instance, you need to
* ask for the robot state and expect an answer before the time expires.
*/
ros::AsyncSpinner spinner(1);
spinner.start();
static const std::string PLANNING_GROUP = "fourr_planar_arm";
static const std::string NON_REDUNDANT_PLANNING_GROUP = "q2_q3_q4";
moveit::planning_interface::MoveGroupInterface move_group(PLANNING_GROUP);
const robot_state::JointModelGroup* joint_model_group = move_group.getCurrentState()->getJointModelGroup(PLANNING_GROUP);
ROS_INFO_NAMED("main", "Reference frame: %s", move_group.getPlanningFrame().c_str());
ROS_INFO_NAMED("main", "End effector link: %s", move_group.getEndEffectorLink().c_str());
// Loading the trajectory from the Parameter Server and creating a WorkspaceTrajectory object
std::string trajectory_name;
std::vector<double> time;
std::vector<double> x;
std::vector<double> y;
std::vector<double> z;
std::vector<double> roll;
std::vector<double> pitch;
std::vector<double> yaw;
node_handle.getParam("/trajectory/name", trajectory_name);
node_handle.getParam("/trajectory/time", time);
node_handle.getParam("/trajectory/x", x);
node_handle.getParam("/trajectory/y", y);
node_handle.getParam("/trajectory/z", z);
node_handle.getParam("/trajectory/roll", roll);
node_handle.getParam("/trajectory/pitch", pitch);
node_handle.getParam("/trajectory/yaw", yaw);
moveit_dp_redundancy_resolution::WorkspaceTrajectory ws_trajectory(trajectory_name, time, x, y, z, roll, pitch, yaw);
ROS_INFO_NAMED("main", "WorkspaceTrajectory object created with %lu waypoints", time.size());
namespace rvt = rviz_visual_tools;
moveit_visual_tools::MoveItVisualTools visual_tools("base_link");
visual_tools.deleteAllMarkers();
visual_tools.loadRemoteControl();
visual_tools.publishPath(ws_trajectory.getWaypoints(), rvt::LIME_GREEN, rvt::SMALL);
visual_tools.trigger();
//visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to start planning");
// Planning with dynamic programming redundancy resolution
ros::ServiceClient dp_redundancy_resolution_service
= node_handle.serviceClient<moveit_dp_redundancy_resolution_msgs::GetOptimizedJointsTrajectory>(move_group::DP_REDUNDANCY_RESOLUTION_SERVICE_NAME);
moveit_dp_redundancy_resolution_msgs::GetOptimizedJointsTrajectoryRequest req;
moveit_dp_redundancy_resolution_msgs::GetOptimizedJointsTrajectoryResponse res;
moveit_dp_redundancy_resolution_msgs::WorkspaceTrajectory ws_trajectory_msg;
ws_trajectory.getWorkspaceTrajectoryMsg(ws_trajectory_msg);
req.ws_trajectory = ws_trajectory_msg;
req.planning_group_name = PLANNING_GROUP;
req.non_redundant_group_name = NON_REDUNDANT_PLANNING_GROUP;
req.redundancy_parameter_samples = 1440;
req.redundancy_parameters.push_back("joint1");
dp_redundancy_resolution_service.call(req, res);
visual_tools.publishTrajectoryLine(res.solution, joint_model_group);
visual_tools.trigger();
visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue planning");
// Planning to a pose goal
/*
* Uncomment these instructions to see how the KDL kinematics solver fails in
* finding a solution for a < 6 DOF manipulator
*/
/*
geometry_msgs::Pose target_pose1;
target_pose1.position.x = 5;
target_pose1.position.y = 5;
target_pose1.position.z = 0.4;
move_group.setPoseTarget(target_pose1);
moveit::planning_interface::MoveGroupInterface::Plan my_plan;
bool success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
ROS_INFO_NAMED("main", "Visualizing plan 1 (pose goal) %s", success ? "" : "FAILED");
ROS_INFO_NAMED("main", "Visualizing plan 1 as trajectory line");
visual_tools.publishAxisLabeled(target_pose1, "pose1");
visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group);
visual_tools.trigger();
visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue planning");
*/
// Planning to a joint space goal
moveit::core::RobotStatePtr current_state = move_group.getCurrentState();
std::vector<double> joint_group_positions;
current_state->copyJointGroupPositions(joint_model_group, joint_group_positions);
joint_group_positions[0] = -1.0; // radians
move_group.setJointValueTarget(joint_group_positions);
moveit::planning_interface::MoveGroupInterface::Plan my_plan;
bool success = (move_group.plan(my_plan) == moveit::planning_interface::MoveItErrorCode::SUCCESS);
ROS_INFO_NAMED("main", "Visualizing plan 2 (joint space goal) %s", success ? "" : "FAILED");
visual_tools.deleteAllMarkers();
visual_tools.publishTrajectoryLine(my_plan.trajectory_, joint_model_group);
visual_tools.trigger();
visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to continue planning");
// Planning a joint space path starting from workspace waypoints
robot_state::RobotState start_state(*move_group.getCurrentState());
geometry_msgs::Pose start_pose = ws_trajectory.getWaypoints()[0];
start_state.setFromIK(joint_model_group, start_pose);
move_group.setStartState(start_state);
moveit_msgs::RobotTrajectory trajectory;
const double jump_threshold = 0;
const double eef_step = 0.01;
double fraction = move_group.computeCartesianPath(ws_trajectory.getWaypoints(), eef_step, jump_threshold, trajectory, false);
ROS_INFO_NAMED("main", "Visualizing plan (%.2f%% achieved)", fraction * 100.0);
visual_tools.deleteAllMarkers();
visual_tools.publishPath(ws_trajectory.getWaypoints(), rvt::LIME_GREEN, rvt::SMALL);
// for (std::size_t i = 0; i < time.size(); ++i)
// visual_tools.publishAxisLabeled(ws_trajectory.getWaypoints()[i], "pt" + std::to_string(i), rvt::SMALL);
visual_tools.publishTrajectoryLine(trajectory, joint_model_group);
visual_tools.trigger();
visual_tools.prompt("Press 'next' in the RvizVisualToolsGui window to terminate the node");
ros::shutdown();
return 0;
}
| 42.071749
| 155
| 0.734492
|
unisa-acg
|
44b1e1418cbd084a974188fe6e79ef46286dee77
| 5,639
|
cpp
|
C++
|
src/wrapper/store/storehelper.cpp
|
microshine/trusted-crypto
|
22a6496bd390ebe2ed516a15636d911fae4c6407
|
[
"Apache-2.0"
] | null | null | null |
src/wrapper/store/storehelper.cpp
|
microshine/trusted-crypto
|
22a6496bd390ebe2ed516a15636d911fae4c6407
|
[
"Apache-2.0"
] | null | null | null |
src/wrapper/store/storehelper.cpp
|
microshine/trusted-crypto
|
22a6496bd390ebe2ed516a15636d911fae4c6407
|
[
"Apache-2.0"
] | 1
|
2020-07-01T16:32:57.000Z
|
2020-07-01T16:32:57.000Z
|
#include "../stdafx.h"
#include "storehelper.h"
Handle<PkiItemCollection> Provider::getProviderItemCollection(){
LOGGER_FN();
return this->providerItemCollection;
}
ProviderCollection::ProviderCollection(){
LOGGER_FN();
_items = std::vector<Handle<Provider> >();
}
ProviderCollection::~ProviderCollection(){
LOGGER_FN();
}
Handle<Provider> ProviderCollection::items(int index){
LOGGER_FN();
return _items.at(index);
}
int ProviderCollection::length(){
LOGGER_FN();
return _items.size();
}
void ProviderCollection::push(Handle<Provider> v){
LOGGER_FN();
_items.push_back(v);
}
PkiItem::PkiItem(){
LOGGER_FN();
type = new std::string("");
provider = new std::string("");
category = new std::string("");
hash = new std::string("");
uri = new std::string("");
format = new std::string("");
certSubjectName = new std::string("");
certSubjectFriendlyName = new std::string("");
certIssuerName = new std::string("");
certIssuerFriendlyName = new std::string("");
certNotBefore = new std::string("");
certNotAfter = new std::string("");
certSerial = new std::string("");
certKey = new std::string("");
certOrganizationName = new std::string("");
certSignatureAlgorithm = new std::string("");
csrSubjectName = new std::string("");
csrSubjectFriendlyName = new std::string("");
csrKey = new std::string("");
crlIssuerName = new std::string("");
crlIssuerFriendlyName = new std::string("");
crlLastUpdate = new std::string("");
crlNextUpdate = new std::string("");
keyEncrypted = false;
}
void PkiItem::setFormat(Handle<std::string> format){
LOGGER_FN();
this->format = format;
}
void PkiItem::setType(Handle<std::string> type){
LOGGER_FN();
this->type = type;
}
void PkiItem::setProvider(Handle<std::string> provider){
LOGGER_FN();
this->provider = provider;
}
void PkiItem::setCategory(Handle<std::string> category){
LOGGER_FN();
this->category = category;
}
void PkiItem::setURI(Handle<std::string> uri){
LOGGER_FN();
this->uri = uri;
}
void PkiItem::setHash(Handle<std::string> hash){
LOGGER_FN();
this->hash = hash;
}
void PkiItem::setSubjectName(Handle<std::string> subjectName){
LOGGER_FN();
this->certSubjectName = subjectName;
this->csrSubjectName = subjectName;
}
void PkiItem::setSubjectFriendlyName(Handle<std::string> subjectFriendlyName){
LOGGER_FN();
this->certSubjectFriendlyName = subjectFriendlyName;
this->csrSubjectFriendlyName = subjectFriendlyName;
}
void PkiItem::setIssuerName(Handle<std::string> issuerName){
LOGGER_FN();
this->certIssuerName = issuerName;
this->crlIssuerName = issuerName;
}
void PkiItem::setIssuerFriendlyName(Handle<std::string> issuerFriendlyName){
LOGGER_FN();
this->certIssuerFriendlyName = issuerFriendlyName;
this->crlIssuerFriendlyName = issuerFriendlyName;
}
void PkiItem::setSerial(Handle<std::string> serial){
LOGGER_FN();
this->certSerial = serial;
}
void PkiItem::setNotBefore(Handle<std::string> notBefore){
LOGGER_FN();
this->certNotBefore = notBefore;
}
void PkiItem::setNotAfter(Handle<std::string> notAfter){
LOGGER_FN();
this->certNotAfter = notAfter;
}
void PkiItem::setLastUpdate(Handle<std::string> lastUpdate){
LOGGER_FN();
this->crlLastUpdate = lastUpdate;
}
void PkiItem::setNextUpdate(Handle<std::string> nextUpdate){
LOGGER_FN();
this->crlNextUpdate = nextUpdate;
}
void PkiItem::setKey(Handle<std::string> keyid){
LOGGER_FN();
this->certKey = keyid;
this->csrKey = keyid;
}
void PkiItem::setKeyEncypted(bool enc){
LOGGER_FN();
this->keyEncrypted = enc;
}
void PkiItem::setOrganizationName(Handle<std::string> organizationName){
LOGGER_FN();
this->certOrganizationName = organizationName;
}
void PkiItem::setSignatureAlgorithm(Handle<std::string> signatureAlgorithm){
LOGGER_FN();
this->certSignatureAlgorithm = signatureAlgorithm;
}
PkiItemCollection::PkiItemCollection(){
LOGGER_FN();
_items = std::vector<PkiItem>();
}
PkiItemCollection::~PkiItemCollection(){
LOGGER_FN();
}
Handle<PkiItem> PkiItemCollection::items(int index){
LOGGER_FN();
return new PkiItem(_items.at(index));
}
int PkiItemCollection::length(){
LOGGER_FN();
return _items.size();
}
void PkiItemCollection::push(Handle<PkiItem> v){
LOGGER_FN();
_items.push_back((*v.operator->()));
}
void PkiItemCollection::push(PkiItem &v){
LOGGER_FN();
_items.push_back(v);
}
Filter::Filter(){
LOGGER_FN();
types = std::vector<Handle<std::string>>();
providers = std::vector<Handle<std::string>>();
categorys = std::vector<Handle<std::string>>();
isValid = true;
}
void Filter::setType(Handle<std::string> type){
LOGGER_FN();
this->types.push_back(type);
}
void Filter::setProvider(Handle<std::string> provider){
LOGGER_FN();
this->providers.push_back(provider);
}
void Filter::setCategory(Handle<std::string> category){
LOGGER_FN();
this->categorys.push_back(category);
}
void Filter::setHash(Handle<std::string> hash){
LOGGER_FN();
this->hash = hash;
}
void Filter::setSubjectName(Handle<std::string> subjectName){
LOGGER_FN();
this->subjectName = subjectName;
}
void Filter::setSubjectFriendlyName(Handle<std::string> subjectFriendlyName){
LOGGER_FN();
this->subjectFriendlyName = subjectFriendlyName;
}
void Filter::setIssuerName(Handle<std::string> issuerName){
LOGGER_FN();
this->issuerName = issuerName;
}
void Filter::setIssuerFriendlyName(Handle<std::string> issuerFriendlyName){
LOGGER_FN();
this->issuerFriendlyName = issuerFriendlyName;
}
void Filter::setSerial(Handle<std::string> serial){
LOGGER_FN();
this->serial = serial;
}
void Filter::setIsValid(bool isValid){
LOGGER_FN();
this->isValid = isValid;
}
| 19.311644
| 78
| 0.720695
|
microshine
|
44b3354599055ce7c9ea0b5e90a4a44deaa259cc
| 187
|
hpp
|
C++
|
cegui/src/ScriptModules/Python/bindings/output/CEGUI/Image.pypp.hpp
|
OpenTechEngine-Libraries/CEGUI
|
6f00952d31f318f9482766d1ad2206cb540a78b9
|
[
"MIT"
] | 257
|
2020-01-03T10:13:29.000Z
|
2022-03-26T14:55:12.000Z
|
cegui/src/ScriptModules/Python/bindings/output/CEGUI/Image.pypp.hpp
|
OpenTechEngine-Libraries/CEGUI
|
6f00952d31f318f9482766d1ad2206cb540a78b9
|
[
"MIT"
] | 116
|
2020-01-09T18:13:13.000Z
|
2022-03-15T18:32:02.000Z
|
cegui/src/ScriptModules/Python/bindings/output/CEGUI/Image.pypp.hpp
|
OpenTechEngine-Libraries/CEGUI
|
6f00952d31f318f9482766d1ad2206cb540a78b9
|
[
"MIT"
] | 58
|
2020-01-09T03:07:02.000Z
|
2022-03-22T17:21:36.000Z
|
// This file has been generated by Py++.
#ifndef Image_hpp__pyplusplus_wrapper
#define Image_hpp__pyplusplus_wrapper
void register_Image_class();
#endif//Image_hpp__pyplusplus_wrapper
| 20.777778
| 40
| 0.834225
|
OpenTechEngine-Libraries
|
44b4580632d37867ab5ba5420a10c8d9e90df25b
| 851
|
cpp
|
C++
|
src/main.cpp
|
niko-niko-ni/eme
|
5c3718731464f67a3a03efe7d6012375701c4538
|
[
"MIT"
] | 3
|
2020-08-11T01:27:29.000Z
|
2021-02-10T04:31:13.000Z
|
src/main.cpp
|
niko-niko-ni/eme
|
5c3718731464f67a3a03efe7d6012375701c4538
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
niko-niko-ni/eme
|
5c3718731464f67a3a03efe7d6012375701c4538
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <iostream>
#include "types.h"
#include "symbol.h"
#include "token.h"
#include "lexer.h"
#include "statement_parser.h"
#include "ast.h"
#include "ast_parser.h"
int main() {
try {
printf("main block started. moving on to lexing...\n");
Token_Linked_List tokens = lex_file((char*)"./examples/basicstatements.eme");
printf("lexer finished. moving on to declaring list of statements...\n");
Token_Linked_List statements;
printf("list of statements declared. Moving on to parsing statements...\n");
parse_statements(&statements, tokens);
printf("parsed statements. printing tokens...");
print_all_tokens_after(*statements.first);
Ast_Node *root = parse_statements_to_ast(statements);
print_node(*root);
} catch(const std::exception& e) {
printf("Error: %s\n", e.what());
}
}
| 27.451613
| 81
| 0.692127
|
niko-niko-ni
|
44b5dc9f4394158bd5620d96ac75b751757d0878
| 16,107
|
cpp
|
C++
|
src/interaction/navigationhandler.cpp
|
PhysicsTeacher13/OpenSpace
|
dd007461be4248b71fc465eaede4808a6c905df5
|
[
"MIT"
] | null | null | null |
src/interaction/navigationhandler.cpp
|
PhysicsTeacher13/OpenSpace
|
dd007461be4248b71fc465eaede4808a6c905df5
|
[
"MIT"
] | null | null | null |
src/interaction/navigationhandler.cpp
|
PhysicsTeacher13/OpenSpace
|
dd007461be4248b71fc465eaede4808a6c905df5
|
[
"MIT"
] | null | null | null |
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <openspace/interaction/navigationhandler.h>
#include <openspace/engine/globals.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/scripting/lualibrary.h>
#include <openspace/interaction/orbitalnavigator.h>
#include <openspace/interaction/keyframenavigator.h>
#include <openspace/interaction/inputstate.h>
#include <openspace/network/parallelpeer.h>
#include <openspace/util/camera.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <fstream>
namespace {
constexpr const char* _loggerCat = "NavigationHandler";
constexpr const char* KeyAnchor = "Anchor";
constexpr const char* KeyAim = "Aim";
constexpr const char* KeyPosition = "Position";
constexpr const char* KeyRotation = "Rotation";
constexpr const openspace::properties::Property::PropertyInfo KeyFrameInfo = {
"UseKeyFrameInteraction",
"Use keyframe interaction",
"If this is set to 'true' the entire interaction is based off key frames rather "
"than using the mouse interaction."
};
} // namespace
#include "navigationhandler_lua.inl"
namespace openspace::interaction {
NavigationHandler::NavigationHandler()
: properties::PropertyOwner({ "NavigationHandler" })
, _useKeyFrameInteraction(KeyFrameInfo, false)
{
_inputState = std::make_unique<InputState>();
_orbitalNavigator = std::make_unique<OrbitalNavigator>();
_keyframeNavigator = std::make_unique<KeyframeNavigator>();
// Add the properties
addProperty(_useKeyFrameInteraction);
addPropertySubOwner(*_orbitalNavigator);
}
NavigationHandler::~NavigationHandler() {} // NOLINT
void NavigationHandler::initialize() {
global::parallelPeer.connectionEvent().subscribe(
"NavigationHandler",
"statusChanged",
[this]() {
_useKeyFrameInteraction = (global::parallelPeer.status() ==
ParallelConnection::Status::ClientWithHost);
}
);
}
void NavigationHandler::deinitialize() {
global::parallelPeer.connectionEvent().unsubscribe("NavigationHandler");
}
void NavigationHandler::setCamera(Camera* camera) {
_camera = camera;
_orbitalNavigator->setCamera(camera);
}
const OrbitalNavigator& NavigationHandler::orbitalNavigator() const {
return *_orbitalNavigator;
}
OrbitalNavigator& NavigationHandler::orbitalNavigator() {
return *_orbitalNavigator;
}
KeyframeNavigator& NavigationHandler::keyframeNavigator() const {
return *_keyframeNavigator;
}
bool NavigationHandler::isKeyFrameInteractionEnabled() const {
return _useKeyFrameInteraction;
}
float NavigationHandler::interpolationTime() const {
return _orbitalNavigator->retargetInterpolationTime();
}
void NavigationHandler::setInterpolationTime(float durationInSeconds) {
_orbitalNavigator->setRetargetInterpolationTime(durationInSeconds);
}
void NavigationHandler::updateCamera(double deltaTime) {
ghoul_assert(_inputState != nullptr, "InputState must not be nullptr");
ghoul_assert(_camera != nullptr, "Camera must not be nullptr");
if (_cameraUpdatedFromScript) {
_cameraUpdatedFromScript = false;
}
else if ( ! _playbackModeEnabled ) {
if (_camera) {
if (_useKeyFrameInteraction) {
_keyframeNavigator->updateCamera(*_camera, _playbackModeEnabled);
}
else {
_orbitalNavigator->updateStatesFromInput(*_inputState, deltaTime);
_orbitalNavigator->updateCameraStateFromStates(deltaTime);
}
}
}
}
void NavigationHandler::setEnableKeyFrameInteraction() {
_useKeyFrameInteraction = true;
}
void NavigationHandler::setDisableKeyFrameInteraction() {
_useKeyFrameInteraction = false;
}
void NavigationHandler::triggerPlaybackStart() {
_playbackModeEnabled = true;
}
void NavigationHandler::stopPlayback() {
_playbackModeEnabled = false;
}
Camera* NavigationHandler::camera() const {
return _camera;
}
const InputState& NavigationHandler::inputState() const {
return *_inputState;
}
void NavigationHandler::mouseButtonCallback(MouseButton button, MouseAction action) {
_inputState->mouseButtonCallback(button, action);
}
void NavigationHandler::mousePositionCallback(double x, double y) {
_inputState->mousePositionCallback(x, y);
}
void NavigationHandler::mouseScrollWheelCallback(double pos) {
_inputState->mouseScrollWheelCallback(pos);
}
void NavigationHandler::keyboardCallback(Key key, KeyModifier modifier, KeyAction action)
{
_inputState->keyboardCallback(key, modifier, action);
}
void NavigationHandler::setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict)
{
bool readSuccessful = true;
std::string anchor;
std::string aim;
glm::dvec3 cameraPosition;
glm::dvec4 cameraRotation; // Need to read the quaternion as a vector first.
readSuccessful &= cameraDict.getValue(KeyAnchor, anchor);
readSuccessful &= cameraDict.getValue(KeyPosition, cameraPosition);
readSuccessful &= cameraDict.getValue(KeyRotation, cameraRotation);
cameraDict.getValue(KeyAim, aim); // Aim is not required
if (!readSuccessful) {
throw ghoul::RuntimeError(
"Position, Rotation and Focus need to be defined for camera dictionary."
);
}
// Set state
_orbitalNavigator->setAnchorNode(anchor);
_orbitalNavigator->setAimNode(aim);
_camera->setPositionVec3(cameraPosition);
_camera->setRotation(glm::dquat(
cameraRotation.x, cameraRotation.y, cameraRotation.z, cameraRotation.w));
}
ghoul::Dictionary NavigationHandler::cameraStateDictionary() {
glm::dvec3 cameraPosition;
glm::dquat quat;
glm::dvec4 cameraRotation;
cameraPosition = _camera->positionVec3();
quat = _camera->rotationQuaternion();
cameraRotation = glm::dvec4(quat.w, quat.x, quat.y, quat.z);
ghoul::Dictionary cameraDict;
cameraDict.setValue(KeyPosition, cameraPosition);
cameraDict.setValue(KeyRotation, cameraRotation);
cameraDict.setValue(KeyAnchor, _orbitalNavigator->anchorNode()->identifier());
if (_orbitalNavigator->aimNode()) {
cameraDict.setValue(KeyAim, _orbitalNavigator->aimNode()->identifier());
}
return cameraDict;
}
void NavigationHandler::saveCameraStateToFile(const std::string& filepath) {
if (!filepath.empty()) {
std::string fullpath = absPath(filepath);
LINFO(fmt::format("Saving camera position: {}", filepath));
ghoul::Dictionary cameraDict = cameraStateDictionary();
// TODO(abock): Should get the camera state as a dictionary and save the
// dictionary to a file in form of a lua state and not use ofstreams here.
std::ofstream ofs(fullpath.c_str());
glm::dvec3 p = _camera->positionVec3();
glm::dquat q = _camera->rotationQuaternion();
ofs << "return {" << std::endl;
ofs << " " << KeyAnchor << " = " << "\"" <<
_orbitalNavigator->anchorNode()->identifier() << "\""
<< "," << std::endl;
if (_orbitalNavigator->aimNode()) {
ofs << " " << KeyAim << " = " << "\"" <<
_orbitalNavigator->aimNode()->identifier() << "\""
<< "," << std::endl;
}
ofs << " " << KeyPosition << " = {"
<< std::to_string(p.x) << ", "
<< std::to_string(p.y) << ", "
<< std::to_string(p.z) << "}," << std::endl;
ofs << " " << KeyRotation << " = {"
<< std::to_string(q.w) << ", "
<< std::to_string(q.x) << ", "
<< std::to_string(q.y) << ", "
<< std::to_string(q.z) << "}," << std::endl;
ofs << "}"<< std::endl;
ofs.close();
}
}
void NavigationHandler::restoreCameraStateFromFile(const std::string& filepath) {
LINFO(fmt::format("Reading camera state from file: {}", filepath));
if (!FileSys.fileExists(filepath)) {
throw ghoul::FileNotFoundError(filepath, "CameraFilePath");
}
ghoul::Dictionary cameraDict;
try {
ghoul::lua::loadDictionaryFromFile(filepath, cameraDict);
setCameraStateFromDictionary(cameraDict);
_cameraUpdatedFromScript = true;
}
catch (ghoul::RuntimeError& e) {
LWARNING("Unable to set camera position");
LWARNING(e.message);
}
}
void NavigationHandler::setJoystickAxisMapping(int axis,
JoystickCameraStates::AxisType mapping,
JoystickCameraStates::AxisInvert shouldInvert,
JoystickCameraStates::AxisNormalize shouldNormalize)
{
_orbitalNavigator->joystickStates().setAxisMapping(
axis,
mapping,
shouldInvert,
shouldNormalize
);
}
JoystickCameraStates::AxisInformation
NavigationHandler::joystickAxisMapping(int axis) const
{
return _orbitalNavigator->joystickStates().axisMapping(axis);
}
void NavigationHandler::setJoystickAxisDeadzone(int axis, float deadzone) {
_orbitalNavigator->joystickStates().setDeadzone(axis, deadzone);
}
float NavigationHandler::joystickAxisDeadzone(int axis) const {
return _orbitalNavigator->joystickStates().deadzone(axis);
}
void NavigationHandler::bindJoystickButtonCommand(int button, std::string command,
JoystickAction action,
JoystickCameraStates::ButtonCommandRemote remote,
std::string documentation)
{
_orbitalNavigator->joystickStates().bindButtonCommand(
button,
std::move(command),
action,
remote,
std::move(documentation)
);
}
void NavigationHandler::clearJoystickButtonCommand(int button) {
_orbitalNavigator->joystickStates().clearButtonCommand(button);
}
std::vector<std::string> NavigationHandler::joystickButtonCommand(int button) const {
return _orbitalNavigator->joystickStates().buttonCommand(button);
}
scripting::LuaLibrary NavigationHandler::luaLibrary() {
return {
"navigation",
{
{
"setCameraState",
&luascriptfunctions::setCameraState,
{},
"object",
"Set the camera state"
},
{
"saveCameraStateToFile",
&luascriptfunctions::saveCameraStateToFile,
{},
"string",
"Save the current camera state to file"
},
{
"restoreCameraStateFromFile",
&luascriptfunctions::restoreCameraStateFromFile,
{},
"string",
"Restore the camera state from file"
},
{
"retargetAnchor",
&luascriptfunctions::retargetAnchor,
{},
"void",
"Reset the camera direction to point at the anchor node"
},
{
"retargetAim",
&luascriptfunctions::retargetAim,
{},
"void",
"Reset the camera direction to point at the aim node"
},
{
"bindJoystickAxis",
&luascriptfunctions::bindJoystickAxis,
{},
"int, axisType [, isInverted, isNormalized]",
"Binds the axis identified by the first argument to be used as the type "
"identified by the second argument. If 'isInverted' is 'true', the axis "
"value is inverted, if 'isNormalized' is true the axis value is "
"normalized from [-1, 1] to [0,1]."
},
{
"joystickAxis",
&luascriptfunctions::joystickAxis,
{},
"int",
"Returns the joystick axis information for the passed axis. The "
"information that is returned is the current axis binding as a string, "
"whether the values are inverted as bool, and whether the value are "
"normalized as a bool"
},
{
"setAxisDeadZone",
&luascriptfunctions::setJoystickAxisDeadzone,
{},
"int, float",
"Sets the deadzone for a particular joystick axis which means that any "
"input less than this value is completely ignored."
},
{
"bindJoystickButton",
&luascriptfunctions::bindJoystickButton,
{},
"int, string [, string, bool]",
"Binds a Lua script to be executed when the joystick button identified "
"by the first argument is triggered. The third argument determines when "
"the script should be executed, this defaults to 'pressed', which means "
"that the script is run when the user presses the button. The last "
"argument determines whether the command is going to be executable "
"locally or remotely. The latter being the default."
},
{
"clearJoystickButotn",
&luascriptfunctions::clearJoystickButton,
{},
"int",
"Removes all commands that are currently bound to the button identified "
"by the first argument"
},
{
"joystickButton",
&luascriptfunctions::joystickButton,
{},
"int",
"Returns the script that is currently bound to be executed when the "
"provided button is pressed"
}
}
};
}
} // namespace openspace::interaction
| 36.773973
| 90
| 0.592351
|
PhysicsTeacher13
|
44b659fdfcf335ad97f6a58480929bfab09662e5
| 1,802
|
cpp
|
C++
|
Data Structure/BinarySearchTree/lowest common ancestor.cpp
|
ShreyaDayma-cse/Contribute-to-HacktoberFest2021
|
6847aeb1c14c67f78b79f926af45e9ea1bdfda35
|
[
"MIT"
] | 2
|
2021-10-06T10:00:26.000Z
|
2021-10-06T10:00:30.000Z
|
Data Structure/BinarySearchTree/lowest common ancestor.cpp
|
ShreyaDayma-cse/Contribute-to-HacktoberFest2021
|
6847aeb1c14c67f78b79f926af45e9ea1bdfda35
|
[
"MIT"
] | null | null | null |
Data Structure/BinarySearchTree/lowest common ancestor.cpp
|
ShreyaDayma-cse/Contribute-to-HacktoberFest2021
|
6847aeb1c14c67f78b79f926af45e9ea1bdfda35
|
[
"MIT"
] | null | null | null |
// A recursive CPP program to find
// LCA of two nodes n1 and n2.
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node* left, *right;
};
/* Function to find LCA of n1 and n2.
The function assumes that both n1 and n2
are present in BST */
struct node *lca(struct node* root, int n1, int n2)
{
while (root != NULL)
{
// If both n1 and n2 are smaller than root,
// then LCA lies in left
if (root->data > n1 && root->data > n2)
root = root->left;
// If both n1 and n2 are greater than root,
// then LCA lies in right
else if (root->data < n1 && root->data < n2)
root = root->right;
else break;
}
return root;
}
/* Helper function that allocates
a new node with the given data.*/
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = Node->right = NULL;
return(Node);
}
/* Driver code*/
int main()
{
// Let us construct the BST
// shown in the above figure
node *root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
int n1 = 10, n2 = 14;
node *t = lca(root, n1, n2);
cout << "LCA of " << n1 << " and " << n2 << " is " << t->data<<endl;
n1 = 14, n2 = 8;
t = lca(root, n1, n2);
cout<<"LCA of " << n1 << " and " << n2 << " is " << t->data << endl;
n1 = 10, n2 = 22;
t = lca(root, n1, n2);
cout << "LCA of " << n1 << " and " << n2 << " is " << t->data << endl;
return 0;
}
| 25.027778
| 76
| 0.506104
|
ShreyaDayma-cse
|
44b8d9bba31dbe8f2adaf3072186237fb7d61f51
| 5,433
|
cpp
|
C++
|
includes/lib_encrypt-me/sources/Controller.cpp
|
Marsevil/encrypt-me
|
94bd9aa7b8fcb61192f21b9a99f593d9ff01ee01
|
[
"MIT"
] | 3
|
2020-11-21T23:20:01.000Z
|
2021-12-25T22:26:51.000Z
|
includes/lib_encrypt-me/sources/Controller.cpp
|
Marsevil/encrypt-me
|
94bd9aa7b8fcb61192f21b9a99f593d9ff01ee01
|
[
"MIT"
] | 6
|
2020-11-22T01:25:40.000Z
|
2021-05-11T13:04:21.000Z
|
includes/lib_encrypt-me/sources/Controller.cpp
|
Marsevil/encrypt-me
|
94bd9aa7b8fcb61192f21b9a99f593d9ff01ee01
|
[
"MIT"
] | 1
|
2021-05-16T15:19:42.000Z
|
2021-05-16T15:19:42.000Z
|
//
// Created by marsevil on 10/01/2021.
//
#include "Controller.hpp"
Controller::Controller(View* _view, sf::path const& _source, sf::path const& _destination, std::string const& _password)
: view(_view), source(_source), destination(_destination), password(_password) {
// Nothing to do here.
}
Controller::~Controller() {
delete view;
}
void Controller::checkDirectoryContent(bool encExtension, sf::path sourcePath, sf::path destinationPath, std::vector<Tuple>& diffList) {
for (sf::path const& path : sf::directory_iterator(destinationPath)) {
sf::path hypotheticalSourcePath(sourcePath / path.filename());
if (encExtension && !sf::is_directory(path)) {
if (hypotheticalSourcePath.extension() == ".enc") hypotheticalSourcePath.replace_extension("");
else hypotheticalSourcePath += ".enc";
}
if (!exists(hypotheticalSourcePath)) diffList.push_back({
"",
path,
Tuple::Action::DELETE
});
}
}
std::vector<Tuple> Controller::diff(bool encExtension) const {
std::vector<Tuple> diffList(checkConfig(encExtension));
if (sf::last_write_time(source) > sf::last_write_time(destination))
checkDirectoryContent(encExtension, source, destination, diffList);
diff(encExtension, source, destination, diffList);
return diffList;
}
void Controller::diff(bool encExtension, sf::path const& sourceDirectory, sf::path const& destinationDirectory, std::vector<Tuple>& diffList) {
for (sf::path const& sourcePath : sf::directory_iterator(sourceDirectory)) {
sf::path destinationPath(destinationDirectory / sourcePath.filename());
bool isDirectory(sf::is_directory(sourcePath));
if (isDirectory) {
// If sourcePath is a directory
if (!sf::exists(destinationPath)) diffList.push_back({
sourcePath,
destinationPath,
Tuple::Action::CREATE_DIR
});
else if (sf::last_write_time(sourcePath) > sf::last_write_time(destinationPath)) {
checkDirectoryContent(encExtension, sourcePath, destinationPath, diffList);
}
diff(encExtension, sourcePath, destinationPath, diffList);
} else {
// If sourcePath is not a directory.
if (encExtension) {
if (sourcePath.extension() == ".enc") destinationPath.replace_extension("");
else destinationPath += ".enc";
}
if (!sf::exists(destinationPath)) diffList.push_back({
sourcePath,
destinationPath,
Tuple::Action::CREATE
});
else if (sf::last_write_time(sourcePath) > sf::last_write_time(destinationPath)) diffList.push_back({
sourcePath,
destinationPath,
Tuple::Action::UPDATE
});
}
}
}
std::vector<Tuple> Controller::checkConfig(bool isCryptography) const {
std::vector<Tuple> ret;
if (!sf::exists(source)) throw std::runtime_error("Source doesn't exists.");
else if (!sf::is_directory(source)) throw std::runtime_error("Source should be a directory.");
if (!sf::exists(destination)) ret.push_back({
source,
destination,
Tuple::Action::CREATE_DIR
});
if (isCryptography && password.empty()) throw std::runtime_error("Password should not be empty.");
return ret;
}
Applyer* Controller::getApplyer(const Applyer::Process &process) const {
if (process == Applyer::Process::ENCRYPT || process == Applyer::Process::DECRYPT) {
return new CryptMan(password);
} else if (process == Applyer::Process::COPY) {
throw std::runtime_error("Copy function not implemented yet.");
} else {
throw std::domain_error("Process not supported.");
}
}
void Controller::apply(std::vector<Tuple> const& diffList, Applyer::Process process) const {
Applyer* applyer = getApplyer(process);
// Apply modifications.
for (Tuple const& tuple : diffList) {
view->printTask(tuple);
if (tuple.toDo == Tuple::Action::CREATE_DIR) sf::create_directories(tuple.destination);
else if (tuple.toDo == Tuple::Action::CREATE || tuple.toDo == Tuple::Action::UPDATE) {
applyer->setSource(tuple.source);
applyer->setDestination(tuple.destination);
applyer->apply(process);
} else if (tuple.toDo == Tuple::DELETE) sf::remove_all(tuple.destination);
view->printDone();
}
// Copy last modified time.
for (Tuple const& tuple : diffList) {
if (tuple.toDo != Tuple::DELETE && tuple.source.lexically_relative(source).has_parent_path())
sf::last_write_time(tuple.destination.parent_path(), sf::last_write_time(tuple.source.parent_path()));
}
delete applyer;
}
void Controller::run() {
setSource(view->getSource());
setDestination(view->getDestination());
Applyer::Process process(view->getProcess());
Action action(view->getAction());
bool isCryptography = (process == Applyer::DECRYPT || process == Applyer::ENCRYPT);
if (isCryptography) setPassword(view->getPassword());
std::vector<Tuple> diffs(diff(isCryptography));
if (action == Action::APPLY && view->confirmDiff(diffs)) apply(diffs, process);
else if (action == Action::SHOW) view->printDiff(diffs);
}
| 36.709459
| 143
| 0.638874
|
Marsevil
|
44ba5c3704b1f06ffe7f86a14c0b9b0231eb7ae2
| 4,690
|
cc
|
C++
|
dacbench/envs/rl-plan/fast-downward/src/search/merge_and_shrink/merge_scoring_function_dfp.cc
|
ndangtt/LeadingOnesDAC
|
953747d8702f179851d7973c65779a1f830e03a1
|
[
"Apache-2.0"
] | 1
|
2022-02-23T15:26:11.000Z
|
2022-02-23T15:26:11.000Z
|
dacbench/envs/rl-plan/fast-downward/src/search/merge_and_shrink/merge_scoring_function_dfp.cc
|
ndangtt/LeadingOnesDAC
|
953747d8702f179851d7973c65779a1f830e03a1
|
[
"Apache-2.0"
] | null | null | null |
dacbench/envs/rl-plan/fast-downward/src/search/merge_and_shrink/merge_scoring_function_dfp.cc
|
ndangtt/LeadingOnesDAC
|
953747d8702f179851d7973c65779a1f830e03a1
|
[
"Apache-2.0"
] | null | null | null |
#include "merge_scoring_function_dfp.h"
#include "distances.h"
#include "factored_transition_system.h"
#include "label_equivalence_relation.h"
#include "labels.h"
#include "transition_system.h"
#include "../options/option_parser.h"
#include "../options/plugin.h"
#include "../utils/markup.h"
#include <cassert>
using namespace std;
namespace merge_and_shrink {
vector<int> MergeScoringFunctionDFP::compute_label_ranks(
const FactoredTransitionSystem &fts, int index) const {
const TransitionSystem &ts = fts.get_transition_system(index);
const Distances &distances = fts.get_distances(index);
assert(distances.are_goal_distances_computed());
int num_labels = fts.get_labels().get_size();
// Irrelevant (and inactive, i.e. reduced) labels have a dummy rank of -1
vector<int> label_ranks(num_labels, -1);
for (const GroupAndTransitions &gat : ts) {
const LabelGroup &label_group = gat.label_group;
const vector<Transition> &transitions = gat.transitions;
// Relevant labels with no transitions have a rank of infinity.
int label_rank = INF;
bool group_relevant = false;
if (static_cast<int>(transitions.size()) == ts.get_size()) {
/*
A label group is irrelevant in the earlier notion if it has
exactly a self loop transition for every state.
*/
for (const Transition &transition : transitions) {
if (transition.target != transition.src) {
group_relevant = true;
break;
}
}
} else {
group_relevant = true;
}
if (!group_relevant) {
label_rank = -1;
} else {
for (const Transition &transition : transitions) {
label_rank = min(label_rank,
distances.get_goal_distance(transition.target));
}
}
for (int label_no : label_group) {
label_ranks[label_no] = label_rank;
}
}
return label_ranks;
}
vector<double> MergeScoringFunctionDFP::compute_scores(
const FactoredTransitionSystem &fts,
const vector<pair<int, int>> &merge_candidates) {
int num_ts = fts.get_size();
vector<vector<int>> transition_system_label_ranks(num_ts);
vector<double> scores;
scores.reserve(merge_candidates.size());
// Go over all pairs of transition systems and compute their weight.
for (pair<int, int> merge_candidate : merge_candidates) {
int ts_index1 = merge_candidate.first;
int ts_index2 = merge_candidate.second;
vector<int> &label_ranks1 = transition_system_label_ranks[ts_index1];
if (label_ranks1.empty()) {
label_ranks1 = compute_label_ranks(fts, ts_index1);
}
vector<int> &label_ranks2 = transition_system_label_ranks[ts_index2];
if (label_ranks2.empty()) {
label_ranks2 = compute_label_ranks(fts, ts_index2);
}
assert(label_ranks1.size() == label_ranks2.size());
// Compute the weight associated with this pair
int pair_weight = INF;
for (size_t i = 0; i < label_ranks1.size(); ++i) {
if (label_ranks1[i] != -1 && label_ranks2[i] != -1) {
// label is relevant in both transition_systems
int max_label_rank = max(label_ranks1[i], label_ranks2[i]);
pair_weight = min(pair_weight, max_label_rank);
}
}
scores.push_back(pair_weight);
}
return scores;
}
string MergeScoringFunctionDFP::name() const {
return "dfp";
}
static shared_ptr<MergeScoringFunction>_parse(options::OptionParser &parser) {
parser.document_synopsis(
"DFP scoring",
"This scoring function computes the 'DFP' score as descrdibed in the "
"paper \"Directed model checking with distance-preserving abstractions\" "
"by Draeger, Finkbeiner and Podelski (SPIN 2006), adapted to planning in "
"the following paper:" + utils::format_conference_reference(
{"Silvan Sievers", "Martin Wehrle", "Malte Helmert"},
"Generalized Label Reduction for Merge-and-Shrink Heuristics",
"https://ai.dmi.unibas.ch/papers/sievers-et-al-aaai2014.pdf",
"Proceedings of the 28th AAAI Conference on Artificial"
" Intelligence (AAAI 2014)",
"2358-2366",
"AAAI Press",
"2014"));
if (parser.dry_run())
return nullptr;
else
return make_shared<MergeScoringFunctionDFP>();
}
static options::Plugin<MergeScoringFunction> _plugin("dfp", _parse);
}
| 36.076923
| 82
| 0.632196
|
ndangtt
|
44bafafe79871d1e0479f4063007537e36544ed8
| 3,732
|
cpp
|
C++
|
drake/systems/plants/constraint/testMultipleTimeLinearPostureConstraintmex.cpp
|
ericmanzi/double_pendulum_lqr
|
76bba3091295abb7d412c4a3156258918f280c96
|
[
"BSD-3-Clause"
] | 4
|
2018-04-16T09:54:52.000Z
|
2021-03-29T21:59:27.000Z
|
drake/systems/plants/constraint/testMultipleTimeLinearPostureConstraintmex.cpp
|
ericmanzi/double_pendulum_lqr
|
76bba3091295abb7d412c4a3156258918f280c96
|
[
"BSD-3-Clause"
] | null | null | null |
drake/systems/plants/constraint/testMultipleTimeLinearPostureConstraintmex.cpp
|
ericmanzi/double_pendulum_lqr
|
76bba3091295abb7d412c4a3156258918f280c96
|
[
"BSD-3-Clause"
] | 1
|
2017-08-24T20:32:03.000Z
|
2017-08-24T20:32:03.000Z
|
#include "mex.h"
#include "RigidBodyConstraint.h"
#include "drakeMexUtil.h"
#include "../RigidBodyManipulator.h"
#include <cstring>
/*
* [num_constraint,constraint_val,iAfun,jAvar,A ,constraint_name,lower_bound,upper_bound] = testMultipleTimeLinearPostureConstraintmex(kinCnst_ptr,q,t)
* @param kinCnst_ptr A pointer to a MultipleTimeLinearPostureConstraint object
* @param q A nqxnT double vector
* @param t A double array, the time moments to evaluate constraint value, bounds and name.
* @retval num_constraint The number of constraint active at time t
* @retval constraint_val The value of the constraint at time t
* @retval iAfun,jAvar,A The sparse matrix sparse(iAfun,jAvar,A,num_constraint,numel(q)) is the gradient of constraint_val w.r.t q
* @retval constraint_name The name of the constraint at time t
* @retval lower_bound The lower bound of the constraint at time t
* @retval upper_bound The upper bound of the constraint at time t
* */
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray *prhs[])
{
if(nrhs!=3 || nlhs != 8)
{
mexErrMsgIdAndTxt("Drake:testMultipleTimeLinearPostureConstrainttmex:BadInputs","Usage [num_cnst,cnst_val,iAfun,jAvar,A,cnst_name,lb,ub] = testMultipleTimeLinearPostureConstraintmex(kinCnst,q,t)");
}
MultipleTimeLinearPostureConstraint* cnst = (MultipleTimeLinearPostureConstraint*) getDrakeMexPointer(prhs[0]);
int n_breaks = static_cast<int>(mxGetNumberOfElements(prhs[2]));
double* t_ptr = new double[n_breaks];
memcpy(t_ptr,mxGetPrSafe(prhs[2]),sizeof(double)*n_breaks);
int nq = cnst->getRobotPointer()->num_positions;
Eigen::MatrixXd q(nq,n_breaks);
if(mxGetM(prhs[1]) != nq || mxGetN(prhs[1]) != n_breaks)
{
mexErrMsgIdAndTxt("Drake:testMultipleTimeLinearPostureConstraintmex:BadInputs","Argument 2 must be of size nq*n_breaks");
}
memcpy(q.data(),mxGetPrSafe(prhs[1]),sizeof(double)*nq*n_breaks);
int num_cnst = cnst->getNumConstraint(t_ptr,n_breaks);
Eigen::VectorXd c(num_cnst);
cnst->feval(t_ptr,n_breaks,q,c);
Eigen::VectorXi iAfun;
Eigen::VectorXi jAvar;
Eigen::VectorXd A;
cnst->geval(t_ptr,n_breaks,iAfun,jAvar,A);
std::vector<std::string> cnst_names;
cnst->name(t_ptr,n_breaks,cnst_names);
Eigen::VectorXd lb(num_cnst);
Eigen::VectorXd ub(num_cnst);
cnst->bounds(t_ptr,n_breaks,lb,ub);
Eigen::VectorXd iAfun_tmp(iAfun.size());
Eigen::VectorXd jAvar_tmp(jAvar.size());
for(int i = 0;i<iAfun.size();i++)
{
iAfun_tmp(i) = (double) iAfun(i)+1;
jAvar_tmp(i) = (double) jAvar(i)+1;
}
plhs[0] = mxCreateDoubleScalar((double) num_cnst);
plhs[1] = mxCreateDoubleMatrix(num_cnst,1,mxREAL);
memcpy(mxGetPrSafe(plhs[1]),c.data(),sizeof(double)*num_cnst);
plhs[2] = mxCreateDoubleMatrix(iAfun_tmp.size(),1,mxREAL);
memcpy(mxGetPrSafe(plhs[2]),iAfun_tmp.data(),sizeof(double)*iAfun_tmp.size());
plhs[3] = mxCreateDoubleMatrix(jAvar_tmp.size(),1,mxREAL);
memcpy(mxGetPrSafe(plhs[3]),jAvar_tmp.data(),sizeof(double)*jAvar_tmp.size());
plhs[4] = mxCreateDoubleMatrix(A.size(),1,mxREAL);
memcpy(mxGetPrSafe(plhs[4]),A.data(),sizeof(double)*A.size());
int name_ndim = 1;
mwSize name_dims[] = {(mwSize) num_cnst};
plhs[5] = mxCreateCellArray(name_ndim,name_dims);
mxArray *name_ptr;
for(int i = 0;i<num_cnst;i++)
{
name_ptr = mxCreateString(cnst_names[i].c_str());
mxSetCell(plhs[5],i,name_ptr);
}
plhs[6] = mxCreateDoubleMatrix(num_cnst,1,mxREAL);
plhs[7] = mxCreateDoubleMatrix(num_cnst,1,mxREAL);
memcpy(mxGetPrSafe(plhs[6]),lb.data(),sizeof(double)*num_cnst);
memcpy(mxGetPrSafe(plhs[7]),ub.data(),sizeof(double)*num_cnst);
delete[] t_ptr;
}
| 46.65
| 201
| 0.716506
|
ericmanzi
|
44bd081ae118bde5c09ba8998956997d39e06cdd
| 544
|
cpp
|
C++
|
archives/problemset/codeforces.com/137C.cpp
|
BoleynSu/CP-CompetitiveProgramming
|
cc256bf402360fe0f689fdcdc4e898473a9594dd
|
[
"MIT"
] | 6
|
2019-03-23T21:06:25.000Z
|
2021-06-27T05:22:41.000Z
|
archives/problemset/codeforces.com/137C.cpp
|
BoleynSu/CP-CompetitiveProgramming
|
cc256bf402360fe0f689fdcdc4e898473a9594dd
|
[
"MIT"
] | 1
|
2020-10-11T08:14:00.000Z
|
2020-10-11T08:14:00.000Z
|
archives/problemset/codeforces.com/137C.cpp
|
BoleynSu/CP-CompetitiveProgramming
|
cc256bf402360fe0f689fdcdc4e898473a9594dd
|
[
"MIT"
] | 3
|
2019-03-23T21:06:31.000Z
|
2021-10-24T01:44:01.000Z
|
#include <string>
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
typedef vector<PII> VPII;
#define a second
#define b first
int main()
{
int n;
cin>>n;
VPII v(n);
for (int i=0;i<n;i++)
cin>>v[i].a>>v[i].b;
sort(v.begin(),v.end());
int answer=0;
for (int i=n-1,min=(~0u)>>1;i>=0;i--)
{
if (v[i].a>min) answer++;
else min=v[i].a;
}
cout<<answer<<endl;
return 0;
}
| 17
| 42
| 0.516544
|
BoleynSu
|
44bdf92af8f76917c2ef37bba53a3803c61dddf6
| 22,099
|
cc
|
C++
|
src/lib/process/tests/d_cfg_mgr_unittests.cc
|
gumingpo/kea-latest
|
ca64954cd71dd544e7c92a0aa366dfc0f79d4ce1
|
[
"Apache-2.0"
] | 1
|
2017-08-24T19:55:21.000Z
|
2017-08-24T19:55:21.000Z
|
src/lib/process/tests/d_cfg_mgr_unittests.cc
|
Acidburn0zzz/kea
|
3036e88d4ff730919cd7d2fb50a961a5d33bf390
|
[
"Apache-2.0"
] | null | null | null |
src/lib/process/tests/d_cfg_mgr_unittests.cc
|
Acidburn0zzz/kea
|
3036e88d4ff730919cd7d2fb50a961a5d33bf390
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2013-2017 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <cc/command_interpreter.h>
#include <config/module_spec.h>
#include <exceptions/exceptions.h>
#include <dhcpsrv/parsers/dhcp_parsers.h>
#include <process/testutils/d_test_stubs.h>
#include <process/d_cfg_mgr.h>
#include <boost/foreach.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <gtest/gtest.h>
#include <sstream>
using namespace std;
using namespace isc;
using namespace isc::config;
using namespace isc::process;
using namespace isc::data;
using namespace boost::posix_time;
namespace {
/// @brief Test Class for verifying that configuration context cannot be null
/// during construction.
class DCtorTestCfgMgr : public DCfgMgrBase {
public:
/// @brief Constructor - Note that is passes in an empty configuration
/// pointer to the base class constructor.
DCtorTestCfgMgr() : DCfgMgrBase(DCfgContextBasePtr()) {
}
/// @brief Destructor
virtual ~DCtorTestCfgMgr() {
}
/// @brief Dummy implementation as this method is abstract.
virtual DCfgContextBasePtr createNewContext() {
return (DCfgContextBasePtr());
}
/// @brief Returns summary of configuration in the textual format.
virtual std::string getConfigSummary(const uint32_t) {
return ("");
}
};
/// @brief Test fixture class for testing DCfgMgrBase class.
/// It maintains an member instance of DStubCfgMgr and derives from
/// ConfigParseTest fixture, thus providing methods for converting JSON
/// strings to configuration element sets, checking parse results,
/// accessing the configuration context and trying to unparse.
class DStubCfgMgrTest : public ConfigParseTest {
public:
/// @brief Constructor
DStubCfgMgrTest():cfg_mgr_(new DStubCfgMgr) {
}
/// @brief Destructor
~DStubCfgMgrTest() {
}
/// @brief Convenience method which returns a DStubContextPtr to the
/// configuration context.
///
/// @return returns a DStubContextPtr.
DStubContextPtr getStubContext() {
return (boost::dynamic_pointer_cast<DStubContext>
(cfg_mgr_->getContext()));
}
/// @brief Configuration manager instance.
DStubCfgMgrPtr cfg_mgr_;
};
///@brief Tests basic construction/destruction of configuration manager.
/// Verifies that:
/// 1. Proper construction succeeds.
/// 2. Configuration context is initialized by construction.
/// 3. Destruction works properly.
/// 4. Construction with a null context is not allowed.
TEST(DCfgMgrBase, construction) {
DCfgMgrBasePtr cfg_mgr;
// Verify that configuration manager constructions without error.
ASSERT_NO_THROW(cfg_mgr.reset(new DStubCfgMgr()));
// Verify that the context can be retrieved and is not null.
DCfgContextBasePtr context = cfg_mgr->getContext();
EXPECT_TRUE(context);
// Verify that the manager can be destructed without error.
EXPECT_NO_THROW(cfg_mgr.reset());
// Verify that an attempt to construct a manger with a null context fails.
ASSERT_THROW(DCtorTestCfgMgr(), DCfgMgrBaseError);
}
///@brief Tests fundamental aspects of configuration parsing.
/// Verifies that:
/// 1. A correctly formed simple configuration parses without error.
/// 2. An error building the element is handled.
/// 3. An error committing the element is handled.
/// 4. An unknown element error is handled.
TEST_F(DStubCfgMgrTest, basicParseTest) {
// Create a simple configuration.
string config = "{ \"test-value\": [] } ";
ASSERT_TRUE(fromJSON(config));
// Verify that we can parse a simple configuration.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(0));
// Verify that we can check a simple configuration.
answer_ = cfg_mgr_->parseConfig(config_set_, true);
EXPECT_TRUE(checkAnswer(0));
// Verify that an unknown element error is caught and returns a failed
// parse result.
SimFailure::set(SimFailure::ftElementUnknown);
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(1));
// Verify that an error is caught too when the config is checked for.
SimFailure::set(SimFailure::ftElementUnknown);
answer_ = cfg_mgr_->parseConfig(config_set_, true);
EXPECT_TRUE(checkAnswer(1));
}
///@brief Tests ordered and non-ordered element parsing
/// This test verifies that:
/// 1. Non-ordered parsing parses elements in the order they are presented
/// by the configuration set (as-they-come).
/// 2. A parse order list with too few elements is detected.
/// 3. Ordered parsing parses the elements in the order specified by the
/// configuration manager's parse order list.
/// 4. A parse order list with too many elements is detected.
TEST_F(DStubCfgMgrTest, parseOrderTest) {
// Element ids used for test.
std::string charlie("charlie");
std::string bravo("bravo");
std::string alpha("alpha");
std::string string_test("string_test");
std::string uint32_test("uint32_test");
std::string bool_test("bool_test");
// Create the test configuration with the elements in "random" order.
// NOTE that element sets produced by isc::data::Element::fromJSON(),
// are in lexical order by element_id. This means that iterating over
// such an element set, will present the elements in lexical order. Should
// this change, this test will need to be modified accordingly.
string config = "{"
" \"string_test\": \"hoopla\", "
" \"bravo\": [], "
" \"uint32_test\": 55, "
" \"alpha\": {}, "
" \"charlie\": [], "
" \"bool_test\": true "
"} ";
ASSERT_TRUE(fromJSON(config));
// Verify that non-ordered parsing, results in an as-they-come parse order.
// Create an expected parse order.
// (NOTE that iterating over Element sets produced by fromJSON() will
// present the elements in lexical order. Should this change, the expected
// order list below would need to be changed accordingly).
ElementIdList order_expected;
// scalar params should be first and lexically
order_expected.push_back(bool_test);
order_expected.push_back(string_test);
order_expected.push_back(uint32_test);
// objects second and lexically
order_expected.push_back(alpha);
order_expected.push_back(bravo);
order_expected.push_back(charlie);
// Verify that the manager has an EMPTY parse order list. (Empty list
// instructs the manager to parse them as-they-come.)
EXPECT_EQ(0, cfg_mgr_->getParseOrder().size());
// Parse the configuration, verify it parses without error.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(0));
// Verify that the parsed order matches what we expected.
EXPECT_TRUE(cfg_mgr_->parsed_order_ == order_expected);
// Clear the manager's parse order "memory".
cfg_mgr_->parsed_order_.clear();
// Create a parse order list that has too few entries. Verify that
// when parsing the test config, it fails.
cfg_mgr_->addToParseOrder(charlie);
// Verify the parse order list is the size we expect.
EXPECT_EQ(1, cfg_mgr_->getParseOrder().size());
// Verify the configuration fails.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(1));
// Verify that the configuration parses correctly, when the parse order
// is correct. Add the needed entries to the parse order
cfg_mgr_->addToParseOrder(bravo);
cfg_mgr_->addToParseOrder(alpha);
// Verify the parse order list is the size we expect.
EXPECT_EQ(3, cfg_mgr_->getParseOrder().size());
// Clear the manager's parse order "memory".
cfg_mgr_->parsed_order_.clear();
// Verify the configuration parses without error.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(0));
// Build expected order
// primitives should be first and lexically
order_expected.clear();
order_expected.push_back(bool_test);
order_expected.push_back(string_test);
order_expected.push_back(uint32_test);
// objects second and by the parse order
order_expected.push_back(charlie);
order_expected.push_back(bravo);
order_expected.push_back(alpha);
// Verify that the parsed order is the order we configured.
EXPECT_TRUE(cfg_mgr_->parsed_order_ == order_expected);
// Create a parse order list that has too many entries. Verify that
// when parsing the test config, it fails.
cfg_mgr_->addToParseOrder("delta");
// Verify the parse order list is the size we expect.
EXPECT_EQ(4, cfg_mgr_->getParseOrder().size());
// Verify the configuration fails.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(1));
}
/// @brief Tests that element ids supported by the base class as well as those
/// added by the derived class function properly.
/// This test verifies that:
/// 1. Boolean parameters can be parsed and retrieved.
/// 2. Uint32 parameters can be parsed and retrieved.
/// 3. String parameters can be parsed and retrieved.
/// 4. Map elements can be parsed and retrieved.
/// 5. List elements can be parsed and retrieved.
/// 6. Parsing a second configuration, updates the existing context values
/// correctly.
TEST_F(DStubCfgMgrTest, simpleTypesTest) {
// Create a configuration with all of the parameters.
string config = "{ \"bool_test\": true , "
" \"uint32_test\": 77 , "
" \"string_test\": \"hmmm chewy\" , "
" \"map_test\" : {} , "
" \"list_test\": [] }";
ASSERT_TRUE(fromJSON(config));
// Verify that the configuration parses without error.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
ASSERT_TRUE(checkAnswer(0));
DStubContextPtr context = getStubContext();
ASSERT_TRUE(context);
// Verify that the boolean parameter was parsed correctly by retrieving
// its value from the context.
bool actual_bool = false;
EXPECT_NO_THROW(context->getParam("bool_test", actual_bool));
EXPECT_EQ(true, actual_bool);
// Verify that the uint32 parameter was parsed correctly by retrieving
// its value from the context.
uint32_t actual_uint32 = 0;
EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32));
EXPECT_EQ(77, actual_uint32);
// Verify that the string parameter was parsed correctly by retrieving
// its value from the context.
std::string actual_string = "";
EXPECT_NO_THROW(context->getParam("string_test", actual_string));
EXPECT_EQ("hmmm chewy", actual_string);
isc::data::ConstElementPtr object;
EXPECT_NO_THROW(context->getObjectParam("map_test", object));
EXPECT_TRUE(object);
EXPECT_NO_THROW(context->getObjectParam("list_test", object));
EXPECT_TRUE(object);
// Create a configuration which "updates" all of the parameter values.
string config2 = "{ \"bool_test\": false , "
" \"uint32_test\": 88 , "
" \"string_test\": \"ewww yuk!\" , "
" \"map_test2\" : {} , "
" \"list_test2\": [] }";
ASSERT_TRUE(fromJSON(config2));
// Verify that the configuration parses without error.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(0));
context = getStubContext();
ASSERT_TRUE(context);
// Verify that the boolean parameter was updated correctly by retrieving
// its value from the context.
actual_bool = true;
EXPECT_NO_THROW(context->getParam("bool_test", actual_bool));
EXPECT_FALSE(actual_bool);
// Verify that the uint32 parameter was updated correctly by retrieving
// its value from the context.
actual_uint32 = 0;
EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32));
EXPECT_EQ(88, actual_uint32);
// Verify that the string parameter was updated correctly by retrieving
// its value from the context.
actual_string = "";
EXPECT_NO_THROW(context->getParam("string_test", actual_string));
EXPECT_EQ("ewww yuk!", actual_string);
// Verify previous objects are not there.
EXPECT_THROW(context->getObjectParam("map_test", object),
isc::dhcp::DhcpConfigError);
EXPECT_THROW(context->getObjectParam("list_test", object),
isc::dhcp::DhcpConfigError);
// Verify new map object is there.
EXPECT_NO_THROW(context->getObjectParam("map_test2", object));
EXPECT_TRUE(object);
// Verify new list object is there.
EXPECT_NO_THROW(context->getObjectParam("list_test2", object));
EXPECT_TRUE(object);
}
/// @brief Tests that the configuration context is preserved after failure
/// during parsing causes a rollback.
/// 1. Verifies configuration context rollback.
TEST_F(DStubCfgMgrTest, rollBackTest) {
// Create a configuration with all of the parameters.
string config = "{ \"bool_test\": true , "
" \"uint32_test\": 77 , "
" \"string_test\": \"hmmm chewy\" , "
" \"map_test\" : {} , "
" \"list_test\": [] }";
ASSERT_TRUE(fromJSON(config));
// Verify that the configuration parses without error.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(0));
DStubContextPtr context = getStubContext();
ASSERT_TRUE(context);
// Verify that all of parameters have the expected values.
bool actual_bool = false;
EXPECT_NO_THROW(context->getParam("bool_test", actual_bool));
EXPECT_EQ(true, actual_bool);
uint32_t actual_uint32 = 0;
EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32));
EXPECT_EQ(77, actual_uint32);
std::string actual_string = "";
EXPECT_NO_THROW(context->getParam("string_test", actual_string));
EXPECT_EQ("hmmm chewy", actual_string);
isc::data::ConstElementPtr object;
EXPECT_NO_THROW(context->getObjectParam("map_test", object));
EXPECT_TRUE(object);
EXPECT_NO_THROW(context->getObjectParam("list_test", object));
EXPECT_TRUE(object);
// Create a configuration which "updates" all of the parameter values
// plus one unknown at the end.
string config2 = "{ \"bool_test\": false , "
" \"uint32_test\": 88 , "
" \"string_test\": \"ewww yuk!\" , "
" \"map_test2\" : {} , "
" \"list_test2\": [] , "
" \"zeta_unknown\": 33 } ";
ASSERT_TRUE(fromJSON(config2));
// Force a failure on the last element
SimFailure::set(SimFailure::ftElementUnknown);
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(1));
context = getStubContext();
ASSERT_TRUE(context);
// Verify that all of parameters have the original values.
actual_bool = false;
EXPECT_NO_THROW(context->getParam("bool_test", actual_bool));
EXPECT_EQ(true, actual_bool);
actual_uint32 = 0;
EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32));
EXPECT_EQ(77, actual_uint32);
actual_string = "";
EXPECT_NO_THROW(context->getParam("string_test", actual_string));
EXPECT_EQ("hmmm chewy", actual_string);
EXPECT_NO_THROW(context->getObjectParam("map_test", object));
EXPECT_TRUE(object);
EXPECT_NO_THROW(context->getObjectParam("list_test", object));
EXPECT_TRUE(object);
}
/// @brief Tests that the configuration context is preserved during
/// check only parsing.
TEST_F(DStubCfgMgrTest, checkOnly) {
// Create a configuration with all of the parameters.
string config = "{ \"bool_test\": true , "
" \"uint32_test\": 77 , "
" \"string_test\": \"hmmm chewy\" , "
" \"map_test\" : {} , "
" \"list_test\": [] }";
ASSERT_TRUE(fromJSON(config));
// Verify that the configuration parses without error.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(0));
DStubContextPtr context = getStubContext();
ASSERT_TRUE(context);
// Verify that all of parameters have the expected values.
bool actual_bool = false;
EXPECT_NO_THROW(context->getParam("bool_test", actual_bool));
EXPECT_EQ(true, actual_bool);
uint32_t actual_uint32 = 0;
EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32));
EXPECT_EQ(77, actual_uint32);
std::string actual_string = "";
EXPECT_NO_THROW(context->getParam("string_test", actual_string));
EXPECT_EQ("hmmm chewy", actual_string);
isc::data::ConstElementPtr object;
EXPECT_NO_THROW(context->getObjectParam("map_test", object));
EXPECT_TRUE(object);
EXPECT_NO_THROW(context->getObjectParam("list_test", object));
EXPECT_TRUE(object);
// Create a configuration which "updates" all of the parameter values.
string config2 = "{ \"bool_test\": false , "
" \"uint32_test\": 88 , "
" \"string_test\": \"ewww yuk!\" , "
" \"map_test2\" : {} , "
" \"list_test2\": [] }";
ASSERT_TRUE(fromJSON(config2));
answer_ = cfg_mgr_->parseConfig(config_set_, true);
EXPECT_TRUE(checkAnswer(0));
context = getStubContext();
ASSERT_TRUE(context);
// Verify that all of parameters have the original values.
actual_bool = false;
EXPECT_NO_THROW(context->getParam("bool_test", actual_bool));
EXPECT_EQ(true, actual_bool);
actual_uint32 = 0;
EXPECT_NO_THROW(context->getParam("uint32_test", actual_uint32));
EXPECT_EQ(77, actual_uint32);
actual_string = "";
EXPECT_NO_THROW(context->getParam("string_test", actual_string));
EXPECT_EQ("hmmm chewy", actual_string);
EXPECT_NO_THROW(context->getObjectParam("map_test", object));
EXPECT_TRUE(object);
EXPECT_NO_THROW(context->getObjectParam("list_test", object));
EXPECT_TRUE(object);
}
// Tests that configuration element position is returned by getParam variants.
TEST_F(DStubCfgMgrTest, paramPosition) {
// Create a configuration with one of each scalar types. We end them
// with line feeds so we can test position value.
string config = "{ \"bool_test\": true , \n"
" \"uint32_test\": 77 , \n"
" \"string_test\": \"hmmm chewy\" }";
ASSERT_TRUE(fromJSON(config));
// Verify that the configuration parses without error.
answer_ = cfg_mgr_->parseConfig(config_set_, false);
ASSERT_TRUE(checkAnswer(0));
DStubContextPtr context = getStubContext();
ASSERT_TRUE(context);
// Verify that the boolean parameter was parsed correctly by retrieving
// its value from the context.
bool actual_bool = false;
isc::data::Element::Position pos;
EXPECT_NO_THROW(pos = context->getParam("bool_test", actual_bool));
EXPECT_EQ(true, actual_bool);
EXPECT_EQ(1, pos.line_);
// Verify that the uint32 parameter was parsed correctly by retrieving
// its value from the context.
uint32_t actual_uint32 = 0;
EXPECT_NO_THROW(pos = context->getParam("uint32_test", actual_uint32));
EXPECT_EQ(77, actual_uint32);
EXPECT_EQ(2, pos.line_);
// Verify that the string parameter was parsed correctly by retrieving
// its value from the context.
std::string actual_string = "";
EXPECT_NO_THROW(pos = context->getParam("string_test", actual_string));
EXPECT_EQ("hmmm chewy", actual_string);
EXPECT_EQ(3, pos.line_);
// Verify that an optional parameter that is not defined, returns the
// zero position.
pos = isc::data::Element::ZERO_POSITION();
EXPECT_NO_THROW(pos = context->getParam("bogus_value",
actual_string, true));
EXPECT_EQ(pos.file_, isc::data::Element::ZERO_POSITION().file_);
}
// This tests if some aspects of simpleParseConfig are behaving properly.
// Thorough testing is only possible for specific implementations. This
// is done for control agent (see CtrlAgentControllerTest tests in
// src/bin/agent/tests/ctrl_agent_controller_unittest.cc for example).
// Also, shell tests in src/bin/agent/ctrl_agent_process_tests.sh test
// the whole CA process that uses simpleParseConfig. The alternative
// would be to implement whole parser that would set the context
// properly. The ROI for this is not worth the effort.
TEST_F(DStubCfgMgrTest, simpleParseConfig) {
using namespace isc::data;
// Passing just null pointer should result in error return code
answer_ = cfg_mgr_->simpleParseConfig(ConstElementPtr(), false);
EXPECT_TRUE(checkAnswer(1));
// Ok, now try with a dummy, but valid json code
string config = "{ \"bool_test\": true , \n"
" \"uint32_test\": 77 , \n"
" \"string_test\": \"hmmm chewy\" }";
ASSERT_NO_THROW(fromJSON(config));
answer_ = cfg_mgr_->simpleParseConfig(config_set_, false);
EXPECT_TRUE(checkAnswer(0));
}
// This test checks that the post configuration callback function is
// executed by the simpleParseConfig function.
TEST_F(DStubCfgMgrTest, simpleParseConfigWithCallback) {
string config = "{ \"bool_test\": true , \n"
" \"uint32_test\": 77 , \n"
" \"string_test\": \"hmmm chewy\" }";
ASSERT_NO_THROW(fromJSON(config));
answer_ = cfg_mgr_->simpleParseConfig(config_set_, false,
[this]() {
isc_throw(Unexpected, "unexpected configuration error");
});
EXPECT_TRUE(checkAnswer(1));
}
} // end of anonymous namespace
| 37.90566
| 79
| 0.675234
|
gumingpo
|
44c01e02d26812b47858cb315b1b9d92fcbc95a6
| 6,254
|
cpp
|
C++
|
opencv-2.4.11/modules/imgproc/src/matchcontours.cpp
|
durai-chellamuthu/node-opencv
|
a9c18c77b2fe0f62f2f8376854bdf33de71f5dc3
|
[
"MIT"
] | 264
|
2015-01-04T10:58:41.000Z
|
2022-03-30T21:26:07.000Z
|
opencv-2.4.11/modules/imgproc/src/matchcontours.cpp
|
durai-chellamuthu/node-opencv
|
a9c18c77b2fe0f62f2f8376854bdf33de71f5dc3
|
[
"MIT"
] | 30
|
2015-02-16T21:06:34.000Z
|
2019-07-18T10:22:57.000Z
|
opencv-2.4.11/modules/imgproc/src/matchcontours.cpp
|
durai-chellamuthu/node-opencv
|
a9c18c77b2fe0f62f2f8376854bdf33de71f5dc3
|
[
"MIT"
] | 57
|
2015-02-20T16:38:48.000Z
|
2020-12-27T08:57:10.000Z
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: cvMatchContours
// Purpose:
// Calculates matching of the two contours
// Context:
// Parameters:
// contour_1 - pointer to the first input contour object.
// contour_2 - pointer to the second input contour object.
// method - method for the matching calculation
// (now CV_IPPI_CONTOURS_MATCH_I1, CV_CONTOURS_MATCH_I2 or
// CV_CONTOURS_MATCH_I3 only )
// rezult - output calculated measure
//
//F*/
CV_IMPL double
cvMatchShapes( const void* contour1, const void* contour2,
int method, double /*parameter*/ )
{
CvMoments moments;
CvHuMoments huMoments;
double ma[7], mb[7];
int i, sma, smb;
double eps = 1.e-5;
double mmm;
double result = 0;
if( !contour1 || !contour2 )
CV_Error( CV_StsNullPtr, "" );
// calculate moments of the first shape
cvMoments( contour1, &moments );
cvGetHuMoments( &moments, &huMoments );
ma[0] = huMoments.hu1;
ma[1] = huMoments.hu2;
ma[2] = huMoments.hu3;
ma[3] = huMoments.hu4;
ma[4] = huMoments.hu5;
ma[5] = huMoments.hu6;
ma[6] = huMoments.hu7;
// calculate moments of the second shape
cvMoments( contour2, &moments );
cvGetHuMoments( &moments, &huMoments );
mb[0] = huMoments.hu1;
mb[1] = huMoments.hu2;
mb[2] = huMoments.hu3;
mb[3] = huMoments.hu4;
mb[4] = huMoments.hu5;
mb[5] = huMoments.hu6;
mb[6] = huMoments.hu7;
switch (method)
{
case 1:
{
for( i = 0; i < 7; i++ )
{
double ama = fabs( ma[i] );
double amb = fabs( mb[i] );
if( ma[i] > 0 )
sma = 1;
else if( ma[i] < 0 )
sma = -1;
else
sma = 0;
if( mb[i] > 0 )
smb = 1;
else if( mb[i] < 0 )
smb = -1;
else
smb = 0;
if( ama > eps && amb > eps )
{
ama = 1. / (sma * log10( ama ));
amb = 1. / (smb * log10( amb ));
result += fabs( -ama + amb );
}
}
break;
}
case 2:
{
for( i = 0; i < 7; i++ )
{
double ama = fabs( ma[i] );
double amb = fabs( mb[i] );
if( ma[i] > 0 )
sma = 1;
else if( ma[i] < 0 )
sma = -1;
else
sma = 0;
if( mb[i] > 0 )
smb = 1;
else if( mb[i] < 0 )
smb = -1;
else
smb = 0;
if( ama > eps && amb > eps )
{
ama = sma * log10( ama );
amb = smb * log10( amb );
result += fabs( -ama + amb );
}
}
break;
}
case 3:
{
for( i = 0; i < 7; i++ )
{
double ama = fabs( ma[i] );
double amb = fabs( mb[i] );
if( ma[i] > 0 )
sma = 1;
else if( ma[i] < 0 )
sma = -1;
else
sma = 0;
if( mb[i] > 0 )
smb = 1;
else if( mb[i] < 0 )
smb = -1;
else
smb = 0;
if( ama > eps && amb > eps )
{
ama = sma * log10( ama );
amb = smb * log10( amb );
mmm = fabs( (ama - amb) / ama );
if( result < mmm )
result = mmm;
}
}
break;
}
default:
CV_Error( CV_StsBadArg, "Unknown comparison method" );
}
return result;
}
/* End of file. */
| 31.427136
| 90
| 0.48369
|
durai-chellamuthu
|
44c036da3c5ac682a871fce79885115f340c6b1b
| 1,816
|
cpp
|
C++
|
src/BejeweledIO.cpp
|
AlexBarnes86/Jewels
|
0a4ec5ced01309e3a8a77f7377d84a12306b1688
|
[
"MIT"
] | null | null | null |
src/BejeweledIO.cpp
|
AlexBarnes86/Jewels
|
0a4ec5ced01309e3a8a77f7377d84a12306b1688
|
[
"MIT"
] | null | null | null |
src/BejeweledIO.cpp
|
AlexBarnes86/Jewels
|
0a4ec5ced01309e3a8a77f7377d84a12306b1688
|
[
"MIT"
] | null | null | null |
#include "BejeweledIO.h"
#include <stdlib.h>
ScoreIO::ScoreIO()
: scoreFile("HighScores.txt")
{
readScores();
}
vector<PlayerScore> ScoreIO::readScores()
{
string HighScores = "HighScores.txt";
ifstream ist(HighScores.c_str());
if(!ist)
cout << "High Score File Not Found!" << endl;
string temp;
string name;
int score;
int level;
while(getline(ist, temp))
{
istringstream strInput(temp);
strInput>>name>>level>>score;
PlayerScore pscore(name, level, score);
scores.push_back(pscore);
cout << "Score pushed back: Name: " << name << ' ' << level << ' ' << score << endl;
}
ist.close();
return scores;
}
void ScoreIO::writeScore(PlayerScore ps)
{
string HighScores = "HighScores.txt";
ofstream ost(HighScores.c_str());
if(!ost)
cout << "High Score File Not Found!\n" << endl;
bool scoreMadeIt = false;
for (unsigned int i=0; i<scores.size(); i++)
{
int temp = scores[i].getScore();
if(!scoreMadeIt && ps.getScore()>=temp)
{
cout << "Writing: " << ps.getName() << " " << ps.getLevel() << " " << ps.getScore() << endl;
ost << ps.getName() << " " << ps.getLevel() << " " << ps.getScore() << endl;
scoreMadeIt = true;
}
else
{
cout << "Writing: " << scores[i].getName() << " " << scores[i].getLevel() << " " << scores[i].getScore() << endl;
ost << scores[i].getName() << " " << scores[i].getLevel() << " " << scores[i].getScore() << endl;
}
}
ost.close();
}
string readHelpFile(string filename)
{
ifstream ist(filename.c_str());
if(!ist)
return "Help file not found!";
string temp;
string helpFile;
while(getline(ist, temp))
{
helpFile+=temp+'\n';
}
ist.close();
return helpFile;
}
PlayerScore ScoreIO::getPlayer(int idx)
{
return scores[idx];
}
| 22.146341
| 117
| 0.585903
|
AlexBarnes86
|
44c1f507a48534a5fa1674dce8129005d09e86b4
| 11,528
|
cpp
|
C++
|
llc/gpk_encoding.cpp
|
asm128/gpk
|
cbd81e2de8024176eb6401746bbbfcd0b69c3e9f
|
[
"Apache-2.0"
] | null | null | null |
llc/gpk_encoding.cpp
|
asm128/gpk
|
cbd81e2de8024176eb6401746bbbfcd0b69c3e9f
|
[
"Apache-2.0"
] | 1
|
2018-06-22T00:58:58.000Z
|
2018-06-22T00:58:58.000Z
|
llc/gpk_encoding.cpp
|
asm128/gpk
|
cbd81e2de8024176eb6401746bbbfcd0b69c3e9f
|
[
"Apache-2.0"
] | 1
|
2018-07-16T20:18:03.000Z
|
2018-07-16T20:18:03.000Z
|
#include "gpk_encoding.h"
#include "gpk_view_bit.h"
#include "gpk_noise.h"
#include "gpk_chrono.h"
#include "gpk_parse.h"
#include <ctime>
#include <random>
::gpk::error_t gpk::saltDataSalt (const ::gpk::view_const_byte& binary, ::gpk::array_pod<byte_t> & salted) {
gpk_necall(salted.resize(binary.size() * 2), "%s", "Out of memory?");
byte_t * pSalted = salted.begin();
const byte_t * pBinary = binary.begin();
for(uint32_t iBinary = 0; iBinary < binary.size(); ++iBinary) {
pSalted[iBinary * 2] = pBinary[iBinary];
pSalted[iBinary * 2 + 1] = (::gpk::noise1DBase(::gpk::timeCurrentInUs()) + ::gpk::timeCurrentInUs()) & 0xFF;
}
return 0;
}
::gpk::error_t gpk::saltDataUnsalt (const ::gpk::view_const_byte& salted, ::gpk::array_pod<byte_t> & binary) {
gpk_necall(binary.resize(salted.size() / 2), "%s", "Out of memory?");
const byte_t * pSalted = salted.begin();
byte_t * pBinary = binary.begin();
for(uint32_t iBinary = 0; iBinary < binary.size(); ++iBinary)
pBinary[iBinary] = pSalted[iBinary * 2];
return 0;
}
static ::gpk::error_t hexFromByte (uint8_t i, char* hexed) {
char converted [0x20] = {};
snprintf(converted, ::gpk::size(converted) - 1, "%*.2X", 2, i);
hexed[0] = converted[0];
hexed[1] = converted[1];
return 0;
}
static ::gpk::error_t hexToByte (const char* s, uint8_t& byte) {
char temp [3] = {s[0], s[1]};
gpk_necall(::gpk::parseIntegerHexadecimal(::gpk::vcs{temp}, &byte), "%s", "");
return 0;
}
static ::gpk::error_t hexToByte (const char* s, byte_t& byte) {
char temp [3] = {s[0], s[1]};
gpk_necall(::gpk::parseIntegerHexadecimal(::gpk::vcs{temp}, &byte), "%s", "");
return 0;
}
::gpk::error_t gpk::hexEncode (const ::gpk::view_array<const ubyte_t > & in_binary, ::gpk::array_pod<char_t > & out_hexed ) {
uint32_t offset = out_hexed.size();
gpk_necall(out_hexed.resize(offset + in_binary.size() * 2), "%s", "Out of memory?");
byte_t * pHexed = out_hexed.begin();
const ubyte_t * pBinary = in_binary.begin();
for(uint32_t iByte = 0; iByte < in_binary.size(); ++iByte)
hexFromByte(pBinary[iByte], &pHexed[offset + iByte * 2]);
return 0;
}
::gpk::error_t gpk::hexDecode (const ::gpk::view_array<const char_t > & in_hexed , ::gpk::array_pod<ubyte_t > & out_binary) {
uint32_t offset = out_binary.size();
uint32_t binarySize = in_hexed.size() >> 1;
gpk_necall(out_binary.resize(offset + binarySize), "%s", "Out of memory?");
const byte_t * pHexed = in_hexed.begin();
ubyte_t * pBinary = out_binary.begin();
for(uint32_t iByte = 0; iByte < binarySize; ++iByte)
hexToByte(&pHexed[iByte * 2], pBinary[offset + iByte]);
return 0;
}
::gpk::error_t gpk::hexDecode (const ::gpk::view_array<const char_t > & in_hexed , ::gpk::array_pod<byte_t > & out_binary) {
uint32_t offset = out_binary.size();
uint32_t binarySize = in_hexed.size() >> 1;
gpk_necall(out_binary.resize(offset + binarySize), "%s", "Out of memory?");
const byte_t * pHexed = in_hexed.begin();
byte_t * pBinary = out_binary.begin();
for(uint32_t iByte = 0; iByte < binarySize; ++iByte)
hexToByte(&pHexed[iByte * 2], pBinary[offset + iByte]);
return 0;
}
::gpk::error_t gpk::ardellEncode (::gpk::array_pod<int32_t> & cache, const ::gpk::view_array<const byte_t>& input, uint64_t key, bool salt, ::gpk::array_pod<byte_t>& output) {
// Originally written by Gary Ardell as Visual Basic code. free from all copyright restrictions.
char saltValue [4] = {};
if (salt)
for (int32_t i = 0; i < 4; i++) {
int32_t t = 100 * (1 + saltValue[i]) * rand() * (((int32_t)time(0)) + 1);
saltValue[i] = t % 256;
}
const int32_t keyFinal[8] =
{ (int32_t)(11 + (key % 233))
, (int32_t)( 7 + (key % 239))
, (int32_t)( 5 + (key % 241))
, (int32_t)( 3 + (key % 251))
};
int32_t n = salt ? input.size() + 4 : input.size();
gpk_necall(cache.resize(n), "%s", "Out of memory?");
int32_t * sn = cache.begin();
if(salt) {
for(int32_t i = 0; i < 2; ++i)
sn[i] = saltValue[i];
for(int32_t i = 0; i < n - 4; ++i)
sn[2 + i] = input[i];
for(int32_t i = 0; i < 2; ++i)
sn[2 + n + i] = saltValue[2 + i];
}
else
for(int32_t i = 0; i < n; ++i)
sn[i] = input[i];
int32_t i;
for(i = 1 ; i < n; ++i) sn[i] = sn[i] ^ sn[i - 1] ^ ((keyFinal[0] * sn[i - 1]) % 256);
for(i = n - 2 ; i >= 0; --i) sn[i] = sn[i] ^ sn[i + 1] ^ (keyFinal[1] * sn[i + 1]) % 256 ;
for(i = 2 ; i < n; ++i) sn[i] = sn[i] ^ sn[i - 2] ^ (keyFinal[2] * sn[i - 1]) % 256 ;
for(i = n - 3 ; i >= 0; --i) sn[i] = sn[i] ^ sn[i + 2] ^ (keyFinal[3] * sn[i + 1]) % 256 ;
uint32_t outputOffset = output.size();
gpk_necall(output.resize(outputOffset + n), "%s", "Out of memory?");
byte_t * outputFast = output.begin();
for( i = 0; i < n; ++i)
outputFast[outputOffset + i] = (char)sn[i];
return 0;
}
::gpk::error_t gpk::ardellDecode (::gpk::array_pod<int32_t> & cache, const ::gpk::view_array<const byte_t>& input, uint64_t key, bool salt, ::gpk::array_pod<byte_t>& output) {
// Originally written by Gary Ardell as Visual Basic code. free from all copyright restrictions.
const int32_t keyFinal[8] =
{ (int32_t)(11 + (key % 233))
, (int32_t)( 7 + (key % 239))
, (int32_t)( 5 + (key % 241))
, (int32_t)( 3 + (key % 251))
};
int32_t n = (int32_t)input.size();
gpk_necall(cache.resize(n), "%s", "Out of memory?");
int32_t * sn = cache.begin();
int32_t i;
for(i = 0 ; i < n ; ++i) sn[i] = input[i];
for(i = 0 ; i < n - 2; ++i) sn[i] = sn[i] ^ sn[i + 2] ^ (keyFinal[3] * sn[i + 1]) % 256;
for(i = n - 1 ; i >= 2 ; --i) sn[i] = sn[i] ^ sn[i - 2] ^ (keyFinal[2] * sn[i - 1]) % 256;
for(i = 0 ; i < n - 1; ++i) sn[i] = sn[i] ^ sn[i + 1] ^ (keyFinal[1] * sn[i + 1]) % 256;
for(i = n - 1 ; i >= 1 ; --i) sn[i] = sn[i] ^ sn[i - 1] ^ (keyFinal[0] * sn[i - 1]) % 256;
uint32_t outputOffset = output.size();
const uint32_t finalStringSize = salt ? n - 4 : n;
const ::gpk::view_array<const int32_t> finalValues = {salt ? &sn[2] : sn, finalStringSize};
gpk_necall(output.resize(outputOffset + finalStringSize), "%s", "Out of memory?");
byte_t * outputFast = output.begin();
const int32_t * finalValuesFast = finalValues.begin();
for( i = 0; i < (int32_t)finalStringSize; ++i)
outputFast[outputOffset + i] = (char)finalValuesFast[i];
return 0;
}
::gpk::error_t gpk::utf8FromCodePoint (uint32_t codePoint, ::gpk::array_pod<char_t> & hexDigits) {
const uint32_t offset = hexDigits.size();
if (codePoint <= 0x7f) {
hexDigits.resize(offset + 1);
hexDigits[offset + 0] = static_cast<char>(codePoint);
} else {
if (codePoint <= 0x7FF) {
hexDigits.resize(offset + 2);
hexDigits[offset + 1] = static_cast<char>(0x80 | (0x3f & codePoint));
hexDigits[offset + 0] = static_cast<char>(0xC0 | (0x1f & (codePoint >> 6)));
} else if (codePoint <= 0xFFFF) {
hexDigits.resize(offset + 3);
hexDigits[offset + 2] = static_cast<char>(0x80 | (0x3f & codePoint));
hexDigits[offset + 1] = static_cast<char>(0x80 | (0x3f & (codePoint >> 6)));
hexDigits[offset + 0] = static_cast<char>(0xE0 | (0x0f & (codePoint >> 12)));
} else if (codePoint <= 0x10FFFF) {
hexDigits.resize(offset + 4);
hexDigits[offset + 3] = static_cast<char>(0x80 | (0x3f & codePoint));
hexDigits[offset + 2] = static_cast<char>(0x80 | (0x3f & (codePoint >> 6)));
hexDigits[offset + 1] = static_cast<char>(0x80 | (0x3f & (codePoint >> 12)));
hexDigits[offset + 0] = static_cast<char>(0xF0 | (0x07 & (codePoint >> 18)));
}
}
return 0;
}
::gpk::error_t gpk::digest (const ::gpk::view_const_byte & input, ::gpk::array_pod<uint32_t> & digest) {
uint32_t x = 0;
::gpk::array_pod<uint32_t> filtered = {};
for(uint32_t i = 0; i < input.size() - 8; ++i) {
x += ::gpk::noise1DBase32(input[i])
+ ::gpk::noise1DBase32(input[i + 1])
+ ::gpk::noise1DBase32(input[i + 2])
+ ::gpk::noise1DBase32(input[i + 3])
+ ::gpk::noise1DBase32(input[i + 4])
+ ::gpk::noise1DBase32(input[i + 5])
+ ::gpk::noise1DBase32(input[i + 6])
+ ::gpk::noise1DBase32(input[i + 7])
;
x += x ^ (x << 11);
filtered.push_back(x);
}
for(uint32_t i = 0; i < filtered.size() - 8; ++i) {
filtered[i] ^= ::gpk::noise1DBase32(filtered[i])
+ ::gpk::noise1DBase32(filtered[i + 1])
+ ::gpk::noise1DBase32(filtered[i + 2])
+ ::gpk::noise1DBase32(filtered[i + 3])
+ ::gpk::noise1DBase32(filtered[i + 4])
+ ::gpk::noise1DBase32(filtered[i + 5])
+ ::gpk::noise1DBase32(filtered[i + 6])
+ ::gpk::noise1DBase32(filtered[i + 7])
;
}
for(uint32_t i = 2; i < (filtered.size() - 32); i += 2) {
for(uint32_t j = 0; j < 32; j++)
filtered[j] += filtered[i + j];
}
digest.append({filtered.begin(), ::gpk::min(32U, filtered.size())});
return 0;
}
::gpk::error_t gpk::digest (const ::gpk::view_const_byte & input, ::gpk::array_pod<byte_t> & digest) {
uint32_t x = 0;
::gpk::array_pod<uint32_t> filtered = {};
for(uint32_t i = 0; i < input.size() - 8; ++i) {
x += ::gpk::noise1DBase32(input[i])
+ ::gpk::noise1DBase32(input[i + 1])
+ ::gpk::noise1DBase32(input[i + 2])
+ ::gpk::noise1DBase32(input[i + 3])
+ ::gpk::noise1DBase32(input[i + 4])
+ ::gpk::noise1DBase32(input[i + 5])
+ ::gpk::noise1DBase32(input[i + 6])
+ ::gpk::noise1DBase32(input[i + 7])
;
x += x ^ (x << 11);
filtered.push_back(x);
}
for(uint32_t i = 0; i < filtered.size() - 8; ++i) {
filtered[i] ^= ::gpk::noise1DBase32(filtered[i])
+ ::gpk::noise1DBase32(filtered[i + 1])
+ ::gpk::noise1DBase32(filtered[i + 2])
+ ::gpk::noise1DBase32(filtered[i + 3])
+ ::gpk::noise1DBase32(filtered[i + 4])
+ ::gpk::noise1DBase32(filtered[i + 5])
+ ::gpk::noise1DBase32(filtered[i + 6])
+ ::gpk::noise1DBase32(filtered[i + 7])
;
}
for(uint32_t i = 2, count = (filtered.size() - 8); i < count; i += 2) {
for(uint32_t j = 0; j < 8; j++)
filtered[j] += filtered[i + j];
}
char temp [32] = {};
for(uint32_t i = 0; i < ::gpk::min(filtered.size(), 8U); ++i) {
snprintf(temp, ::gpk::size(temp) - 2, "%i", filtered[i]);
digest.append_string(temp);
}
return 0;
}
| 45.385827
| 201
| 0.523942
|
asm128
|
44c27f857b84d3171d72122c13641b9b0f5aeba5
| 1,400
|
cpp
|
C++
|
amr-wind/equation_systems/icns/source_terms/BodyForce.cpp
|
gdeskos/amr-wind
|
002a2bbb1538a25a06126504d507245b623413f6
|
[
"BSD-3-Clause"
] | 2
|
2022-02-16T18:00:27.000Z
|
2022-03-21T18:57:14.000Z
|
amr-wind/equation_systems/icns/source_terms/BodyForce.cpp
|
gdeskos/amr-wind
|
002a2bbb1538a25a06126504d507245b623413f6
|
[
"BSD-3-Clause"
] | 1
|
2022-02-16T21:09:49.000Z
|
2022-02-16T21:09:49.000Z
|
amr-wind/equation_systems/icns/source_terms/BodyForce.cpp
|
gdeskos/amr-wind
|
002a2bbb1538a25a06126504d507245b623413f6
|
[
"BSD-3-Clause"
] | 1
|
2022-01-04T18:15:30.000Z
|
2022-01-04T18:15:30.000Z
|
#include "amr-wind/equation_systems/icns/source_terms/BodyForce.H"
#include "amr-wind/CFDSim.H"
#include "amr-wind/utilities/trig_ops.H"
#include "AMReX_ParmParse.H"
#include "AMReX_Gpu.H"
namespace amr_wind {
namespace pde {
namespace icns {
/** Body Force
*/
BodyForce::BodyForce(const CFDSim& sim) : m_time(sim.time())
{
// Read the geostrophic wind speed vector (in m/s)
amrex::ParmParse pp("BodyForce");
pp.query("type", m_type);
m_type = amrex::toLower(m_type);
pp.getarr("magnitude", m_body_force);
if (m_type == "oscillatory") pp.get("angular_frequency", m_omega);
}
BodyForce::~BodyForce() = default;
void BodyForce::operator()(
const int lev,
const amrex::MFIter& mfi,
const amrex::Box& bx,
const FieldState fstate,
const amrex::Array4<amrex::Real>& src_term) const
{
const auto& time = m_time.current_time();
amrex::GpuArray<amrex::Real, AMREX_SPACEDIM> forcing{
{m_body_force[0], m_body_force[1], m_body_force[2]}};
amrex::Real coeff =
(m_type == "oscillatory") ? std::cos(m_omega * time) : 1.0;
amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
src_term(i, j, k, 0) += coeff * forcing[0];
src_term(i, j, k, 1) += coeff * forcing[1];
src_term(i, j, k, 2) += coeff * forcing[2];
});
}
} // namespace icns
} // namespace pde
} // namespace amr_wind
| 26.923077
| 79
| 0.649286
|
gdeskos
|
44c360e7a8e3f52a0b6390f8f47612c47ed43f14
| 339
|
cpp
|
C++
|
src/StringId.cpp
|
microsoft/gqlmapi
|
953f8c0a1c4d069c34716dfe97ede4d3ff1ddcaa
|
[
"MIT"
] | 3
|
2021-02-11T15:38:51.000Z
|
2021-12-29T15:00:13.000Z
|
src/StringId.cpp
|
microsoft/gqlmapi
|
953f8c0a1c4d069c34716dfe97ede4d3ff1ddcaa
|
[
"MIT"
] | null | null | null |
src/StringId.cpp
|
microsoft/gqlmapi
|
953f8c0a1c4d069c34716dfe97ede4d3ff1ddcaa
|
[
"MIT"
] | 3
|
2021-02-14T13:50:36.000Z
|
2021-02-14T13:50:49.000Z
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "Types.h"
#include "Unicode.h"
namespace graphql::mapi {
StringId::StringId(PCWSTR name)
: m_name { convert::utf8::to_utf8(name) }
{
}
const std::string& StringId::getName() const
{
return m_name;
}
} // namespace graphql::mapi
| 17.842105
| 60
| 0.710914
|
microsoft
|
44c4101369212356265ec2af1c92d6847e37499b
| 24,967
|
cc
|
C++
|
art/compiler/optimizing/graph_checker.cc
|
lihuibng/marshmallow
|
950cf8de3b4d63af9fc9699374e4ec45ad09b3a7
|
[
"Apache-2.0"
] | 5
|
2022-02-27T08:38:13.000Z
|
2022-03-21T03:03:49.000Z
|
art/compiler/optimizing/graph_checker.cc
|
lihuibng/marshmallow
|
950cf8de3b4d63af9fc9699374e4ec45ad09b3a7
|
[
"Apache-2.0"
] | 1
|
2022-03-08T08:20:47.000Z
|
2022-03-08T08:20:47.000Z
|
art/compiler/optimizing/graph_checker.cc
|
lihuibng/marshmallow
|
950cf8de3b4d63af9fc9699374e4ec45ad09b3a7
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2014 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.
*/
#include "graph_checker.h"
#include <map>
#include <string>
#include <sstream>
#include "base/bit_vector-inl.h"
#include "base/stringprintf.h"
namespace art {
void GraphChecker::VisitBasicBlock(HBasicBlock* block) {
current_block_ = block;
// Check consistency with respect to predecessors of `block`.
const GrowableArray<HBasicBlock*>& predecessors = block->GetPredecessors();
std::map<HBasicBlock*, size_t> predecessors_count;
for (size_t i = 0, e = predecessors.Size(); i < e; ++i) {
HBasicBlock* p = predecessors.Get(i);
++predecessors_count[p];
}
for (auto& pc : predecessors_count) {
HBasicBlock* p = pc.first;
size_t p_count_in_block_predecessors = pc.second;
const GrowableArray<HBasicBlock*>& p_successors = p->GetSuccessors();
size_t block_count_in_p_successors = 0;
for (size_t j = 0, f = p_successors.Size(); j < f; ++j) {
if (p_successors.Get(j) == block) {
++block_count_in_p_successors;
}
}
if (p_count_in_block_predecessors != block_count_in_p_successors) {
AddError(StringPrintf(
"Block %d lists %zu occurrences of block %d in its predecessors, whereas "
"block %d lists %zu occurrences of block %d in its successors.",
block->GetBlockId(), p_count_in_block_predecessors, p->GetBlockId(),
p->GetBlockId(), block_count_in_p_successors, block->GetBlockId()));
}
}
// Check consistency with respect to successors of `block`.
const GrowableArray<HBasicBlock*>& successors = block->GetSuccessors();
std::map<HBasicBlock*, size_t> successors_count;
for (size_t i = 0, e = successors.Size(); i < e; ++i) {
HBasicBlock* s = successors.Get(i);
++successors_count[s];
}
for (auto& sc : successors_count) {
HBasicBlock* s = sc.first;
size_t s_count_in_block_successors = sc.second;
const GrowableArray<HBasicBlock*>& s_predecessors = s->GetPredecessors();
size_t block_count_in_s_predecessors = 0;
for (size_t j = 0, f = s_predecessors.Size(); j < f; ++j) {
if (s_predecessors.Get(j) == block) {
++block_count_in_s_predecessors;
}
}
if (s_count_in_block_successors != block_count_in_s_predecessors) {
AddError(StringPrintf(
"Block %d lists %zu occurrences of block %d in its successors, whereas "
"block %d lists %zu occurrences of block %d in its predecessors.",
block->GetBlockId(), s_count_in_block_successors, s->GetBlockId(),
s->GetBlockId(), block_count_in_s_predecessors, block->GetBlockId()));
}
}
// Ensure `block` ends with a branch instruction.
if (!block->EndsWithControlFlowInstruction()) {
AddError(StringPrintf("Block %d does not end with a branch instruction.",
block->GetBlockId()));
}
// Visit this block's list of phis.
for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
HInstruction* current = it.Current();
// Ensure this block's list of phis contains only phis.
if (!current->IsPhi()) {
AddError(StringPrintf("Block %d has a non-phi in its phi list.",
current_block_->GetBlockId()));
}
if (current->GetNext() == nullptr && current != block->GetLastPhi()) {
AddError(StringPrintf("The recorded last phi of block %d does not match "
"the actual last phi %d.",
current_block_->GetBlockId(),
current->GetId()));
}
current->Accept(this);
}
// Visit this block's list of instructions.
for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
HInstruction* current = it.Current();
// Ensure this block's list of instructions does not contains phis.
if (current->IsPhi()) {
AddError(StringPrintf("Block %d has a phi in its non-phi list.",
current_block_->GetBlockId()));
}
if (current->GetNext() == nullptr && current != block->GetLastInstruction()) {
AddError(StringPrintf("The recorded last instruction of block %d does not match "
"the actual last instruction %d.",
current_block_->GetBlockId(),
current->GetId()));
}
current->Accept(this);
}
}
void GraphChecker::VisitBoundsCheck(HBoundsCheck* check) {
if (!GetGraph()->HasBoundsChecks()) {
AddError(StringPrintf("Instruction %s:%d is a HBoundsCheck, "
"but HasBoundsChecks() returns false",
check->DebugName(),
check->GetId()));
}
// Perform the instruction base checks too.
VisitInstruction(check);
}
void GraphChecker::VisitInstruction(HInstruction* instruction) {
if (seen_ids_.IsBitSet(instruction->GetId())) {
AddError(StringPrintf("Instruction id %d is duplicate in graph.",
instruction->GetId()));
} else {
seen_ids_.SetBit(instruction->GetId());
}
// Ensure `instruction` is associated with `current_block_`.
if (instruction->GetBlock() == nullptr) {
AddError(StringPrintf("%s %d in block %d not associated with any block.",
instruction->IsPhi() ? "Phi" : "Instruction",
instruction->GetId(),
current_block_->GetBlockId()));
} else if (instruction->GetBlock() != current_block_) {
AddError(StringPrintf("%s %d in block %d associated with block %d.",
instruction->IsPhi() ? "Phi" : "Instruction",
instruction->GetId(),
current_block_->GetBlockId(),
instruction->GetBlock()->GetBlockId()));
}
// Ensure the inputs of `instruction` are defined in a block of the graph.
for (HInputIterator input_it(instruction); !input_it.Done();
input_it.Advance()) {
HInstruction* input = input_it.Current();
const HInstructionList& list = input->IsPhi()
? input->GetBlock()->GetPhis()
: input->GetBlock()->GetInstructions();
if (!list.Contains(input)) {
AddError(StringPrintf("Input %d of instruction %d is not defined "
"in a basic block of the control-flow graph.",
input->GetId(),
instruction->GetId()));
}
}
// Ensure the uses of `instruction` are defined in a block of the graph,
// and the entry in the use list is consistent.
for (HUseIterator<HInstruction*> use_it(instruction->GetUses());
!use_it.Done(); use_it.Advance()) {
HInstruction* use = use_it.Current()->GetUser();
const HInstructionList& list = use->IsPhi()
? use->GetBlock()->GetPhis()
: use->GetBlock()->GetInstructions();
if (!list.Contains(use)) {
AddError(StringPrintf("User %s:%d of instruction %d is not defined "
"in a basic block of the control-flow graph.",
use->DebugName(),
use->GetId(),
instruction->GetId()));
}
size_t use_index = use_it.Current()->GetIndex();
if ((use_index >= use->InputCount()) || (use->InputAt(use_index) != instruction)) {
AddError(StringPrintf("User %s:%d of instruction %d has a wrong "
"UseListNode index.",
use->DebugName(),
use->GetId(),
instruction->GetId()));
}
}
// Ensure the environment uses entries are consistent.
for (HUseIterator<HEnvironment*> use_it(instruction->GetEnvUses());
!use_it.Done(); use_it.Advance()) {
HEnvironment* use = use_it.Current()->GetUser();
size_t use_index = use_it.Current()->GetIndex();
if ((use_index >= use->Size()) || (use->GetInstructionAt(use_index) != instruction)) {
AddError(StringPrintf("Environment user of %s:%d has a wrong "
"UseListNode index.",
instruction->DebugName(),
instruction->GetId()));
}
}
// Ensure 'instruction' has pointers to its inputs' use entries.
for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
HUserRecord<HInstruction*> input_record = instruction->InputRecordAt(i);
HInstruction* input = input_record.GetInstruction();
HUseListNode<HInstruction*>* use_node = input_record.GetUseNode();
size_t use_index = use_node->GetIndex();
if ((use_node == nullptr)
|| !input->GetUses().Contains(use_node)
|| (use_index >= e)
|| (use_index != i)) {
AddError(StringPrintf("Instruction %s:%d has an invalid pointer to use entry "
"at input %u (%s:%d).",
instruction->DebugName(),
instruction->GetId(),
static_cast<unsigned>(i),
input->DebugName(),
input->GetId()));
}
}
}
void GraphChecker::VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) {
VisitInstruction(invoke);
if (invoke->IsStaticWithExplicitClinitCheck()) {
size_t last_input_index = invoke->InputCount() - 1;
HInstruction* last_input = invoke->InputAt(last_input_index);
if (last_input == nullptr) {
AddError(StringPrintf("Static invoke %s:%d marked as having an explicit clinit check "
"has a null pointer as last input.",
invoke->DebugName(),
invoke->GetId()));
}
if (!last_input->IsClinitCheck() && !last_input->IsLoadClass()) {
AddError(StringPrintf("Static invoke %s:%d marked as having an explicit clinit check "
"has a last instruction (%s:%d) which is neither a clinit check "
"nor a load class instruction.",
invoke->DebugName(),
invoke->GetId(),
last_input->DebugName(),
last_input->GetId()));
}
}
}
void GraphChecker::VisitCheckCast(HCheckCast* check) {
VisitInstruction(check);
HInstruction* input = check->InputAt(1);
if (!input->IsLoadClass()) {
AddError(StringPrintf("%s:%d expects a HLoadClass as second input, not %s:%d.",
check->DebugName(),
check->GetId(),
input->DebugName(),
input->GetId()));
}
}
void GraphChecker::VisitInstanceOf(HInstanceOf* instruction) {
VisitInstruction(instruction);
HInstruction* input = instruction->InputAt(1);
if (!input->IsLoadClass()) {
AddError(StringPrintf("%s:%d expects a HLoadClass as second input, not %s:%d.",
instruction->DebugName(),
instruction->GetId(),
input->DebugName(),
input->GetId()));
}
}
void SSAChecker::VisitBasicBlock(HBasicBlock* block) {
super_type::VisitBasicBlock(block);
// Ensure there is no critical edge (i.e., an edge connecting a
// block with multiple successors to a block with multiple
// predecessors).
if (block->GetSuccessors().Size() > 1) {
for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
HBasicBlock* successor = block->GetSuccessors().Get(j);
if (successor->GetPredecessors().Size() > 1) {
AddError(StringPrintf("Critical edge between blocks %d and %d.",
block->GetBlockId(),
successor->GetBlockId()));
}
}
}
// Check Phi uniqueness (no two Phis with the same type refer to the same register).
for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
HPhi* phi = it.Current()->AsPhi();
if (phi->GetNextEquivalentPhiWithSameType() != nullptr) {
std::stringstream type_str;
type_str << phi->GetType();
AddError(StringPrintf("Equivalent phi (%d) found for VReg %d with type: %s",
phi->GetId(), phi->GetRegNumber(), type_str.str().c_str()));
}
}
if (block->IsLoopHeader()) {
CheckLoop(block);
}
}
void SSAChecker::CheckLoop(HBasicBlock* loop_header) {
int id = loop_header->GetBlockId();
HLoopInformation* loop_information = loop_header->GetLoopInformation();
// Ensure the pre-header block is first in the list of
// predecessors of a loop header.
if (!loop_header->IsLoopPreHeaderFirstPredecessor()) {
AddError(StringPrintf(
"Loop pre-header is not the first predecessor of the loop header %d.",
id));
}
// Ensure the loop header has only one incoming branch and the remaining
// predecessors are back edges.
size_t num_preds = loop_header->GetPredecessors().Size();
if (num_preds < 2) {
AddError(StringPrintf(
"Loop header %d has less than two predecessors: %zu.",
id,
num_preds));
} else {
HBasicBlock* first_predecessor = loop_header->GetPredecessors().Get(0);
if (loop_information->IsBackEdge(*first_predecessor)) {
AddError(StringPrintf(
"First predecessor of loop header %d is a back edge.",
id));
}
for (size_t i = 1, e = loop_header->GetPredecessors().Size(); i < e; ++i) {
HBasicBlock* predecessor = loop_header->GetPredecessors().Get(i);
if (!loop_information->IsBackEdge(*predecessor)) {
AddError(StringPrintf(
"Loop header %d has multiple incoming (non back edge) blocks.",
id));
}
}
}
const ArenaBitVector& loop_blocks = loop_information->GetBlocks();
// Ensure back edges belong to the loop.
size_t num_back_edges = loop_information->GetBackEdges().Size();
if (num_back_edges == 0) {
AddError(StringPrintf(
"Loop defined by header %d has no back edge.",
id));
} else {
for (size_t i = 0; i < num_back_edges; ++i) {
int back_edge_id = loop_information->GetBackEdges().Get(i)->GetBlockId();
if (!loop_blocks.IsBitSet(back_edge_id)) {
AddError(StringPrintf(
"Loop defined by header %d has an invalid back edge %d.",
id,
back_edge_id));
}
}
}
// Ensure all blocks in the loop are live and dominated by the loop header.
for (uint32_t i : loop_blocks.Indexes()) {
HBasicBlock* loop_block = GetGraph()->GetBlocks().Get(i);
if (loop_block == nullptr) {
AddError(StringPrintf("Loop defined by header %d contains a previously removed block %d.",
id,
i));
} else if (!loop_header->Dominates(loop_block)) {
AddError(StringPrintf("Loop block %d not dominated by loop header %d.",
i,
id));
}
}
// If this is a nested loop, ensure the outer loops contain a superset of the blocks.
for (HLoopInformationOutwardIterator it(*loop_header); !it.Done(); it.Advance()) {
HLoopInformation* outer_info = it.Current();
if (!loop_blocks.IsSubsetOf(&outer_info->GetBlocks())) {
AddError(StringPrintf("Blocks of loop defined by header %d are not a subset of blocks of "
"an outer loop defined by header %d.",
id,
outer_info->GetHeader()->GetBlockId()));
}
}
}
void SSAChecker::VisitInstruction(HInstruction* instruction) {
super_type::VisitInstruction(instruction);
// Ensure an instruction dominates all its uses.
for (HUseIterator<HInstruction*> use_it(instruction->GetUses());
!use_it.Done(); use_it.Advance()) {
HInstruction* use = use_it.Current()->GetUser();
if (!use->IsPhi() && !instruction->StrictlyDominates(use)) {
AddError(StringPrintf("Instruction %d in block %d does not dominate "
"use %d in block %d.",
instruction->GetId(), current_block_->GetBlockId(),
use->GetId(), use->GetBlock()->GetBlockId()));
}
}
// Ensure an instruction having an environment is dominated by the
// instructions contained in the environment.
for (HEnvironment* environment = instruction->GetEnvironment();
environment != nullptr;
environment = environment->GetParent()) {
for (size_t i = 0, e = environment->Size(); i < e; ++i) {
HInstruction* env_instruction = environment->GetInstructionAt(i);
if (env_instruction != nullptr
&& !env_instruction->StrictlyDominates(instruction)) {
AddError(StringPrintf("Instruction %d in environment of instruction %d "
"from block %d does not dominate instruction %d.",
env_instruction->GetId(),
instruction->GetId(),
current_block_->GetBlockId(),
instruction->GetId()));
}
}
}
}
static Primitive::Type PrimitiveKind(Primitive::Type type) {
switch (type) {
case Primitive::kPrimBoolean:
case Primitive::kPrimByte:
case Primitive::kPrimShort:
case Primitive::kPrimChar:
case Primitive::kPrimInt:
return Primitive::kPrimInt;
default:
return type;
}
}
void SSAChecker::VisitPhi(HPhi* phi) {
VisitInstruction(phi);
// Ensure the first input of a phi is not itself.
if (phi->InputAt(0) == phi) {
AddError(StringPrintf("Loop phi %d in block %d is its own first input.",
phi->GetId(),
phi->GetBlock()->GetBlockId()));
}
// Ensure the number of inputs of a phi is the same as the number of
// its predecessors.
const GrowableArray<HBasicBlock*>& predecessors =
phi->GetBlock()->GetPredecessors();
if (phi->InputCount() != predecessors.Size()) {
AddError(StringPrintf(
"Phi %d in block %d has %zu inputs, "
"but block %d has %zu predecessors.",
phi->GetId(), phi->GetBlock()->GetBlockId(), phi->InputCount(),
phi->GetBlock()->GetBlockId(), predecessors.Size()));
} else {
// Ensure phi input at index I either comes from the Ith
// predecessor or from a block that dominates this predecessor.
for (size_t i = 0, e = phi->InputCount(); i < e; ++i) {
HInstruction* input = phi->InputAt(i);
HBasicBlock* predecessor = predecessors.Get(i);
if (!(input->GetBlock() == predecessor
|| input->GetBlock()->Dominates(predecessor))) {
AddError(StringPrintf(
"Input %d at index %zu of phi %d from block %d is not defined in "
"predecessor number %zu nor in a block dominating it.",
input->GetId(), i, phi->GetId(), phi->GetBlock()->GetBlockId(),
i));
}
}
}
// Ensure that the inputs have the same primitive kind as the phi.
for (size_t i = 0, e = phi->InputCount(); i < e; ++i) {
HInstruction* input = phi->InputAt(i);
if (PrimitiveKind(input->GetType()) != PrimitiveKind(phi->GetType())) {
AddError(StringPrintf(
"Input %d at index %zu of phi %d from block %d does not have the "
"same type as the phi: %s versus %s",
input->GetId(), i, phi->GetId(), phi->GetBlock()->GetBlockId(),
Primitive::PrettyDescriptor(input->GetType()),
Primitive::PrettyDescriptor(phi->GetType())));
}
}
if (phi->GetType() != HPhi::ToPhiType(phi->GetType())) {
AddError(StringPrintf("Phi %d in block %d does not have an expected phi type: %s",
phi->GetId(),
phi->GetBlock()->GetBlockId(),
Primitive::PrettyDescriptor(phi->GetType())));
}
}
void SSAChecker::HandleBooleanInput(HInstruction* instruction, size_t input_index) {
HInstruction* input = instruction->InputAt(input_index);
if (input->IsIntConstant()) {
int32_t value = input->AsIntConstant()->GetValue();
if (value != 0 && value != 1) {
AddError(StringPrintf(
"%s instruction %d has a non-Boolean constant input %d whose value is: %d.",
instruction->DebugName(),
instruction->GetId(),
static_cast<int>(input_index),
value));
}
} else if (input->GetType() == Primitive::kPrimInt
&& (input->IsPhi() || input->IsAnd() || input->IsOr() || input->IsXor())) {
// TODO: We need a data-flow analysis to determine if the Phi or
// binary operation is actually Boolean. Allow for now.
} else if (input->GetType() != Primitive::kPrimBoolean) {
AddError(StringPrintf(
"%s instruction %d has a non-Boolean input %d whose type is: %s.",
instruction->DebugName(),
instruction->GetId(),
static_cast<int>(input_index),
Primitive::PrettyDescriptor(input->GetType())));
}
}
void SSAChecker::VisitIf(HIf* instruction) {
VisitInstruction(instruction);
HandleBooleanInput(instruction, 0);
}
void SSAChecker::VisitBooleanNot(HBooleanNot* instruction) {
VisitInstruction(instruction);
HandleBooleanInput(instruction, 0);
}
void SSAChecker::VisitCondition(HCondition* op) {
VisitInstruction(op);
if (op->GetType() != Primitive::kPrimBoolean) {
AddError(StringPrintf(
"Condition %s %d has a non-Boolean result type: %s.",
op->DebugName(), op->GetId(),
Primitive::PrettyDescriptor(op->GetType())));
}
HInstruction* lhs = op->InputAt(0);
HInstruction* rhs = op->InputAt(1);
if (PrimitiveKind(lhs->GetType()) != PrimitiveKind(rhs->GetType())) {
AddError(StringPrintf(
"Condition %s %d has inputs of different types: %s, and %s.",
op->DebugName(), op->GetId(),
Primitive::PrettyDescriptor(lhs->GetType()),
Primitive::PrettyDescriptor(rhs->GetType())));
}
if (!op->IsEqual() && !op->IsNotEqual()) {
if ((lhs->GetType() == Primitive::kPrimNot)) {
AddError(StringPrintf(
"Condition %s %d uses an object as left-hand side input.",
op->DebugName(), op->GetId()));
} else if (rhs->GetType() == Primitive::kPrimNot) {
AddError(StringPrintf(
"Condition %s %d uses an object as right-hand side input.",
op->DebugName(), op->GetId()));
}
}
}
void SSAChecker::VisitBinaryOperation(HBinaryOperation* op) {
VisitInstruction(op);
if (op->IsUShr() || op->IsShr() || op->IsShl()) {
if (PrimitiveKind(op->InputAt(1)->GetType()) != Primitive::kPrimInt) {
AddError(StringPrintf(
"Shift operation %s %d has a non-int kind second input: "
"%s of type %s.",
op->DebugName(), op->GetId(),
op->InputAt(1)->DebugName(),
Primitive::PrettyDescriptor(op->InputAt(1)->GetType())));
}
} else {
if (PrimitiveKind(op->InputAt(0)->GetType()) != PrimitiveKind(op->InputAt(1)->GetType())) {
AddError(StringPrintf(
"Binary operation %s %d has inputs of different types: "
"%s, and %s.",
op->DebugName(), op->GetId(),
Primitive::PrettyDescriptor(op->InputAt(0)->GetType()),
Primitive::PrettyDescriptor(op->InputAt(1)->GetType())));
}
}
if (op->IsCompare()) {
if (op->GetType() != Primitive::kPrimInt) {
AddError(StringPrintf(
"Compare operation %d has a non-int result type: %s.",
op->GetId(),
Primitive::PrettyDescriptor(op->GetType())));
}
} else {
// Use the first input, so that we can also make this check for shift operations.
if (PrimitiveKind(op->GetType()) != PrimitiveKind(op->InputAt(0)->GetType())) {
AddError(StringPrintf(
"Binary operation %s %d has a result type different "
"from its input type: %s vs %s.",
op->DebugName(), op->GetId(),
Primitive::PrettyDescriptor(op->GetType()),
Primitive::PrettyDescriptor(op->InputAt(0)->GetType())));
}
}
}
void SSAChecker::VisitConstant(HConstant* instruction) {
HBasicBlock* block = instruction->GetBlock();
if (!block->IsEntryBlock()) {
AddError(StringPrintf(
"%s %d should be in the entry block but is in block %d.",
instruction->DebugName(),
instruction->GetId(),
block->GetBlockId()));
}
}
} // namespace art
| 40.269355
| 96
| 0.597669
|
lihuibng
|
44c476f120a0f728f5d117f3ae8b0b0a1bc487dd
| 21,386
|
cpp
|
C++
|
BonDriver_Proxy.cpp
|
epgdatacapbon/BonDriverProxy_Linux
|
3d778b07354820a8f60b50b07fffbc334cec15a0
|
[
"MIT"
] | 30
|
2015-01-27T15:34:50.000Z
|
2021-01-24T12:50:04.000Z
|
BonDriver_Proxy.cpp
|
epgdatacapbon/BonDriverProxy_Linux
|
3d778b07354820a8f60b50b07fffbc334cec15a0
|
[
"MIT"
] | 1
|
2017-01-31T06:52:10.000Z
|
2017-01-31T06:52:10.000Z
|
BonDriver_Proxy.cpp
|
epgdatacapbon/BonDriverProxy_Linux
|
3d778b07354820a8f60b50b07fffbc334cec15a0
|
[
"MIT"
] | 16
|
2015-04-11T02:06:11.000Z
|
2022-01-28T04:02:31.000Z
|
#include "BonDriver_Proxy.h"
namespace BonDriver_Proxy {
static BOOL IsTagMatch(const char *line, const char *tag, char **value)
{
const int taglen = ::strlen(tag);
const char *p;
if (::strncmp(line, tag, taglen) != 0)
return FALSE;
p = line + taglen;
while (*p == ' ' || *p == '\t')
p++;
if (value == NULL && *p == '\0')
return TRUE;
if (*p++ != '=')
return FALSE;
while (*p == ' ' || *p == '\t')
p++;
*value = const_cast<char *>(p);
return TRUE;
}
static int Init()
{
FILE *fp;
char *p, buf[512];
Dl_info info;
if (::dladdr((void *)Init, &info) == 0)
return -1;
::strncpy(buf, info.dli_fname, sizeof(buf) - 8);
buf[sizeof(buf) - 8] = '\0';
::strcat(buf, ".conf");
fp = ::fopen(buf, "r");
if (fp == NULL)
return -2;
BOOL bHost, bPort, bBonDriver, bChannelLock, bConnectTimeOut, bUseMagicPacket;
BOOL bTargetHost, bTargetPort, bTargetMac;
BOOL bPacketFifoSize, bTsFifoSize, bTsPacketBufSize;
bHost = bPort = bBonDriver = bChannelLock = bConnectTimeOut = bUseMagicPacket = FALSE;
bTargetHost = bTargetPort = bTargetMac = FALSE;
bPacketFifoSize = bTsFifoSize = bTsPacketBufSize = FALSE;
while (::fgets(buf, sizeof(buf), fp))
{
if (buf[0] == ';')
continue;
p = buf + ::strlen(buf) - 1;
while ((p >= buf) && (*p == '\r' || *p == '\n'))
*p-- = '\0';
if (p < buf)
continue;
if (!bHost && IsTagMatch(buf, "ADDRESS", &p))
{
::strncpy(g_Host, p, sizeof(g_Host) - 1);
g_Host[sizeof(g_Host) - 1] = '\0';
bHost = TRUE;
}
else if (!bPort && IsTagMatch(buf, "PORT", &p))
{
::strncpy(g_Port, p, sizeof(g_Port) - 1);
g_Port[sizeof(g_Port) - 1] = '\0';
bPort = TRUE;
}
else if (!bBonDriver && IsTagMatch(buf, "BONDRIVER", &p))
{
::strncpy(g_BonDriver, p, sizeof(g_BonDriver) - 1);
g_BonDriver[sizeof(g_BonDriver) - 1] = '\0';
bBonDriver = TRUE;
}
else if (!bChannelLock && IsTagMatch(buf, "CHANNEL_LOCK", &p))
{
g_ChannelLock = (BYTE)::atoi(p);
bChannelLock = TRUE;
}
else if (!bConnectTimeOut && IsTagMatch(buf, "CONNECT_TIMEOUT", &p))
{
g_ConnectTimeOut = ::atoi(p);
bConnectTimeOut = TRUE;
}
else if (!bUseMagicPacket && IsTagMatch(buf, "USE_MAGICPACKET", &p))
{
g_UseMagicPacket = ::atoi(p);
bUseMagicPacket = TRUE;
}
else if (!bTargetHost && IsTagMatch(buf, "TARGET_ADDRESS", &p))
{
::strncpy(g_TargetHost, p, sizeof(g_TargetHost) - 1);
g_TargetHost[sizeof(g_TargetHost) - 1] = '\0';
bTargetHost = TRUE;
}
else if (!bTargetPort && IsTagMatch(buf, "TARGET_PORT", &p))
{
::strncpy(g_TargetPort, p, sizeof(g_TargetPort) - 1);
g_TargetPort[sizeof(g_TargetPort) - 1] = '\0';
bTargetPort = TRUE;
}
else if (!bTargetMac && IsTagMatch(buf, "TARGET_MACADDRESS", &p))
{
char mac[32];
::memset(mac, 0, sizeof(mac));
::strncpy(mac, p, sizeof(mac) - 1);
BOOL bErr = FALSE;
for (int i = 0; i < 6 && !bErr; i++)
{
BYTE b = 0;
p = &mac[i * 3];
for (int j = 0; j < 2 && !bErr; j++)
{
if ('0' <= *p && *p <= '9')
b = b * 0x10 + (*p - '0');
else if ('A' <= *p && *p <= 'F')
b = b * 0x10 + (*p - 'A' + 10);
else if ('a' <= *p && *p <= 'f')
b = b * 0x10 + (*p - 'a' + 10);
else
bErr = TRUE;
p++;
}
g_TargetMac[i] = b;
}
if (!bErr)
bTargetMac = TRUE;
}
else if (!bPacketFifoSize && IsTagMatch(buf, "PACKET_FIFO_SIZE", &p))
{
g_PacketFifoSize = ::atoi(p);
bPacketFifoSize = TRUE;
}
else if (!bTsFifoSize && IsTagMatch(buf, "TS_FIFO_SIZE", &p))
{
g_TsFifoSize = ::atoi(p);
bTsFifoSize = TRUE;
}
else if (!bTsPacketBufSize && IsTagMatch(buf, "TSPACKET_BUFSIZE", &p))
{
g_TsPacketBufSize = ::atoi(p);
bTsPacketBufSize = TRUE;
}
}
::fclose(fp);
if (!bHost || !bPort || !bBonDriver)
return -3;
if (g_UseMagicPacket)
{
if (!bTargetMac)
return -4;
if (!bTargetHost)
::strcpy(g_TargetHost, g_Host);
if (!bTargetPort)
::strcpy(g_TargetPort, g_Port);
}
return 0;
}
cProxyClient::cProxyClient() : m_Error(m_c, m_m), m_SingleShot(m_c, m_m), m_fifoSend(m_c, m_m), m_fifoRecv(m_c, m_m), m_fifoTS(m_c, m_m)
{
m_s = INVALID_SOCKET;
m_LastBuf = NULL;
m_dwBufPos = 0;
::memset(m_pBuf, 0, sizeof(m_pBuf));
m_bBonDriver = m_bTuner = m_bRereased = m_bWaitCNR = FALSE;
m_fSignalLevel = 0;
m_dwSpace = m_dwChannel = 0x7fffffff; // INT_MAX
m_hThread = 0;
// m_iEndCount = -1;
size_t n = 0;
char *p = (char *)TUNER_NAME;
for (;;)
{
m_TunerName[n++] = *p;
m_TunerName[n++] = '\0';
if ((*p++ == '\0') || (n > (sizeof(m_TunerName) - 2)))
break;
}
m_TunerName[sizeof(m_TunerName) - 2] = '\0';
m_TunerName[sizeof(m_TunerName) - 1] = '\0';
pthread_mutexattr_t attr;
::pthread_mutexattr_init(&attr);
::pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
::pthread_mutex_init(&m_m, &attr);
::pthread_cond_init(&m_c, NULL);
m_SingleShot.SetAutoReset(TRUE);
int i;
for (i = 0; i < ebResNum; i++)
{
m_bResEvent[i] = new cEvent(m_c, m_m);
m_bResEvent[i]->SetAutoReset(TRUE);
}
for (i = 0; i < edwResNum; i++)
{
m_dwResEvent[i] = new cEvent(m_c, m_m);
m_dwResEvent[i]->SetAutoReset(TRUE);
}
for (i = 0; i < epResNum; i++)
{
m_pResEvent[i] = new cEvent(m_c, m_m);
m_pResEvent[i]->SetAutoReset(TRUE);
}
}
cProxyClient::~cProxyClient()
{
if (!m_bRereased)
{
if (m_bTuner)
CloseTuner();
makePacket(eRelease);
}
m_Error.Set();
// if (m_iEndCount != -1)
// SleepLock(3);
if (m_hThread != 0)
::pthread_join(m_hThread, NULL);
int i;
{
LOCK(m_writeLock);
for (i = 0; i < 8; i++)
delete[] m_pBuf[i];
TsFlush();
delete m_LastBuf;
}
for (i = 0; i < ebResNum; i++)
delete m_bResEvent[i];
for (i = 0; i < edwResNum; i++)
delete m_dwResEvent[i];
for (i = 0; i < epResNum; i++)
delete m_pResEvent[i];
::pthread_cond_destroy(&m_c);
::pthread_mutex_destroy(&m_m);
if (m_s != INVALID_SOCKET)
::close(m_s);
}
void *cProxyClient::ProcessEntry(LPVOID pv)
{
cProxyClient *pProxy = static_cast<cProxyClient *>(pv);
DWORD &ret = pProxy->m_tRet;
ret = pProxy->Process();
// pProxy->m_iEndCount++;
return &ret;
}
DWORD cProxyClient::Process()
{
pthread_t hThread[2];
if (::pthread_create(&hThread[0], NULL, cProxyClient::Sender, this))
{
m_Error.Set();
return 1;
}
if (::pthread_create(&hThread[1], NULL, cProxyClient::Receiver, this))
{
m_Error.Set();
::pthread_join(hThread[0], NULL);
return 2;
}
// m_iEndCount = 0;
m_SingleShot.Set();
cEvent *h[2] = { &m_Error, m_fifoRecv.GetEventHandle() };
for (;;)
{
DWORD dwRet = cEvent::MultipleWait(2, h);
switch (dwRet)
{
case WAIT_OBJECT_0:
goto end;
case WAIT_OBJECT_0 + 1:
{
int idx;
cPacketHolder *pPh = NULL;
m_fifoRecv.Pop(&pPh);
switch (pPh->GetCommand())
{
case eSelectBonDriver:
idx = ebResSelectBonDriver;
goto bres;
case eCreateBonDriver:
idx = ebResCreateBonDriver;
goto bres;
case eOpenTuner:
idx = ebResOpenTuner;
goto bres;
case ePurgeTsStream:
idx = ebResPurgeTsStream;
goto bres;
case eSetLnbPower:
idx = ebResSetLnbPower;
bres:
{
LOCK(m_readLock);
if (pPh->GetBodyLength() != sizeof(BYTE))
m_bRes[idx] = FALSE;
else
m_bRes[idx] = pPh->m_pPacket->payload[0];
m_bResEvent[idx]->Set();
break;
}
case eGetTsStream:
if (pPh->GetBodyLength() >= (sizeof(DWORD) * 2))
{
DWORD *pdw = (DWORD *)(pPh->m_pPacket->payload);
DWORD dwSize = ntohl(*pdw);
// 変なパケットは廃棄(正規のサーバに繋いでいる場合は来る事はないハズ)
if ((pPh->GetBodyLength() - (sizeof(DWORD) * 2)) == dwSize)
{
union {
DWORD dw;
float f;
} u;
pdw = (DWORD *)(&(pPh->m_pPacket->payload[sizeof(DWORD)]));
u.dw = ntohl(*pdw);
m_fSignalLevel = u.f;
m_bWaitCNR = FALSE;
pPh->SetDeleteFlag(FALSE);
TS_DATA *pData = new TS_DATA();
pData->dwSize = dwSize;
pData->pbBufHead = pPh->m_pBuf;
pData->pbBuf = &(pPh->m_pPacket->payload[sizeof(DWORD) * 2]);
m_fifoTS.Push(pData);
}
}
break;
case eEnumTuningSpace:
idx = epResEnumTuningSpace;
goto pres;
case eEnumChannelName:
idx = epResEnumChannelName;
pres:
{
LOCK(m_writeLock);
if (m_dwBufPos >= 8)
m_dwBufPos = 0;
if (m_pBuf[m_dwBufPos])
delete[] m_pBuf[m_dwBufPos];
if (pPh->GetBodyLength() == sizeof(TCHAR))
m_pBuf[m_dwBufPos] = NULL;
else
{
DWORD dw = pPh->GetBodyLength();
m_pBuf[m_dwBufPos] = (TCHAR *)(new BYTE[dw]);
::memcpy(m_pBuf[m_dwBufPos], pPh->m_pPacket->payload, dw);
}
{
LOCK(m_readLock);
m_pRes[idx] = m_pBuf[m_dwBufPos++];
m_pResEvent[idx]->Set();
}
break;
}
case eSetChannel2:
idx = edwResSetChannel2;
goto dwres;
case eGetTotalDeviceNum:
idx = edwResGetTotalDeviceNum;
goto dwres;
case eGetActiveDeviceNum:
idx = edwResGetActiveDeviceNum;
dwres:
{
LOCK(m_readLock);
if (pPh->GetBodyLength() != sizeof(DWORD))
m_dwRes[idx] = 0;
else
{
DWORD *pdw = (DWORD *)(pPh->m_pPacket->payload);
m_dwRes[idx] = ntohl(*pdw);
}
m_dwResEvent[idx]->Set();
break;
}
default:
break;
}
delete pPh;
break;
}
default:
// 何かのエラー
m_Error.Set();
goto end;
}
}
end:
// SleepLock(2);
::pthread_join(hThread[0], NULL);
::pthread_join(hThread[1], NULL);
return 0;
}
int cProxyClient::ReceiverHelper(char *pDst, DWORD left)
{
int len, ret;
fd_set rd;
timeval tv;
while (left > 0)
{
if (m_Error.IsSet())
return -1;
FD_ZERO(&rd);
FD_SET(m_s, &rd);
tv.tv_sec = 1;
tv.tv_usec = 0;
if ((len = ::select((int)(m_s + 1), &rd, NULL, NULL, &tv)) == SOCKET_ERROR)
{
ret = -2;
goto err;
}
if (len == 0)
continue;
if ((len = ::recv(m_s, pDst, left, 0)) <= 0)
{
ret = -3;
goto err;
}
left -= len;
pDst += len;
}
return 0;
err:
m_Error.Set();
return ret;
}
void *cProxyClient::Receiver(LPVOID pv)
{
cProxyClient *pProxy = static_cast<cProxyClient *>(pv);
DWORD left, &ret = pProxy->m_tRet;
char *p;
cPacketHolder *pPh = NULL;
const DWORD MaxPacketBufSize = g_TsPacketBufSize + (sizeof(DWORD) * 2);
for (;;)
{
pPh = new cPacketHolder(MaxPacketBufSize);
left = sizeof(stPacketHead);
p = (char *)&(pPh->m_pPacket->head);
if (pProxy->ReceiverHelper(p, left) != 0)
{
ret = 201;
goto end;
}
if (!pPh->IsValid())
{
pProxy->m_Error.Set();
ret = 202;
goto end;
}
left = pPh->GetBodyLength();
if (left == 0)
{
pProxy->m_fifoRecv.Push(pPh);
continue;
}
if (left > MaxPacketBufSize)
{
pProxy->m_Error.Set();
ret = 203;
goto end;
}
p = (char *)(pPh->m_pPacket->payload);
if (pProxy->ReceiverHelper(p, left) != 0)
{
ret = 204;
goto end;
}
pProxy->m_fifoRecv.Push(pPh);
}
end:
delete pPh;
// pProxy->m_iEndCount++;
return &ret;
}
void cProxyClient::makePacket(enumCommand eCmd)
{
cPacketHolder *p = new cPacketHolder(eCmd, 0);
m_fifoSend.Push(p);
}
void cProxyClient::makePacket(enumCommand eCmd, LPCSTR str)
{
register size_t size = (::strlen(str) + 1);
cPacketHolder *p = new cPacketHolder(eCmd, size);
::memcpy(p->m_pPacket->payload, str, size);
m_fifoSend.Push(p);
}
void cProxyClient::makePacket(enumCommand eCmd, BOOL b)
{
cPacketHolder *p = new cPacketHolder(eCmd, sizeof(BYTE));
p->m_pPacket->payload[0] = (BYTE)b;
m_fifoSend.Push(p);
}
void cProxyClient::makePacket(enumCommand eCmd, DWORD dw)
{
cPacketHolder *p = new cPacketHolder(eCmd, sizeof(DWORD));
DWORD *pos = (DWORD *)(p->m_pPacket->payload);
*pos = htonl(dw);
m_fifoSend.Push(p);
}
void cProxyClient::makePacket(enumCommand eCmd, DWORD dw1, DWORD dw2)
{
cPacketHolder *p = new cPacketHolder(eCmd, sizeof(DWORD) * 2);
DWORD *pos = (DWORD *)(p->m_pPacket->payload);
*pos++ = htonl(dw1);
*pos = htonl(dw2);
m_fifoSend.Push(p);
}
void cProxyClient::makePacket(enumCommand eCmd, DWORD dw1, DWORD dw2, BYTE b)
{
cPacketHolder *p = new cPacketHolder(eCmd, (sizeof(DWORD) * 2) + sizeof(BYTE));
DWORD *pos = (DWORD *)(p->m_pPacket->payload);
*pos++ = htonl(dw1);
*pos++ = htonl(dw2);
*(BYTE *)pos = b;
m_fifoSend.Push(p);
}
void *cProxyClient::Sender(LPVOID pv)
{
cProxyClient *pProxy = static_cast<cProxyClient *>(pv);
DWORD &ret = pProxy->m_tRet;
cEvent *h[2] = { &(pProxy->m_Error), pProxy->m_fifoSend.GetEventHandle() };
for (;;)
{
DWORD dwRet = cEvent::MultipleWait(2, h);
switch (dwRet)
{
case WAIT_OBJECT_0:
ret = 101;
goto end;
case WAIT_OBJECT_0 + 1:
{
cPacketHolder *pPh = NULL;
pProxy->m_fifoSend.Pop(&pPh);
int left = (int)pPh->m_Size;
char *p = (char *)(pPh->m_pPacket);
while (left > 0)
{
int len = ::send(pProxy->m_s, p, left, 0);
if (len == SOCKET_ERROR)
{
pProxy->m_Error.Set();
break;
}
left -= len;
p += len;
}
delete pPh;
break;
}
default:
// 何かのエラー
pProxy->m_Error.Set();
ret = 102;
goto end;
}
}
end:
// pProxy->m_iEndCount++;
return &ret;
}
BOOL cProxyClient::SelectBonDriver()
{
{
LOCK(g_Lock);
makePacket(eSelectBonDriver, g_BonDriver);
}
if (m_bResEvent[ebResSelectBonDriver]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
return m_bRes[ebResSelectBonDriver];
}
return FALSE;
}
BOOL cProxyClient::CreateBonDriver()
{
makePacket(eCreateBonDriver);
if (m_bResEvent[ebResCreateBonDriver]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
if (m_bRes[ebResCreateBonDriver])
m_bBonDriver = TRUE;
return m_bRes[ebResCreateBonDriver];
}
return FALSE;
}
const BOOL cProxyClient::OpenTuner(void)
{
if (!m_bBonDriver)
return FALSE;
makePacket(eOpenTuner);
if (m_bResEvent[ebResOpenTuner]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
if (m_bRes[ebResOpenTuner])
m_bTuner = TRUE;
return m_bRes[ebResOpenTuner];
}
return FALSE;
}
void cProxyClient::CloseTuner(void)
{
if (!m_bTuner)
return;
makePacket(eCloseTuner);
m_bTuner = m_bWaitCNR = FALSE;
m_fSignalLevel = 0;
m_dwSpace = m_dwChannel = 0x7fffffff; // INT_MAX
{
LOCK(m_writeLock);
m_dwBufPos = 0;
for (int i = 0; i < 8; i++)
delete[] m_pBuf[i];
::memset(m_pBuf, 0, sizeof(m_pBuf));
}
}
const BOOL cProxyClient::SetChannel(const BYTE bCh)
{
return TRUE;
}
const float cProxyClient::GetSignalLevel(void)
{
// イベントでやろうかと思ったけど、デッドロックを防ぐ為には発生する処理の回数の内大半では
// 全く無駄なイベント処理が発生する事になるので、ポーリングでやる事にした
// なお、絶妙なタイミングでのネットワーク切断等に備えて、最大でも約0.5秒までしか待たない
timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 10 * 1000 * 1000;
for (int i = 0; m_bWaitCNR && (i < 50); i++)
::nanosleep(&ts, NULL);
return m_fSignalLevel;
}
const DWORD cProxyClient::WaitTsStream(const DWORD dwTimeOut)
{
if (!m_bTuner)
return WAIT_ABANDONED;
if (m_fifoTS.Size() != 0)
return WAIT_OBJECT_0;
else
return WAIT_TIMEOUT; // 手抜き
}
const DWORD cProxyClient::GetReadyCount(void)
{
if (!m_bTuner)
return 0;
return (DWORD)m_fifoTS.Size();
}
const BOOL cProxyClient::GetTsStream(BYTE *pDst, DWORD *pdwSize, DWORD *pdwRemain)
{
if (!m_bTuner)
return FALSE;
BYTE *pSrc;
if (GetTsStream(&pSrc, pdwSize, pdwRemain))
{
if (*pdwSize)
::memcpy(pDst, pSrc, *pdwSize);
return TRUE;
}
return FALSE;
}
const BOOL cProxyClient::GetTsStream(BYTE **ppDst, DWORD *pdwSize, DWORD *pdwRemain)
{
if (!m_bTuner)
return FALSE;
BOOL b;
{
LOCK(m_writeLock);
if (m_fifoTS.Size() != 0)
{
delete m_LastBuf;
m_fifoTS.Pop(&m_LastBuf);
*ppDst = m_LastBuf->pbBuf;
*pdwSize = m_LastBuf->dwSize;
*pdwRemain = (DWORD)m_fifoTS.Size();
b = TRUE;
}
else
{
*pdwSize = 0;
*pdwRemain = 0;
b = FALSE;
}
}
return b;
}
void cProxyClient::PurgeTsStream(void)
{
if (!m_bTuner)
return;
makePacket(ePurgeTsStream);
if (m_bResEvent[ebResPurgeTsStream]->Wait(&m_Error) != WAIT_OBJECT_0)
{
BOOL b;
{
LOCK(m_readLock);
b = m_bRes[ebResPurgeTsStream];
}
if (b)
{
LOCK(m_writeLock);
TsFlush();
}
}
}
void cProxyClient::Release(void)
{
if (m_bTuner)
CloseTuner();
makePacket(eRelease);
m_bRereased = TRUE;
{
LOCK(g_Lock);
g_InstanceList.remove(this);
}
delete this;
}
LPCTSTR cProxyClient::GetTunerName(void)
{
return (LPCTSTR)m_TunerName;
}
const BOOL cProxyClient::IsTunerOpening(void)
{
return FALSE;
}
LPCTSTR cProxyClient::EnumTuningSpace(const DWORD dwSpace)
{
if (!m_bTuner)
return NULL;
makePacket(eEnumTuningSpace, dwSpace);
if (m_pResEvent[epResEnumTuningSpace]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
return m_pRes[epResEnumTuningSpace];
}
return NULL;
}
LPCTSTR cProxyClient::EnumChannelName(const DWORD dwSpace, const DWORD dwChannel)
{
if (!m_bTuner)
return NULL;
makePacket(eEnumChannelName, dwSpace, dwChannel);
if (m_pResEvent[epResEnumChannelName]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
return m_pRes[epResEnumChannelName];
}
return NULL;
}
const BOOL cProxyClient::SetChannel(const DWORD dwSpace, const DWORD dwChannel)
{
if (!m_bTuner)
goto err;
// if ((m_dwSpace == dwSpace) && (m_dwChannel == dwChannel))
// return TRUE;
makePacket(eSetChannel2, dwSpace, dwChannel, g_ChannelLock);
DWORD dw;
if (m_dwResEvent[edwResSetChannel2]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
dw = m_dwRes[edwResSetChannel2];
}
else
dw = 0xff;
switch (dw)
{
case 0x00: // 成功
{
LOCK(m_writeLock);
TsFlush();
m_dwSpace = dwSpace;
m_dwChannel = dwChannel;
m_fSignalLevel = 0;
m_bWaitCNR = TRUE;
}
case 0x01: // fall-through / チャンネルロックされてる
return TRUE;
default:
break;
}
err:
m_fSignalLevel = 0;
return FALSE;
}
const DWORD cProxyClient::GetCurSpace(void)
{
return m_dwSpace;
}
const DWORD cProxyClient::GetCurChannel(void)
{
return m_dwChannel;
}
const DWORD cProxyClient::GetTotalDeviceNum(void)
{
if (!m_bTuner)
return 0;
makePacket(eGetTotalDeviceNum);
if (m_dwResEvent[edwResGetTotalDeviceNum]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
return m_dwRes[edwResGetTotalDeviceNum];
}
return 0;
}
const DWORD cProxyClient::GetActiveDeviceNum(void)
{
if (!m_bTuner)
return 0;
makePacket(eGetActiveDeviceNum);
if (m_dwResEvent[edwResGetActiveDeviceNum]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
return m_dwRes[edwResGetActiveDeviceNum];
}
return 0;
}
const BOOL cProxyClient::SetLnbPower(const BOOL bEnable)
{
if (!m_bTuner)
return FALSE;
makePacket(eSetLnbPower, bEnable);
if (m_bResEvent[ebResSetLnbPower]->Wait(&m_Error) != WAIT_OBJECT_0)
{
LOCK(m_readLock);
return m_bRes[ebResSetLnbPower];
}
return FALSE;
}
static SOCKET Connect(char *host, char *port)
{
addrinfo hints, *results, *rp;
SOCKET sock;
int i, bf;
fd_set wd;
timeval tv;
::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
if (g_UseMagicPacket)
{
char sendbuf[128];
::memset(sendbuf, 0xff, 6);
for (i = 1; i <= 16; i++)
::memcpy(&sendbuf[i * 6], g_TargetMac, 6);
hints.ai_socktype = SOCK_DGRAM;
hints.ai_protocol = IPPROTO_UDP;
hints.ai_flags = AI_NUMERICHOST;
if (::getaddrinfo(g_TargetHost, g_TargetPort, &hints, &results) != 0)
{
hints.ai_flags = 0;
if (::getaddrinfo(g_TargetHost, g_TargetPort, &hints, &results) != 0)
return INVALID_SOCKET;
}
for (rp = results; rp != NULL; rp = rp->ai_next)
{
sock = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == INVALID_SOCKET)
continue;
BOOL opt = TRUE;
if (::setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (const char *)&opt, sizeof(opt)) != 0)
{
::close(sock);
continue;
}
int ret = ::sendto(sock, sendbuf, 102, 0, rp->ai_addr, (int)(rp->ai_addrlen));
::close(sock);
if (ret == 102)
break;
}
::freeaddrinfo(results);
if (rp == NULL)
return INVALID_SOCKET;
}
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_NUMERICHOST;
if (::getaddrinfo(host, port, &hints, &results) != 0)
{
hints.ai_flags = 0;
if (::getaddrinfo(host, port, &hints, &results) != 0)
return INVALID_SOCKET;
}
for (rp = results; rp != NULL; rp = rp->ai_next)
{
sock = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == INVALID_SOCKET)
continue;
bf = TRUE;
::ioctl(sock, FIONBIO, &bf);
tv.tv_sec = g_ConnectTimeOut;
tv.tv_usec = 0;
FD_ZERO(&wd);
FD_SET(sock, &wd);
::connect(sock, rp->ai_addr, (int)(rp->ai_addrlen));
if ((i = ::select((int)(sock + 1), 0, &wd, 0, &tv)) != SOCKET_ERROR)
{
// タイムアウト時間が"全体の"ではなく"個々のソケットの"になるけど、とりあえずこれで
if (i != 0)
{
bf = FALSE;
::ioctl(sock, FIONBIO, &bf);
break;
}
}
::close(sock);
}
::freeaddrinfo(results);
if (rp == NULL)
return INVALID_SOCKET;
return sock;
}
extern "C" IBonDriver *CreateBonDriver()
{
if (Init() != 0)
return NULL;
SOCKET s = Connect(g_Host, g_Port);
if (s == INVALID_SOCKET)
return NULL;
cProxyClient *pProxy = new cProxyClient();
pProxy->setSocket(s);
pthread_t ht;
if (::pthread_create(&ht, NULL, cProxyClient::ProcessEntry, pProxy))
goto err;
pProxy->setThreadHandle(ht);
if (pProxy->WaitSingleShot() == WAIT_OBJECT_0)
goto err;
if (!pProxy->SelectBonDriver())
goto err;
if (pProxy->CreateBonDriver())
{
LOCK(g_Lock);
g_InstanceList.push_back(pProxy);
return pProxy;
}
err:
delete pProxy;
return NULL;
}
extern "C" BOOL SetBonDriver(LPCSTR p)
{
LOCK(g_Lock);
if (::strlen(p) >= sizeof(g_BonDriver))
return FALSE;
::strcpy(g_BonDriver, p);
return TRUE;
}
}
| 20.742968
| 136
| 0.634901
|
epgdatacapbon
|
44c560a2a5700361e8de3ae5bb21827a9af88b54
| 999
|
cc
|
C++
|
tests/test0009.cc
|
michaeljclark/glyb
|
5b302ded6061eea2098bc8e963adb09e5f1dab4e
|
[
"MIT"
] | 7
|
2021-07-28T19:03:08.000Z
|
2022-02-02T23:17:11.000Z
|
tests/test0009.cc
|
michaeljclark/glyb
|
5b302ded6061eea2098bc8e963adb09e5f1dab4e
|
[
"MIT"
] | 2
|
2021-06-15T22:34:44.000Z
|
2021-11-10T04:27:21.000Z
|
tests/test0009.cc
|
michaeljclark/glyb
|
5b302ded6061eea2098bc8e963adb09e5f1dab4e
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#define FLOAT32 "%.9g"
struct atlas_ent
{
int bin_id, font_id, glyph;
short x, y, ox, oy, w, h;
};
int main(int argc, char **argv)
{
FILE *in = nullptr;
if (argc != 2) {
fprintf(stderr, "usage: %s <filename>\n", argv[0]);
exit(1);
}
if (!(in = fopen(argv[1], "r"))) {
fprintf(stderr, "error: fopen: %s, %s\n", argv[1], strerror(errno));
exit(1);
}
const int num_fields = 9;
int ret;
do {
atlas_ent ent;
ret = fscanf(in, "%d,%d,%d,%hd,%hd,%hd,%hd,%hd,%hd\n",
&ent.bin_id, &ent.font_id, &ent.glyph,
&ent.x, &ent.y, &ent.ox, &ent.oy, &ent.w, &ent.h);
if (ret == num_fields) {
printf("%d,%d,%d,%d,%d,%d,%d,%d,%d\n",
ent.bin_id, ent.font_id, ent.glyph,
ent.x, ent.y, ent.ox, ent.oy, ent.w, ent.h);
}
} while (ret == num_fields);
fclose(in);
}
| 22.704545
| 76
| 0.491491
|
michaeljclark
|
44c5c0645aeb629366c56177ce4382dd3b73e9f4
| 123
|
cpp
|
C++
|
Trixs/UIManager.cpp
|
RuurddeRonde/Trixs-raytracer
|
382d4e95a54274ef7fbc4f4fba7575fe6f286298
|
[
"MIT"
] | 2
|
2020-08-25T00:31:17.000Z
|
2021-12-11T22:14:02.000Z
|
Trixs/UIManager.cpp
|
RuurddeRonde/Trixs-raytracer
|
382d4e95a54274ef7fbc4f4fba7575fe6f286298
|
[
"MIT"
] | null | null | null |
Trixs/UIManager.cpp
|
RuurddeRonde/Trixs-raytracer
|
382d4e95a54274ef7fbc4f4fba7575fe6f286298
|
[
"MIT"
] | null | null | null |
#include "UIManager.h"
namespace Trixs
{
UIManager::UIManager(Window* window)
{
}
UIManager::~UIManager()
{
}
}
| 7.6875
| 37
| 0.642276
|
RuurddeRonde
|
44c6dedd44ad4509a3f5a9c13fc04d6f1ffbdc64
| 6,995
|
cc
|
C++
|
lite/kernels/arm/concat_compute_test.cc
|
xw-github/Paddle-Lite
|
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
|
[
"Apache-2.0"
] | null | null | null |
lite/kernels/arm/concat_compute_test.cc
|
xw-github/Paddle-Lite
|
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
|
[
"Apache-2.0"
] | null | null | null |
lite/kernels/arm/concat_compute_test.cc
|
xw-github/Paddle-Lite
|
3cbd1d375d89c4deb379d44cdbcdc32ee74634c5
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/kernels/arm/concat_compute.h"
#include <gtest/gtest.h>
#include <limits>
#include <string>
#include <vector>
#include "lite/backends/arm/math/funcs.h"
#include "lite/core/op_registry.h"
#include "lite/core/tensor.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace arm {
bool infer_shape(const operators::ConcatParam& param) {
std::vector<lite::DDim> input_dims;
for (auto p : param.x) {
input_dims.push_back(p->dims());
}
size_t axis = static_cast<size_t>(param.axis);
const size_t n = input_dims.size();
CHECK_GT_OR_FALSE(n, 0);
auto& out_dims = input_dims[0];
size_t in_zero_dims_size = out_dims.size();
for (size_t i = 1; i < n; i++) {
for (size_t j = 0; j < in_zero_dims_size; j++) {
if (j == axis) {
out_dims[axis] += input_dims[i][j];
} else {
CHECK_EQ_OR_FALSE(out_dims[j], input_dims[i][j]);
}
}
}
if (out_dims[axis] < 0) {
out_dims[axis] = -1;
}
// Set output dims
param.output->Resize(lite::DDim(out_dims));
return true;
}
void concat_compute_ref(const operators::ConcatParam& param) {
std::vector<lite::Tensor*> input = param.x;
int axis = param.axis;
infer_shape(param);
lite::Tensor* output = param.output;
int num = input.size();
int rows = 1;
auto dim_0 = input[0]->dims();
for (int i = 0; i < axis; ++i) {
rows *= dim_0[i];
}
int out_rows = rows, out_cols = 0;
std::vector<int> input_cols(input.size());
for (int i = 0; i < num; ++i) {
int input_i_numel = input[i]->dims().size() == 0 ? 0 : 1;
for (int didx = 0; didx < input[i]->dims().size(); ++didx) {
input_i_numel *= input[i]->dims()[didx];
}
int t_cols = input_i_numel / rows;
out_cols += t_cols;
input_cols[i] = t_cols;
}
// computation
auto output_data = output->mutable_data<float>();
int col_idx = 0;
for (int j = 0; j < num; ++j) {
int col_len = input_cols[j];
auto input_data = input[j]->data<float>();
for (int k = 0; k < out_rows; ++k) {
memcpy(output_data + k * out_cols + col_idx,
input_data + k * col_len,
sizeof(float) * col_len);
}
col_idx += col_len;
}
}
TEST(concat_arm, init) {
ConcatCompute concat;
ASSERT_EQ(concat.precision(), PRECISION(kAny));
ASSERT_EQ(concat.target(), TARGET(kARM));
}
TEST(concat_arm, compute_input_single) {
ConcatCompute concat;
operators::ConcatParam param;
LOG(INFO) << "test concat start";
lite::Tensor output;
lite::Tensor output_ref;
lite::Tensor tensorA;
DDimLite ddimA({10, 4, 3, 2});
tensorA.Resize(ddimA);
for (int i = 0; i < ddimA.data()[0] * ddimA.data()[1] * ddimA.data()[2] *
ddimA.data()[3];
i++) {
tensorA.mutable_data<float>()[i] = i;
}
param.x.push_back(&tensorA);
for (int cur_axis : {0, 1}) {
param.output = &output;
param.axis = cur_axis;
CHECK(infer_shape(param));
concat.SetParam(param);
LOG(INFO) << "test concat start cur_axis:" << cur_axis;
concat.Run();
LOG(INFO) << "concat.Run end";
param.output = &output_ref;
LOG(INFO) << "concat_compute_ref start";
concat_compute_ref(param);
LOG(INFO) << "concat_compute_ref end";
auto* output_data = output.data<float>();
auto* output_ref_data = output_ref.data<float>();
for (int i = 0; i < (ddimA.data()[0]) * ddimA.data()[1] * ddimA.data()[2] *
ddimA.data()[3];
i++) {
// LOG(INFO) << "output[" << i << "]:" << output_data[i] << "
// output_ref_data[" << i << "]:" << output_ref_data[i];
EXPECT_NEAR(output_data[i], output_ref_data[i], 1e-5);
}
}
}
TEST(concat_arm, compute_input_multi) {
ConcatCompute concat;
operators::ConcatParam param;
LOG(INFO) << "test concat start";
// init param
// x: tensorA, tensorB, tensorC, tensorD
// axis: 0
lite::Tensor output;
lite::Tensor output_ref;
lite::Tensor tensorA;
lite::Tensor tensorB;
lite::Tensor tensorC;
lite::Tensor tensorD;
DDimLite ddimA({10, 4, 3, 2});
DDimLite ddimB({20, 4, 3, 2});
DDimLite ddimC({30, 4, 3, 2});
DDimLite ddimD({40, 4, 3, 2});
tensorA.Resize(ddimA);
tensorB.Resize(ddimB);
tensorC.Resize(ddimC);
tensorD.Resize(ddimD);
for (int i = 0; i < ddimA.data()[0] * ddimA.data()[1] * ddimA.data()[2] *
ddimA.data()[3];
i++) {
tensorA.mutable_data<float>()[i] = i;
}
for (int i = 0; i < ddimB.data()[0] * ddimB.data()[1] * ddimB.data()[2] *
ddimB.data()[3];
i++) {
tensorB.mutable_data<float>()[i] = i + 1;
}
for (int i = 0; i < ddimC.data()[0] * ddimC.data()[1] * ddimC.data()[2] *
ddimC.data()[3];
i++) {
tensorC.mutable_data<float>()[i] = i + 2;
}
for (int i = 0; i < ddimD.data()[0] * ddimD.data()[1] * ddimD.data()[2] *
ddimD.data()[3];
i++) {
tensorD.mutable_data<float>()[i] = i + 3;
}
param.x.push_back(&tensorA);
param.x.push_back(&tensorB);
param.x.push_back(&tensorC);
param.x.push_back(&tensorD);
for (int cur_axis : {0}) {
param.output = &output;
param.axis = cur_axis;
CHECK(infer_shape(param));
concat.SetParam(param);
LOG(INFO) << "test concat start cur_axis:" << cur_axis;
concat.Run();
LOG(INFO) << "concat.Run end";
param.output = &output_ref;
LOG(INFO) << "concat_compute_ref start";
concat_compute_ref(param);
LOG(INFO) << "concat_compute_ref end";
auto* output_data = output.data<float>();
auto* output_ref_data = output_ref.data<float>();
int elem_num = (ddimA.data()[0] + ddimB.data()[0] + ddimC.data()[0] +
ddimD.data()[0]) *
ddimA.data()[1] * ddimA.data()[2] * ddimA.data()[3];
for (int i = 0; i < elem_num; i++) {
// LOG(INFO) << "output[" << i << "]:" << output_data[i] << "
// output_ref_data[" << i << "]:" << output_ref_data[i];
EXPECT_NEAR(output_data[i], output_ref_data[i], 1e-5);
}
}
}
TEST(concat, retrive_op) {
auto concat =
KernelRegistry::Global().Create<TARGET(kARM), PRECISION(kAny)>("concat");
ASSERT_FALSE(concat.empty());
ASSERT_TRUE(concat.front());
}
} // namespace arm
} // namespace kernels
} // namespace lite
} // namespace paddle
USE_LITE_KERNEL(concat, kARM, kAny, kNCHW, def);
| 29.639831
| 79
| 0.599714
|
xw-github
|
44c72f463289e7db5e76fe0aa208aa0af4889fea
| 799
|
cpp
|
C++
|
CCC/Stage1/08-Done/ccc08j3.cpp
|
zzh8829/CompetitiveProgramming
|
36f36b10269b4648ca8be0b08c2c49e96abede25
|
[
"MIT"
] | 1
|
2017-10-01T00:51:39.000Z
|
2017-10-01T00:51:39.000Z
|
CCC/Stage1/08-Done/ccc08j3.cpp
|
zzh8829/CompetitiveProgramming
|
36f36b10269b4648ca8be0b08c2c49e96abede25
|
[
"MIT"
] | null | null | null |
CCC/Stage1/08-Done/ccc08j3.cpp
|
zzh8829/CompetitiveProgramming
|
36f36b10269b4648ca8be0b08c2c49e96abede25
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <cctype>
#include <cmath>
using namespace std;
int x = 1,y=1;
int h[31]= {
1,1,1,1,1,1,
2,2,2,2,2,2,
3,3,3,3,3,3,
4,4,4,4,4,4,
5,5,5,5,5,5};
int v[31]= {
1,2,3,4,5,6,
1,2,3,4,5,6,
1,2,3,4,5,6,
1,2,3,4,5,6,
1,2,3,4,5,6};
int getPos(char c)
{
if(isalpha(c))
return c-'A';
if(c==' ')
return 26;
if(c=='-')
return 27;
if(c=='.')
return 28;
if(c=='#')
return 29;
}
int getNum(int n)
{
int t = 0;
t += abs(h[n] - x);
t += abs(v[n] - y);
x = h[n];
y = v[n];
return t;
}
int main()
{
string line;
getline(cin,line);
int sum = 0;
for(int i=0;i!=line.size();i++)
sum+=getNum(getPos(line[i]));
sum += getNum(getPos('#'));
cout << sum <<endl;
system("pause");
return 0;
}
| 14.527273
| 33
| 0.48811
|
zzh8829
|
44c7aaf19786548ecfced6f53e79a496434a9a8c
| 789
|
cpp
|
C++
|
945.minimum_increment_to_make_array_unique_by_sort.cpp
|
liangwt/leetcode
|
8f279343e975666a63ee531228c6836f20f199ca
|
[
"Apache-2.0"
] | 5
|
2019-09-12T05:23:44.000Z
|
2021-11-15T11:19:39.000Z
|
945.minimum_increment_to_make_array_unique_by_sort.cpp
|
liangwt/leetcode
|
8f279343e975666a63ee531228c6836f20f199ca
|
[
"Apache-2.0"
] | 18
|
2019-09-23T13:11:06.000Z
|
2019-11-09T11:20:17.000Z
|
945.minimum_increment_to_make_array_unique_by_sort.cpp
|
liangwt/leetcode
|
8f279343e975666a63ee531228c6836f20f199ca
|
[
"Apache-2.0"
] | null | null | null |
#include <assert.h>
#include <vector>
using namespace std;
class Solution
{
public:
// 先排序,再依次遍历数组元素,若当前元素小于等于它前一个元素,则将其变为前一个数+1。
int minIncrementForUnique(vector<int> &A)
{
int ans = 0;
int len = A.size();
sort(A.begin(), A.end());
for (int i = 1; i < len; ++i)
{
int r = A[i], l = A[i - 1];
if (r <= l)
{
ans += (l - r + 1);
A[i] = l + 1;
}
}
return ans;
}
};
int main()
{
Solution s;
vector<int> A1 = {1, 2, 2};
assert(s.minIncrementForUnique(A1) == 1);
vector<int> A2 = {3, 2, 1, 2, 1, 7};
assert(s.minIncrementForUnique(A2) == 6);
vector<int> A3 = {};
assert(s.minIncrementForUnique(A3) == 0);
}
| 18.348837
| 49
| 0.460076
|
liangwt
|
44c93b13d5c73e5cfdb0d23e0856f038232d5924
| 3,292
|
hpp
|
C++
|
ql/termstructures/volatility/swaption/swaptionvolcube2.hpp
|
haozhangphd/QuantLib-noBoost
|
ddded069868161099843c04840454f00816113ad
|
[
"BSD-3-Clause"
] | 76
|
2017-06-28T21:24:38.000Z
|
2021-12-19T18:07:37.000Z
|
ql/termstructures/volatility/swaption/swaptionvolcube2.hpp
|
haozhangphd/QuantLib-noBoost
|
ddded069868161099843c04840454f00816113ad
|
[
"BSD-3-Clause"
] | 2
|
2017-07-05T09:20:13.000Z
|
2019-10-31T12:06:51.000Z
|
ql/termstructures/volatility/swaption/swaptionvolcube2.hpp
|
haozhangphd/QuantLib-noBoost
|
ddded069868161099843c04840454f00816113ad
|
[
"BSD-3-Clause"
] | 34
|
2017-07-02T14:49:21.000Z
|
2021-11-26T15:32:04.000Z
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 Ferdinando Ametrano
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file swaptionvolcube2.hpp
\brief Swaption volatility cube, fit-later-interpolate-early approach
*/
#ifndef quantlib_swaption_volcube_fit_later_interpolate_early_h
#define quantlib_swaption_volcube_fit_later_interpolate_early_h
#include <ql/termstructures/volatility/swaption/swaptionvolcube.hpp>
#include <ql/math/interpolations/interpolation2d.hpp>
namespace QuantLib {
class SwaptionVolCube2 : public SwaptionVolatilityCube{
public:
/*! The swaption vol cube is made up of ordered swaption vol surface
layers, each layer referring to a swap index of a given length
(in years), all indexes belonging to the same family. In order
to identify the family (and its market conventions) an index of
whatever length from that family must be passed in as
swapIndexBase.
Often for short swap length the swap index family is different,
e.g. the EUR case: swap vs 6M Euribor is used for length>1Y,
while swap vs 3M Euribor is used for the 1Y length. The
shortSwapIndexBase is used to identify this second family.
*/
SwaptionVolCube2(
const Handle<SwaptionVolatilityStructure>& atmVolStructure,
const std::vector<Period>& optionTenors,
const std::vector<Period>& swapTenors,
const std::vector<Spread>& strikeSpreads,
const std::vector<std::vector<Handle<Quote> > >& volSpreads,
const std::shared_ptr<SwapIndex>& swapIndexBase,
const std::shared_ptr<SwapIndex>& shortSwapIndexBase,
bool vegaWeightedSmileFit);
//! \name LazyObject interface
//@{
void performCalculations() const;
//@}
//! \name SwaptionVolatilityCube inspectors
//@{
const Matrix& volSpreads(Size i) const { return volSpreadsMatrix_[i]; }
std::shared_ptr<SmileSection> smileSectionImpl(
const Date& optionDate,
const Period& swapTenor) const;
std::shared_ptr<SmileSection> smileSectionImpl(
Time optionTime,
Time swapLength) const;
//@}
private:
mutable std::vector<Interpolation2D> volSpreadsInterpolator_;
mutable std::vector<Matrix> volSpreadsMatrix_;
};
}
#endif
| 42.753247
| 79
| 0.655832
|
haozhangphd
|
44c9bc060a5ca54beee9f52f28b243a07395959e
| 183,030
|
hpp
|
C++
|
lib/bill/bill/sat/solver/ghack.hpp
|
osamamowafy/mockturtle
|
840ff314e9f5301686790a517c383240f1403588
|
[
"MIT"
] | 98
|
2018-06-15T09:28:11.000Z
|
2022-03-31T15:42:48.000Z
|
lib/bill/bill/sat/solver/ghack.hpp
|
osamamowafy/mockturtle
|
840ff314e9f5301686790a517c383240f1403588
|
[
"MIT"
] | 257
|
2018-05-09T12:14:28.000Z
|
2022-03-30T16:12:14.000Z
|
lib/bill/bill/sat/solver/ghack.hpp
|
osamamowafy/mockturtle
|
840ff314e9f5301686790a517c383240f1403588
|
[
"MIT"
] | 75
|
2020-11-26T13:05:15.000Z
|
2021-12-24T00:28:18.000Z
|
/**************************************************************************************[IntTypes.h]
Copyright (c) 2009-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#pragma once
#ifndef Ghack_IntTypes_h
#define Ghack_IntTypes_h
#ifdef __sun
// Not sure if there are newer versions that support C99 headers. The
// needed features are implemented in the headers below though:
# include <sys/int_types.h>
# include <sys/int_fmtio.h>
# include <sys/int_limits.h>
#else
# include <stdint.h>
# include <inttypes.h>
#endif
#include <limits.h>
#ifndef PRIu64
#define PRIu64 "lu"
#define PRIi64 "ld"
#endif
//=================================================================================================
#endif
/****************************************************************************************[XAlloc.h]
Copyright (c) 2009-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_XAlloc_h
#define Ghack_XAlloc_h
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
namespace GHack {
//=================================================================================================
// Simple layer on top of malloc/realloc to catch out-of-memory situtaions and provide some typing:
class OutOfMemoryException{};
static inline void* xrealloc(void *ptr, size_t size)
{
void* mem = realloc(ptr, size);
if (mem == NULL && errno == ENOMEM){
throw OutOfMemoryException();
}else {
return mem;
}
}
//=================================================================================================
}
#endif
/*******************************************************************************************[Vec.h]
Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Vec_h
#define Ghack_Vec_h
#include <assert.h>
#include <new>
namespace GHack {
//=================================================================================================
// Automatically resizable arrays
//
// NOTE! Don't use this vector on datatypes that cannot be re-located in memory (with realloc)
template<class T>
class vec {
T* data;
int sz;
int cap;
// Don't allow copying (error prone):
vec<T>& operator = (vec<T>& other) { assert(0); return *this; }
vec (vec<T>& other) { assert(0); }
// Helpers for calculating next capacity:
static inline int imax (int x, int y) { int mask = (y-x) >> (sizeof(int)*8-1); return (x&mask) + (y&(~mask)); }
//static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; }
static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; }
public:
// Constructors:
vec() : data(NULL) , sz(0) , cap(0) { }
explicit vec(int size) : data(NULL) , sz(0) , cap(0) { growTo(size); }
vec(int size, const T& pad) : data(NULL) , sz(0) , cap(0) { growTo(size, pad); }
~vec() { clear(true); }
// Pointer to first element:
operator T* (void) { return data; }
// Size operations:
int size (void) const { return sz; }
void shrink (int nelems) { assert(nelems <= sz); for (int i = 0; i < nelems; i++) sz--, data[sz].~T(); }
void shrink_ (int nelems) { assert(nelems <= sz); sz -= nelems; }
int capacity (void) const { return cap; }
void capacity (int min_cap);
void growTo (int size);
void growTo (int size, const T& pad);
void clear (bool dealloc = false);
// Stack interface:
void push (void) { if (sz == cap) capacity(sz+1); new (&data[sz]) T(); sz++; }
void push (const T& elem) { if (sz == cap) capacity(sz+1); data[sz++] = elem; }
void push_ (const T& elem) { assert(sz < cap); data[sz++] = elem; }
void pop (void) { assert(sz > 0); sz--, data[sz].~T(); }
// NOTE: it seems possible that overflow can happen in the 'sz+1' expression of 'push()', but
// in fact it can not since it requires that 'cap' is equal to INT_MAX. This in turn can not
// happen given the way capacities are calculated (below). Essentially, all capacities are
// even, but INT_MAX is odd.
const T& last (void) const { return data[sz-1]; }
T& last (void) { return data[sz-1]; }
// Vector interface:
const T& operator [] (int index) const { return data[index]; }
T& operator [] (int index) { return data[index]; }
// Duplicatation (preferred instead):
void copyTo(vec<T>& copy) const { copy.clear(); copy.growTo(sz); for (int i = 0; i < sz; i++) copy[i] = data[i]; }
void moveTo(vec<T>& dest) { dest.clear(true); dest.data = data; dest.sz = sz; dest.cap = cap; data = NULL; sz = 0; cap = 0; }
};
template<class T>
void vec<T>::capacity(int min_cap) {
if (cap >= min_cap) return;
int add = imax((min_cap - cap + 1) & ~1, ((cap >> 1) + 2) & ~1); // NOTE: grow by approximately 3/2
if (add > INT_MAX - cap || (((data = (T*)::realloc(data, (cap += add) * sizeof(T))) == NULL) && errno == ENOMEM))
throw OutOfMemoryException();
}
template<class T>
void vec<T>::growTo(int size, const T& pad) {
if (sz >= size) return;
capacity(size);
for (int i = sz; i < size; i++) data[i] = pad;
sz = size; }
template<class T>
void vec<T>::growTo(int size) {
if (sz >= size) return;
capacity(size);
for (int i = sz; i < size; i++) new (&data[i]) T();
sz = size; }
template<class T>
void vec<T>::clear(bool dealloc) {
if (data != NULL){
for (int i = 0; i < sz; i++) data[i].~T();
sz = 0;
if (dealloc) free(data), data = NULL, cap = 0; } }
//=================================================================================================
}
#endif
/*******************************************************************************************[Alg.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Alg_h
#define Ghack_Alg_h
namespace GHack {
//=================================================================================================
// Useful functions on vector-like types:
//=================================================================================================
// Removing and searching for elements:
//
template<class V, class T>
static inline void remove(V& ts, const T& t)
{
int j = 0;
for (; j < ts.size() && ts[j] != t; j++);
assert(j < ts.size());
for (; j < ts.size()-1; j++) ts[j] = ts[j+1];
ts.pop();
}
template<class V, class T>
static inline bool find(V& ts, const T& t)
{
int j = 0;
for (; j < ts.size() && ts[j] != t; j++);
return j < ts.size();
}
//=================================================================================================
// Copying vectors with support for nested vector types:
//
// Base case:
template<class T>
static inline void copy(const T& from, T& to)
{
to = from;
}
// Recursive case:
template<class T>
static inline void copy(const vec<T>& from, vec<T>& to, bool append = false)
{
if (!append)
to.clear();
for (int i = 0; i < from.size(); i++){
to.push();
copy(from[i], to.last());
}
}
template<class T>
static inline void append(const vec<T>& from, vec<T>& to){ copy(from, to, true); }
//=================================================================================================
}
#endif
/*****************************************************************************************[Alloc.h]
Copyright (c) 2008-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Alloc_h
#define Ghack_Alloc_h
namespace GHack {
//=================================================================================================
// Simple Region-based memory allocator:
template<class T>
class RegionAllocator
{
T* memory;
uint32_t sz;
uint32_t cap;
uint32_t wasted_;
void capacity(uint32_t min_cap);
public:
// TODO: make this a class for better type-checking?
typedef uint32_t Ref;
enum { Ref_Undef = UINT32_MAX };
enum { Unit_Size = sizeof(uint32_t) };
explicit RegionAllocator(uint32_t start_cap = 1024*1024) : memory(NULL), sz(0), cap(0), wasted_(0){ capacity(start_cap); }
~RegionAllocator()
{
if (memory != NULL)
::free(memory);
}
uint32_t size () const { return sz; }
uint32_t wasted () const { return wasted_; }
Ref alloc (int size);
void free (int size) { wasted_ += size; }
// Deref, Load Effective Address (LEA), Inverse of LEA (AEL):
T& operator[](Ref r) { assert(r >= 0 && r < sz); return memory[r]; }
const T& operator[](Ref r) const { assert(r >= 0 && r < sz); return memory[r]; }
T* lea (Ref r) { assert(r >= 0 && r < sz); return &memory[r]; }
const T* lea (Ref r) const { assert(r >= 0 && r < sz); return &memory[r]; }
Ref ael (const T* t) { assert((void*)t >= (void*)&memory[0] && (void*)t < (void*)&memory[sz-1]);
return (Ref)(t - &memory[0]); }
void moveTo(RegionAllocator& to) {
if (to.memory != NULL) ::free(to.memory);
to.memory = memory;
to.sz = sz;
to.cap = cap;
to.wasted_ = wasted_;
memory = NULL;
sz = cap = wasted_ = 0;
}
};
template<class T>
void RegionAllocator<T>::capacity(uint32_t min_cap)
{
if (cap >= min_cap) return;
uint32_t prev_cap = cap;
while (cap < min_cap){
// NOTE: Multiply by a factor (13/8) without causing overflow, then add 2 and make the
// result even by clearing the least significant bit. The resulting sequence of capacities
// is carefully chosen to hit a maximum capacity that is close to the '2^32-1' limit when
// using 'uint32_t' as indices so that as much as possible of this space can be used.
uint32_t delta = ((cap >> 1) + (cap >> 3) + 2) & ~1;
cap += delta;
if (cap <= prev_cap)
throw OutOfMemoryException();
}
//printf(" .. (%p) cap = %u\n", this, cap);
assert(cap > 0);
memory = (T*)xrealloc(memory, sizeof(T)*cap);
}
template<class T>
typename RegionAllocator<T>::Ref
RegionAllocator<T>::alloc(int size)
{
//printf("ALLOC called (this = %p, size = %d)\n", this, size); fflush(stdout);
assert(size > 0);
capacity(sz + size);
uint32_t prev_sz = sz;
sz += size;
// Handle overflow:
if (sz < prev_sz)
throw OutOfMemoryException();
return prev_sz;
}
//=================================================================================================
}
#endif
/******************************************************************************************[Heap.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Heap_h
#define Ghack_Heap_h
namespace GHack {
//=================================================================================================
// A heap implementation with support for decrease/increase key.
template<class Comp>
class Heap {
Comp lt; // The heap is a minimum-heap with respect to this comparator
vec<int> heap; // Heap of integers
vec<int> indices; // Each integers position (index) in the Heap
// Index "traversal" functions
static inline int left (int i) { return i*2+1; }
static inline int right (int i) { return (i+1)*2; }
static inline int parent(int i) { return (i-1) >> 1; }
void percolateUp(int i)
{
int x = heap[i];
int p = parent(i);
while (i != 0 && lt(x, heap[p])){
heap[i] = heap[p];
indices[heap[p]] = i;
i = p;
p = parent(p);
}
heap [i] = x;
indices[x] = i;
}
void percolateDown(int i)
{
int x = heap[i];
while (left(i) < heap.size()){
int child = right(i) < heap.size() && lt(heap[right(i)], heap[left(i)]) ? right(i) : left(i);
if (!lt(heap[child], x)) break;
heap[i] = heap[child];
indices[heap[i]] = i;
i = child;
}
heap [i] = x;
indices[x] = i;
}
public:
Heap(const Comp& c) : lt(c) { }
int size () const { return heap.size(); }
bool empty () const { return heap.size() == 0; }
bool inHeap (int n) const { return n < indices.size() && indices[n] >= 0; }
int operator[](int index) const { assert(index < heap.size()); return heap[index]; }
void decrease (int n) { assert(inHeap(n)); percolateUp (indices[n]); }
void increase (int n) { assert(inHeap(n)); percolateDown(indices[n]); }
// Safe variant of insert/decrease/increase:
void update(int n)
{
if (!inHeap(n))
insert(n);
else {
percolateUp(indices[n]);
percolateDown(indices[n]); }
}
void insert(int n)
{
indices.growTo(n+1, -1);
assert(!inHeap(n));
indices[n] = heap.size();
heap.push(n);
percolateUp(indices[n]);
}
int removeMin()
{
int x = heap[0];
heap[0] = heap.last();
indices[heap[0]] = 0;
indices[x] = -1;
heap.pop();
if (heap.size() > 1) percolateDown(0);
return x;
}
// Rebuild the heap from scratch, using the elements in 'ns':
void build(vec<int>& ns) {
for (int i = 0; i < heap.size(); i++)
indices[heap[i]] = -1;
heap.clear();
for (int i = 0; i < ns.size(); i++){
indices[ns[i]] = i;
heap.push(ns[i]); }
for (int i = heap.size() / 2 - 1; i >= 0; i--)
percolateDown(i);
}
void clear(bool dealloc = false)
{
for (int i = 0; i < heap.size(); i++)
indices[heap[i]] = -1;
heap.clear(dealloc);
}
};
//=================================================================================================
}
#endif
/*******************************************************************************************[Map.h]
Copyright (c) 2006-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Map_h
#define Ghack_Map_h
namespace GHack {
//=================================================================================================
// Default hash/equals functions
//
template<class K> struct Hash { uint32_t operator()(const K& k) const { return hash(k); } };
template<class K> struct Equal { bool operator()(const K& k1, const K& k2) const { return k1 == k2; } };
template<class K> struct DeepHash { uint32_t operator()(const K* k) const { return hash(*k); } };
template<class K> struct DeepEqual { bool operator()(const K* k1, const K* k2) const { return *k1 == *k2; } };
static inline uint32_t hash(uint32_t x){ return x; }
static inline uint32_t hash(uint64_t x){ return (uint32_t)x; }
static inline uint32_t hash(int32_t x) { return (uint32_t)x; }
static inline uint32_t hash(int64_t x) { return (uint32_t)x; }
//=================================================================================================
// Some primes
//
static const int nprimes = 25;
static const int primes [nprimes] = { 31, 73, 151, 313, 643, 1291, 2593, 5233, 10501, 21013, 42073, 84181, 168451, 337219, 674701, 1349473, 2699299, 5398891, 10798093, 21596719, 43193641, 86387383, 172775299, 345550609, 691101253 };
//=================================================================================================
// Hash table implementation of Maps
//
template<class K, class D, class H = Hash<K>, class E = Equal<K> >
class Map {
public:
struct Pair { K key; D data; };
private:
H hash;
E equals;
vec<Pair>* table;
int cap;
int size;
// Don't allow copying (error prone):
Map<K,D,H,E>& operator = (Map<K,D,H,E>& other) { assert(0); }
Map (Map<K,D,H,E>& other) { assert(0); }
bool checkCap(int new_size) const { return new_size > cap; }
int32_t index (const K& k) const { return hash(k) % cap; }
void _insert (const K& k, const D& d) {
vec<Pair>& ps = table[index(k)];
ps.push(); ps.last().key = k; ps.last().data = d; }
void rehash () {
const vec<Pair>* old = table;
int old_cap = cap;
int newsize = primes[0];
for (int i = 1; newsize <= cap && i < nprimes; i++)
newsize = primes[i];
table = new vec<Pair>[newsize];
cap = newsize;
for (int i = 0; i < old_cap; i++){
for (int j = 0; j < old[i].size(); j++){
_insert(old[i][j].key, old[i][j].data); }}
delete [] old;
// printf(" --- rehashing, old-cap=%d, new-cap=%d\n", cap, newsize);
}
public:
Map () : table(NULL), cap(0), size(0) {}
Map (const H& h, const E& e) : hash(h), equals(e), table(NULL), cap(0), size(0){}
~Map () { delete [] table; }
// PRECONDITION: the key must already exist in the map.
const D& operator [] (const K& k) const
{
assert(size != 0);
const D* res = NULL;
const vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k))
res = &ps[i].data;
assert(res != NULL);
return *res;
}
// PRECONDITION: the key must already exist in the map.
D& operator [] (const K& k)
{
assert(size != 0);
D* res = NULL;
vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k))
res = &ps[i].data;
assert(res != NULL);
return *res;
}
// PRECONDITION: the key must *NOT* exist in the map.
void insert (const K& k, const D& d) { if (checkCap(size+1)) rehash(); _insert(k, d); size++; }
bool peek (const K& k, D& d) const {
if (size == 0) return false;
const vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k)){
d = ps[i].data;
return true; }
return false;
}
bool has (const K& k) const {
if (size == 0) return false;
const vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k))
return true;
return false;
}
// PRECONDITION: the key must exist in the map.
void remove(const K& k) {
assert(table != NULL);
vec<Pair>& ps = table[index(k)];
int j = 0;
for (; j < ps.size() && !equals(ps[j].key, k); j++);
assert(j < ps.size());
ps[j] = ps.last();
ps.pop();
size--;
}
void clear () {
cap = size = 0;
delete [] table;
table = NULL;
}
int elems() const { return size; }
int bucket_count() const { return cap; }
// NOTE: the hash and equality objects are not moved by this method:
void moveTo(Map& other){
delete [] other.table;
other.table = table;
other.cap = cap;
other.size = size;
table = NULL;
size = cap = 0;
}
// NOTE: given a bit more time, I could make a more C++-style iterator out of this:
const vec<Pair>& bucket(int i) const { return table[i]; }
};
//=================================================================================================
}
#endif
/*****************************************************************************************[Queue.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Queue_h
#define Ghack_Queue_h
namespace GHack {
//=================================================================================================
template<class T>
class Queue {
vec<T> buf;
int first;
int end;
public:
typedef T Key;
Queue() : buf(1), first(0), end(0) {}
void clear (bool dealloc = false) { buf.clear(dealloc); buf.growTo(1); first = end = 0; }
int size () const { return (end >= first) ? end - first : end - first + buf.size(); }
const T& operator [] (int index) const { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; }
T& operator [] (int index) { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; }
T peek () const { assert(first != end); return buf[first]; }
void pop () { assert(first != end); first++; if (first == buf.size()) first = 0; }
void insert(T elem) { // INVARIANT: buf[end] is always unused
buf[end++] = elem;
if (end == buf.size()) end = 0;
if (first == end){ // Resize:
vec<T> tmp((buf.size()*3 + 1) >> 1);
//**/printf("queue alloc: %d elems (%.1f MB)\n", tmp.size(), tmp.size() * sizeof(T) / 1000000.0);
int i = 0;
for (int j = first; j < buf.size(); j++) tmp[i++] = buf[j];
for (int j = 0 ; j < end ; j++) tmp[i++] = buf[j];
first = 0;
end = buf.size();
tmp.moveTo(buf);
}
}
};
//=================================================================================================
}
#endif
/******************************************************************************************[Sort.h]
Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Sort_h
#define Ghack_Sort_h
//=================================================================================================
// Some sorting algorithms for vec's
namespace GHack {
template<class T>
struct LessThan_default {
bool operator () (T x, T y) { return x < y; }
};
template <class T, class LessThan>
void selectionSort(T* array, int size, LessThan lt)
{
int i, j, best_i;
T tmp;
for (i = 0; i < size-1; i++){
best_i = i;
for (j = i+1; j < size; j++){
if (lt(array[j], array[best_i]))
best_i = j;
}
tmp = array[i]; array[i] = array[best_i]; array[best_i] = tmp;
}
}
template <class T> static inline void selectionSort(T* array, int size) {
selectionSort(array, size, LessThan_default<T>()); }
template <class T, class LessThan>
void sort(T* array, int size, LessThan lt)
{
if (size <= 15)
selectionSort(array, size, lt);
else{
T pivot = array[size / 2];
T tmp;
int i = -1;
int j = size;
for(;;){
do i++; while(lt(array[i], pivot));
do j--; while(lt(pivot, array[j]));
if (i >= j) break;
tmp = array[i]; array[i] = array[j]; array[j] = tmp;
}
sort(array , i , lt);
sort(&array[i], size-i, lt);
}
}
template <class T> static inline void sort(T* array, int size) {
sort(array, size, LessThan_default<T>()); }
//=================================================================================================
// For 'vec's:
template <class T, class LessThan> void sort(vec<T>& v, LessThan lt) {
sort((T*)v, v.size(), lt); }
template <class T> void sort(vec<T>& v) {
sort(v, LessThan_default<T>()); }
//=================================================================================================
}
#endif
/************************************************************************************[ParseUtils.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_ParseUtils_h
#define Ghack_ParseUtils_h
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
namespace GHack {
//-------------------------------------------------------------------------------------------------
// End-of-file detection functions for StreamBuffer and char*:
static inline bool isEof(const char* in) { return *in == '\0'; }
//-------------------------------------------------------------------------------------------------
// Generic parse functions parametrized over the input-stream type.
template<class B>
static void skipWhitespace(B& in) {
while ((*in >= 9 && *in <= 13) || *in == 32)
++in; }
template<class B>
static void skipLine(B& in) {
for (;;){
if (isEof(in)) return;
if (*in == '\n') { ++in; return; }
++in; } }
template<class B>
static double parseDouble(B& in) { // only in the form X.XXXXXe-XX
bool neg= false;
double accu = 0.0;
double currentExponent = 1;
int exponent;
skipWhitespace(in);
if(*in == EOF) return 0;
if (*in == '-') neg = true, ++in;
else if (*in == '+') ++in;
if (*in < '1' || *in > '9') printf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
accu = (double)(*in - '0');
++in;
if (*in != '.') printf("PARSE ERROR! Unexpected char: %c\n", *in),exit(3);
++in; // skip dot
currentExponent = 0.1;
while (*in >= '0' && *in <= '9')
accu = accu + currentExponent * ((double)(*in - '0')),
currentExponent /= 10,
++in;
if (*in != 'e') printf("PARSE ERROR! Unexpected char: %c\n", *in),exit(3);
++in; // skip dot
exponent = parseInt(in); // read exponent
accu *= pow(10,exponent);
return neg ? -accu:accu;
}
template<class B>
static int parseInt(B& in) {
int val = 0;
bool neg = false;
skipWhitespace(in);
if (*in == '-') neg = true, ++in;
else if (*in == '+') ++in;
if (*in < '0' || *in > '9') fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
while (*in >= '0' && *in <= '9')
val = val*10 + (*in - '0'),
++in;
return neg ? -val : val; }
// String matching: in case of a match the input iterator will be advanced the corresponding
// number of characters.
template<class B>
static bool match(B& in, const char* str) {
int i;
for (i = 0; str[i] != '\0'; i++)
if (in[i] != str[i])
return false;
in += i;
return true;
}
// String matching: consumes characters eagerly, but does not require random access iterator.
template<class B>
static bool eagerMatch(B& in, const char* str) {
for (; *str != '\0'; ++str, ++in)
if (*str != *in)
return false;
return true; }
//=================================================================================================
}
#endif
/***************************************************************************************[Options.h]
Copyright (c) 2008-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Options_h
#define Ghack_Options_h
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
namespace GHack {
//==================================================================================================
// Top-level option parse/help functions:
extern void parseOptions (int& argc, char** argv, bool strict = false);
extern void printUsageAndExit(int argc, char** argv, bool verbose = false);
extern void setUsageHelp (const char* str);
extern void setHelpPrefixStr (const char* str);
//==================================================================================================
// Options is an abstract class that gives the interface for all types options:
class Option
{
protected:
const char* name;
const char* description;
const char* category;
const char* type_name;
static vec<Option*>& getOptionList () { static vec<Option*> options; return options; }
static const char*& getUsageString() { static const char* usage_str; return usage_str; }
static const char*& getHelpPrefixString() { static const char* help_prefix_str = ""; return help_prefix_str; }
struct OptionLt {
bool operator()(const Option* x, const Option* y) {
int test1 = strcmp(x->category, y->category);
return test1 < 0 || (test1 == 0 && strcmp(x->type_name, y->type_name) < 0);
}
};
Option(const char* name_,
const char* desc_,
const char* cate_,
const char* type_) :
name (name_)
, description(desc_)
, category (cate_)
, type_name (type_)
{
getOptionList().push(this);
}
public:
virtual ~Option() {}
virtual bool parse (const char* str) = 0;
virtual void help (bool verbose = false) = 0;
friend void parseOptions (int& argc, char** argv, bool strict);
friend void printUsageAndExit (int argc, char** argv, bool verbose);
friend void setUsageHelp (const char* str);
friend void setHelpPrefixStr (const char* str);
};
//==================================================================================================
// Range classes with specialization for floating types:
struct IntRange {
int begin;
int end;
IntRange(int b, int e) : begin(b), end(e) {}
};
struct Int64Range {
int64_t begin;
int64_t end;
Int64Range(int64_t b, int64_t e) : begin(b), end(e) {}
};
struct DoubleRange {
double begin;
double end;
bool begin_inclusive;
bool end_inclusive;
DoubleRange(double b, bool binc, double e, bool einc) : begin(b), end(e), begin_inclusive(binc), end_inclusive(einc) {}
};
//==================================================================================================
// Double options:
class DoubleOption : public Option
{
protected:
DoubleRange range;
double value;
public:
DoubleOption(const char* c, const char* n, const char* d, double def = double(), DoubleRange r = DoubleRange(-HUGE_VAL, false, HUGE_VAL, false))
: Option(n, d, c, "<double>"), range(r), value(def) {
// FIXME: set LC_NUMERIC to "C" to make sure that strtof/strtod parses decimal point correctly.
}
operator double (void) const { return value; }
operator double& (void) { return value; }
DoubleOption& operator=(double x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
char* end;
double tmp = strtod(span, &end);
if (end == NULL)
return false;
else if (tmp >= range.end && (!range.end_inclusive || tmp != range.end)){
fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
exit(1);
}else if (tmp <= range.begin && (!range.begin_inclusive || tmp != range.begin)){
fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
exit(1); }
value = tmp;
// fprintf(stderr, "READ VALUE: %g\n", value);
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-12s = %-8s %c%4.2g .. %4.2g%c (default: %g)\n",
name, type_name,
range.begin_inclusive ? '[' : '(',
range.begin,
range.end,
range.end_inclusive ? ']' : ')',
value);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
//==================================================================================================
// Int options:
class IntOption : public Option
{
protected:
IntRange range;
int32_t value;
public:
IntOption(const char* c, const char* n, const char* d, int32_t def = int32_t(), IntRange r = IntRange(INT32_MIN, INT32_MAX))
: Option(n, d, c, "<int32>"), range(r), value(def) {}
operator int32_t (void) const { return value; }
operator int32_t& (void) { return value; }
IntOption& operator= (int32_t x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
char* end;
int32_t tmp = strtol(span, &end, 10);
if (end == NULL)
return false;
else if (tmp > range.end){
fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
exit(1);
}else if (tmp < range.begin){
fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
exit(1); }
value = tmp;
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-12s = %-8s [", name, type_name);
if (range.begin == INT32_MIN)
fprintf(stderr, "imin");
else
fprintf(stderr, "%4d", range.begin);
fprintf(stderr, " .. ");
if (range.end == INT32_MAX)
fprintf(stderr, "imax");
else
fprintf(stderr, "%4d", range.end);
fprintf(stderr, "] (default: %d)\n", value);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
// Leave this out for visual C++ until Microsoft implements C99 and gets support for strtoll.
#ifndef _MSC_VER
class Int64Option : public Option
{
protected:
Int64Range range;
int64_t value;
public:
Int64Option(const char* c, const char* n, const char* d, int64_t def = int64_t(), Int64Range r = Int64Range(INT64_MIN, INT64_MAX))
: Option(n, d, c, "<int64>"), range(r), value(def) {}
operator int64_t (void) const { return value; }
operator int64_t& (void) { return value; }
Int64Option& operator= (int64_t x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
char* end;
int64_t tmp = strtoll(span, &end, 10);
if (end == NULL)
return false;
else if (tmp > range.end){
fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
exit(1);
}else if (tmp < range.begin){
fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
exit(1); }
value = tmp;
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-12s = %-8s [", name, type_name);
if (range.begin == INT64_MIN)
fprintf(stderr, "imin");
else
fprintf(stderr, "%4" PRIi64, range.begin);
fprintf(stderr, " .. ");
if (range.end == INT64_MAX)
fprintf(stderr, "imax");
else
fprintf(stderr, "%4" PRIi64, range.end);
fprintf(stderr, "] (default: %" PRIi64")\n", value);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
#endif
//==================================================================================================
// String option:
class StringOption : public Option
{
const char* value;
public:
StringOption(const char* c, const char* n, const char* d, const char* def = NULL)
: Option(n, d, c, "<string>"), value(def) {}
operator const char* (void) const { return value; }
operator const char*& (void) { return value; }
StringOption& operator= (const char* x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
value = span;
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-10s = %8s\n", name, type_name);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
//==================================================================================================
// Bool option:
class BoolOption : public Option
{
bool value;
public:
BoolOption(const char* c, const char* n, const char* d, bool v)
: Option(n, d, c, "<bool>"), value(v) {}
operator bool (void) const { return value; }
operator bool& (void) { return value; }
BoolOption& operator=(bool b) { value = b; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (match(span, "-")){
bool b = !match(span, "no-");
if (strcmp(span, name) == 0){
value = b;
return true; }
}
return false;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%s, -no-%s", name, name);
for (uint32_t i = 0; i < 32 - strlen(name)*2; i++)
fprintf(stderr, " ");
fprintf(stderr, " ");
fprintf(stderr, "(default: %s)\n", value ? "on" : "off");
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
//=================================================================================================
}
#endif
/****************************************************************************************[System.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_System_h
#define Ghack_System_h
//-------------------------------------------------------------------------------------------------
namespace GHack {
static inline double cpuTime(void); // CPU-time in seconds.
extern double memUsed(); // Memory in mega bytes (returns 0 for unsupported architectures).
extern double memUsedPeak(); // Peak-memory in mega bytes (returns 0 for unsupported architectures).
}
//-------------------------------------------------------------------------------------------------
// Implementation of inline functions:
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <time.h>
static inline double GHack::cpuTime(void) { return (double)clock() / CLOCKS_PER_SEC; }
#else
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
static inline double GHack::cpuTime(void) {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; }
#endif
#endif
/***********************************************************************************[SolverTypes.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of
Glucose are exactly the same as Minisat on which it is based on. (see below).
---------------
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_SolverTypes_h
#define Ghack_SolverTypes_h
#include <assert.h>
namespace GHack {
//=================================================================================================
// Variables, literals, lifted booleans, clauses:
// NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N,
// so that they can be used as array indices.
typedef int Var;
#define var_Undef (-1)
struct Lit {
int x;
// Use this as a constructor:
friend Lit mkLit(Var var, bool sign);
bool operator == (Lit p) const { return x == p.x; }
bool operator != (Lit p) const { return x != p.x; }
bool operator < (Lit p) const { return x < p.x; } // '<' makes p, ~p adjacent in the ordering.
};
inline Lit mkLit (Var var, bool sign = false) { Lit p; p.x = var + var + (int)sign; return p; }
inline Lit operator ~(Lit p) { Lit q; q.x = p.x ^ 1; return q; }
inline Lit operator ^(Lit p, bool b) { Lit q; q.x = p.x ^ (unsigned int)b; return q; }
inline bool sign (Lit p) { return p.x & 1; }
inline int var (Lit p) { return p.x >> 1; }
// Mapping Literals to and from compact integers suitable for array indexing:
inline int toInt (Var v) { return v; }
inline int toInt (Lit p) { return p.x; }
inline Lit toLit (int i) { Lit p; p.x = i; return p; }
//const Lit lit_Undef = mkLit(var_Undef, false); // }- Useful special constants.
//const Lit lit_Error = mkLit(var_Undef, true ); // }
const Lit lit_Undef = { -2 }; // }- Useful special constants.
const Lit lit_Error = { -1 }; // }
//=================================================================================================
// Lifted booleans:
//
// NOTE: this implementation is optimized for the case when comparisons between values are mostly
// between one variable and one constant. Some care had to be taken to make sure that gcc
// does enough constant propagation to produce sensible code, and this appears to be somewhat
// fragile unfortunately.
class lbool {
uint8_t value;
public:
constexpr explicit lbool(uint8_t v) : value(v) { }
lbool() : value(0) { }
explicit lbool(bool x) : value(!x) { }
bool operator == (lbool b) const { return ((b.value&2) & (value&2)) | (!(b.value&2)&(value == b.value)); }
bool operator != (lbool b) const { return !(*this == b); }
lbool operator ^ (bool b) const { return lbool((uint8_t)(value^(uint8_t)b)); }
lbool operator && (lbool b) const {
uint8_t sel = (this->value << 1) | (b.value << 3);
uint8_t v = (0xF7F755F4 >> sel) & 3;
return lbool(v); }
lbool operator || (lbool b) const {
uint8_t sel = (this->value << 1) | (b.value << 3);
uint8_t v = (0xFCFCF400 >> sel) & 3;
return lbool(v); }
friend int toInt (lbool l);
friend lbool toLbool(int v);
};
inline int toInt (lbool l) { return l.value; }
inline lbool toLbool(int v) { return lbool((uint8_t)v); }
constexpr auto l_True = GHack::lbool((uint8_t)0);
constexpr auto l_False = GHack::lbool((uint8_t)1);
constexpr auto l_Undef = GHack::lbool((uint8_t)2);
//=================================================================================================
// Clause -- a simple class for representing a clause:
struct Clause;
typedef RegionAllocator<uint32_t>::Ref CRef;
struct Clause {
int t;
struct {
unsigned mark : 2;
unsigned learnt : 1;
unsigned has_extra : 1;
unsigned reloced : 1;
unsigned lbd : 26;
unsigned canbedel : 1;
unsigned size : 32;
unsigned szWithoutSelectors : 32;
} header;
union { Lit lit; float act; uint32_t abs; CRef rel; } data[0];
friend class ClauseAllocator;
// NOTE: This constructor cannot be used directly (doesn't allocate enough memory).
template<class V>
Clause(const V& ps, bool use_extra, bool learnt) {
header.mark = t = 0;
header.learnt = learnt;
header.has_extra = use_extra;
header.reloced = 0;
header.size = ps.size();
header.lbd = 0;
header.canbedel = 1;
for (int i = 0; i < ps.size(); i++)
data[i].lit = ps[i];
if (header.has_extra){
if (header.learnt)
data[header.size].act = 0;
else
calcAbstraction(); }
}
public:
void calcAbstraction() {
assert(header.has_extra);
uint32_t abstraction = 0;
for (int i = 0; i < size(); i++)
abstraction |= 1 << (var(data[i].lit) & 31);
data[header.size].abs = abstraction; }
int size () const { return header.size; }
void shrink (int i) { assert(i <= size()); if (header.has_extra) data[header.size-i] = data[header.size]; header.size -= i; }
void pop () { shrink(1); }
bool learnt () const { return header.learnt; }
bool has_extra () const { return header.has_extra; }
uint32_t mark () const { return header.mark; }
void mark (uint32_t m) { header.mark = m; }
const Lit& last () const { return data[header.size-1].lit; }
bool reloced () const { return header.reloced; }
CRef relocation () const { return data[0].rel; }
void relocate (CRef c) { header.reloced = 1; data[0].rel = c; }
// NOTE: somewhat unsafe to change the clause in-place! Must manually call 'calcAbstraction' afterwards for
// subsumption operations to behave correctly.
Lit& operator [] (int i) { return data[i].lit; }
Lit operator [] (int i) const { return data[i].lit; }
operator const Lit* (void) const { return (Lit*)data; }
float& activity () { assert(header.has_extra); return data[header.size].act; }
uint32_t abstraction () const { assert(header.has_extra); return data[header.size].abs; }
Lit subsumes (const Clause& other) const;
void strengthen (Lit p);
void setLBD(int i) {header.lbd = i;}
// unsigned int& lbd () { return header.lbd; }
unsigned int lbd () const { return header.lbd; }
void setCanBeDel(bool b) {header.canbedel = b;}
bool canBeDel() {return header.canbedel;}
void setSizeWithoutSelectors (unsigned int n) {header.szWithoutSelectors = n; }
unsigned int sizeWithoutSelectors () const { return header.szWithoutSelectors; }
};
//=================================================================================================
// ClauseAllocator -- a simple class for allocating memory for clauses:
const CRef CRef_Undef = RegionAllocator<uint32_t>::Ref_Undef;
class ClauseAllocator : public RegionAllocator<uint32_t>
{
static int clauseWord32Size(int size, bool has_extra){
return (sizeof(Clause) + (sizeof(Lit) * (size + (int)has_extra))) / sizeof(uint32_t); }
public:
bool extra_clause_field;
ClauseAllocator(uint32_t start_cap) : RegionAllocator<uint32_t>(start_cap), extra_clause_field(false){}
ClauseAllocator() : extra_clause_field(false){}
void moveTo(ClauseAllocator& to){
to.extra_clause_field = extra_clause_field;
RegionAllocator<uint32_t>::moveTo(to); }
template<class Lits>
CRef alloc(const Lits& ps, bool learnt = false)
{
assert(sizeof(Lit) == sizeof(uint32_t));
assert(sizeof(float) == sizeof(uint32_t));
bool use_extra = learnt | extra_clause_field;
CRef cid = RegionAllocator<uint32_t>::alloc(clauseWord32Size(ps.size(), use_extra));
new (lea(cid)) Clause(ps, use_extra, learnt);
return cid;
}
// Deref, Load Effective Address (LEA), Inverse of LEA (AEL):
Clause& operator[](Ref r) { return (Clause&)RegionAllocator<uint32_t>::operator[](r); }
const Clause& operator[](Ref r) const { return (Clause&)RegionAllocator<uint32_t>::operator[](r); }
Clause* lea (Ref r) { return (Clause*)RegionAllocator<uint32_t>::lea(r); }
const Clause* lea (Ref r) const { return (Clause*)RegionAllocator<uint32_t>::lea(r); }
Ref ael (const Clause* t){ return RegionAllocator<uint32_t>::ael((uint32_t*)t); }
void free(CRef cid)
{
Clause& c = operator[](cid);
RegionAllocator<uint32_t>::free(clauseWord32Size(c.size(), c.has_extra()));
}
void reloc(CRef& cr, ClauseAllocator& to)
{
Clause& c = operator[](cr);
if (c.reloced()) { cr = c.relocation(); return; }
cr = to.alloc(c, c.learnt());
c.relocate(cr);
// Copy extra data-fields:
// (This could be cleaned-up. Generalize Clause-constructor to be applicable here instead?)
to[cr].mark(c.mark());
if (to[cr].learnt()) {
to[cr].t = c.t;
to[cr].activity() = c.activity();
to[cr].setLBD(c.lbd());
to[cr].setSizeWithoutSelectors(c.sizeWithoutSelectors());
to[cr].setCanBeDel(c.canBeDel());
}
else if (to[cr].has_extra()) to[cr].calcAbstraction();
}
};
//=================================================================================================
// OccLists -- a class for maintaining occurence lists with lazy deletion:
template<class Idx, class Vec, class Deleted>
class OccLists
{
vec<Vec> occs;
vec<char> dirty;
vec<Idx> dirties;
Deleted deleted;
public:
OccLists(const Deleted& d) : deleted(d) {}
void init (const Idx& idx){ occs.growTo(toInt(idx)+1); dirty.growTo(toInt(idx)+1, 0); }
// Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; }
Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; }
Vec& lookup (const Idx& idx){ if (dirty[toInt(idx)]) clean(idx); return occs[toInt(idx)]; }
void cleanAll ();
void clean (const Idx& idx);
void smudge (const Idx& idx){
if (dirty[toInt(idx)] == 0){
dirty[toInt(idx)] = 1;
dirties.push(idx);
}
}
void clear(bool free = true){
occs .clear(free);
dirty .clear(free);
dirties.clear(free);
}
};
template<class Idx, class Vec, class Deleted>
void OccLists<Idx,Vec,Deleted>::cleanAll()
{
for (int i = 0; i < dirties.size(); i++)
// Dirties may contain duplicates so check here if a variable is already cleaned:
if (dirty[toInt(dirties[i])])
clean(dirties[i]);
dirties.clear();
}
template<class Idx, class Vec, class Deleted>
void OccLists<Idx,Vec,Deleted>::clean(const Idx& idx)
{
Vec& vec = occs[toInt(idx)];
int i, j;
for (i = j = 0; i < vec.size(); i++)
if (!deleted(vec[i]))
vec[j++] = vec[i];
vec.shrink(i - j);
dirty[toInt(idx)] = 0;
}
//=================================================================================================
// CMap -- a class for mapping clauses to values:
template<class T>
class CMap
{
struct CRefHash {
uint32_t operator()(CRef cr) const { return (uint32_t)cr; } };
typedef Map<CRef, T, CRefHash> HashTable;
HashTable map;
public:
// Size-operations:
void clear () { map.clear(); }
int size () const { return map.elems(); }
// Insert/Remove/Test mapping:
void insert (CRef cr, const T& t){ map.insert(cr, t); }
void growTo (CRef cr, const T& t){ map.insert(cr, t); } // NOTE: for compatibility
void remove (CRef cr) { map.remove(cr); }
bool has (CRef cr, T& t) { return map.peek(cr, t); }
// Vector interface (the clause 'c' must already exist):
const T& operator [] (CRef cr) const { return map[cr]; }
T& operator [] (CRef cr) { return map[cr]; }
// Iteration (not transparent at all at the moment):
int bucket_count() const { return map.bucket_count(); }
const vec<typename HashTable::Pair>& bucket(int i) const { return map.bucket(i); }
// Move contents to other map:
void moveTo(CMap& other){ map.moveTo(other.map); }
// TMP debug:
void debug(){
printf(" --- size = %d, bucket_count = %d\n", size(), map.bucket_count()); }
};
/*_________________________________________________________________________________________________
|
| subsumes : (other : const Clause&) -> Lit
|
| Description:
| Checks if clause subsumes 'other', and at the same time, if it can be used to simplify 'other'
| by subsumption resolution.
|
| Result:
| lit_Error - No subsumption or simplification
| lit_Undef - Clause subsumes 'other'
| p - The literal p can be deleted from 'other'
|________________________________________________________________________________________________@*/
inline Lit Clause::subsumes(const Clause& other) const
{
//if (other.size() < size() || (extra.abst & ~other.extra.abst) != 0)
//if (other.size() < size() || (!learnt() && !other.learnt() && (extra.abst & ~other.extra.abst) != 0))
assert(!header.learnt); assert(!other.header.learnt);
assert(header.has_extra); assert(other.header.has_extra);
if (other.header.size < header.size || (data[header.size].abs & ~other.data[other.header.size].abs) != 0)
return lit_Error;
Lit ret = lit_Undef;
const Lit* c = (const Lit*)(*this);
const Lit* d = (const Lit*)other;
for (unsigned i = 0; i < header.size; i++) {
// search for c[i] or ~c[i]
for (unsigned j = 0; j < other.header.size; j++)
if (c[i] == d[j])
goto ok;
else if (ret == lit_Undef && c[i] == ~d[j]){
ret = c[i];
goto ok;
}
// did not find it
return lit_Error;
ok:;
}
return ret;
}
inline void Clause::strengthen(Lit p)
{
remove(*this, p);
calcAbstraction();
}
//=================================================================================================
}
#endif
/***********************************************************************************[BoundedQueue.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef BoundedQueue_h
#define BoundedQueue_h
//=================================================================================================
namespace GHack {
template <class T>
class bqueue {
vec<T> elems;
int first;
int last;
unsigned long long sumofqueue;
int maxsize;
int queuesize; // Number of current elements (must be < maxsize !)
bool expComputed;
double exp,value;
public:
bqueue(void) : first(0), last(0), sumofqueue(0), maxsize(0), queuesize(0),expComputed(false) { }
void initSize(int size) {growTo(size);exp = 2.0/(size+1);} // Init size of bounded size queue
void push(T x) {
expComputed = false;
if (queuesize==maxsize) {
assert(last==first); // The queue is full, next value to enter will replace oldest one
sumofqueue -= elems[last];
if ((++last) == maxsize) last = 0;
} else
queuesize++;
sumofqueue += x;
elems[first] = x;
if ((++first) == maxsize) {first = 0;last = 0;}
}
T peek() { assert(queuesize>0); return elems[last]; }
void pop() {sumofqueue-=elems[last]; queuesize--; if ((++last) == maxsize) last = 0;}
unsigned long long getsum() const {return sumofqueue;}
unsigned int getavg() const {return (unsigned int)(sumofqueue/((unsigned long long)queuesize));}
int maxSize() const {return maxsize;}
double getavgDouble() const {
double tmp = 0;
for(int i=0;i<elems.size();i++) {
tmp+=elems[i];
}
return tmp/elems.size();
}
int isvalid() const {return (queuesize==maxsize);}
void growTo(int size) {
elems.growTo(size);
first=0; maxsize=size; queuesize = 0;last = 0;
for(int i=0;i<size;i++) elems[i]=0;
}
double getAvgExp() {
if(expComputed) return value;
double a=exp;
value = elems[first];
for(int i = first;i<maxsize;i++) {
value+=a*((double)elems[i]);
a=a*exp;
}
for(int i = 0;i<last;i++) {
value+=a*((double)elems[i]);
a=a*exp;
}
value = value*(1-exp)/(1-a);
expComputed = true;
return value;
}
void fastclear() {first = 0; last = 0; queuesize=0; sumofqueue=0;} // to be called after restarts... Discard the queue
int size(void) { return queuesize; }
void clear(bool dealloc = false) { elems.clear(dealloc); first = 0; maxsize=0; queuesize=0;sumofqueue=0;}
};
}
//=================================================================================================
#endif
/************************************************************************************[Constants.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#define DYNAMICNBLEVEL
#define CONSTANTREMOVECLAUSE
#define UPDATEVARACTIVITY
// Constants for clauses reductions
#define RATIOREMOVECLAUSES 2
// Constants for restarts
#define LOWER_BOUND_FOR_BLOCKING_RESTART 10000
/****************************************************************************************[Solver.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of
Glucose are exactly the same as Minisat on which it is based on. (see below).
---------------
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_Solver_h
#define Ghack_Solver_h
namespace GHack {
//=================================================================================================
// Solver -- the main class:
class Solver {
public:
// Constructor/Destructor:
//
Solver();
virtual ~Solver();
// Problem specification:
//
Var newVar (bool polarity = true, bool dvar = true); // Add a new variable with parameters specifying variable mode.
bool addClause (const vec<Lit>& ps); // Add a clause to the solver.
bool addEmptyClause(); // Add the empty clause, making the solver contradictory.
bool addClause (Lit p); // Add a unit clause to the solver.
bool addClause (Lit p, Lit q); // Add a binary clause to the solver.
bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
bool addClause_( vec<Lit>& ps); // Add a clause to the solver without making superflous internal copy. Will
// change the passed vector 'ps'.
// Solving:
//
bool simplify (); // Removes already satisfied clauses.
bool solve (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions.
lbool solveLimited (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions (With resource constraints).
bool solve (); // Search without assumptions.
bool solve (Lit p); // Search for a model that respects a single assumption.
bool solve (Lit p, Lit q); // Search for a model that respects two assumptions.
bool solve (Lit p, Lit q, Lit r); // Search for a model that respects three assumptions.
bool okay () const; // FALSE means solver is in a conflicting state
void toDimacs (FILE* f, const vec<Lit>& assumps); // Write CNF to file in DIMACS-format.
void toDimacs (const char *file, const vec<Lit>& assumps);
void toDimacs (FILE* f, Clause& c, vec<Var>& map, Var& max);
void printLit(Lit l);
void printClause(CRef c);
void printInitialClause(CRef c);
// Convenience versions of 'toDimacs()':
void toDimacs (const char* file);
void toDimacs (const char* file, Lit p);
void toDimacs (const char* file, Lit p, Lit q);
void toDimacs (const char* file, Lit p, Lit q, Lit r);
// Variable mode:
//
void setPolarity (Var v, bool b); // Declare which polarity the decision heuristic should use for a variable. Requires mode 'polarity_user'.
void setDecisionVar (Var v, bool b); // Declare if a variable should be eligible for selection in the decision heuristic.
// Read state:
//
lbool value (Var x) const; // The current value of a variable.
lbool value (Lit p) const; // The current value of a literal.
lbool modelValue (Var x) const; // The value of a variable in the last model. The last call to solve must have been satisfiable.
lbool modelValue (Lit p) const; // The value of a literal in the last model. The last call to solve must have been satisfiable.
int nAssigns () const; // The current number of assigned literals.
int nClauses () const; // The current number of original clauses.
int nLearnts () const; // The current number of learnt clauses.
int nVars () const; // The current number of variables.
int nFreeVars () const;
// Incremental mode
void setIncrementalMode();
void initNbInitialVars(int nb);
void printIncrementalStats();
// Resource contraints:
//
void setConfBudget(int64_t x);
void setPropBudget(int64_t x);
void budgetOff();
void interrupt(); // Trigger a (potentially asynchronous) interruption of the solver.
void clearInterrupt(); // Clear interrupt indicator flag.
// Memory managment:
//
virtual void garbageCollect();
void checkGarbage(double gf);
void checkGarbage();
// Extra results: (read-only member variable)
//
vec<lbool> model; // If problem is satisfiable, this vector contains the model (if any).
vec<Lit> conflict; // If problem is unsatisfiable (possibly under assumptions),
// this vector represent the final conflict clause expressed in the assumptions.
// Mode of operation:
//
int verbosity;
int verbEveryConflicts;
int showModel;
// Constants For restarts
double K;
double R;
double sizeLBDQueue;
double sizeTrailQueue;
// Constants for reduce DB
int firstReduceDB;
int incReduceDB;
int specialIncReduceDB,I,O,G,H,Y,Z,A,e;
unsigned int lbLBDFrozenClause;
// Constant for reducing clause
int lbSizeMinimizingClause;
unsigned int lbLBDMinimizingClause;
double var_decay;
double clause_decay;
double random_var_freq;
double random_seed;
int ccmin_mode; // Controls conflict clause minimization (0=none, 1=basic, 2=deep).
int phase_saving; // Controls the level of phase saving (0=none, 1=limited, 2=full).
bool rnd_pol; // Use random polarities for branching heuristics.
bool rnd_init_act; // Initialize variable activities with a small random value.
double garbage_frac; // The fraction of wasted memory allowed before a garbage collection is triggered.
// Certified UNSAT ( Thanks to Marijn Heule)
FILE* certifiedOutput;
bool certifiedUNSAT;
bool vbyte;
void write_char (unsigned char c);
void write_lit (int n);
// Statistics: (read-only member variable)
//
uint64_t nbRemovedClauses,nbReducedClauses,nbDL2,nbBin,nbUn,nbReduceDB,solves, starts, decisions, rnd_decisions, propagations, conflicts,conflictsRestarts,nbstopsrestarts,nbstopsrestartssame,lastblockatrestart;
uint64_t dec_vars, clauses_literals, learnts_literals, max_literals, tot_literals;
protected:
long curRestart;
// Helper structures:
//
struct VarData { CRef reason; int level; };
static inline VarData mkVarData(CRef cr, int l){ VarData d = {cr, l}; return d; }
struct Watcher {
CRef cref;
Lit blocker;
Watcher(CRef cr, Lit p) : cref(cr), blocker(p) {}
bool operator==(const Watcher& w) const { return cref == w.cref; }
bool operator!=(const Watcher& w) const { return cref != w.cref; }
};
struct WatcherDeleted
{
const ClauseAllocator& ca;
WatcherDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
bool operator()(const Watcher& w) const { return ca[w.cref].mark() == 1; }
};
struct VarOrderLt {
const vec<double>& activity;
bool operator () (Var x, Var y) const { return activity[x] > activity[y]; }
VarOrderLt(const vec<double>& act) : activity(act) { }
};
// Solver state:
//
int lastIndexRed;
bool ok; // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used!
double cla_inc; // Amount to bump next clause with.
vec<double> activity; // A heuristic measurement of the activity of a variable.
double var_inc; // Amount to bump next variable with.
OccLists<Lit, vec<Watcher>, WatcherDeleted>
watches; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
OccLists<Lit, vec<Watcher>, WatcherDeleted>
watchesBin; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
vec<CRef> clauses; // List of problem clauses.
vec<CRef> learnts,C,T; // List of learnt clauses.
vec<lbool> assigns; // The current assignments.
vec<char> polarity; // The preferred polarity of each variable.
vec<char> decision; // Declares if a variable is eligible for selection in the decision heuristic.
vec<Lit> trail; // Assignment stack; stores all assigments made in the order they were made.
vec<int> nbpos;
vec<int> trail_lim; // Separator indices for different decision levels in 'trail'.
vec<VarData> vardata; // Stores reason and level for each variable.
int qhead; // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat).
int simpDB_assigns; // Number of top-level assignments since last execution of 'simplify()'.
int64_t simpDB_props; // Remaining number of propagations that must be made before next execution of 'simplify()'.
vec<Lit> assumptions; // Current set of assumptions provided to solve by the user.
Heap<VarOrderLt> order_heap; // A priority queue of variables ordered with respect to the variable activity.
double progress_estimate;// Set by 'search()'.
bool remove_satisfied; // Indicates whether possibly inefficient linear scan for satisfied clauses should be performed in 'simplify'.
vec<unsigned int> permDiff; // permDiff[var] contains the current conflict number... Used to count the number of LBD
#ifdef UPDATEVARACTIVITY
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
vec<Lit> lastDecisionLevel;
#endif
ClauseAllocator ca;
int nbclausesbeforereduce; // To know when it is time to reduce clause database
bqueue<unsigned int> trailQueue,lbdQueue; // Bounded queues for restarts.
float sumLBD; // used to compute the global average of LBD. Restarts...
int sumAssumptions;
// Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which it is
// used, exept 'seen' wich is used in several places.
//
vec<char> seen;
vec<Lit> analyze_stack;
vec<Lit> analyze_toclear;
vec<Lit> add_tmp;
unsigned int MYFLAG;
double max_learnts;
double learntsize_adjust_confl;
int learntsize_adjust_cnt;
// Resource contraints:
//
int64_t conflict_budget; // -1 means no budget.
int64_t propagation_budget; // -1 means no budget.
bool asynch_interrupt;
// Variables added for incremental mode
int incremental; // Use incremental SAT Solver
int nbVarsInitialFormula; // nb VAR in formula without assumptions (incremental SAT)
double totalTime4Sat,totalTime4Unsat;
int nbSatCalls,nbUnsatCalls;
vec<int> assumptionPositions,initialPositions;
// Main internal methods:
//
void insertVarOrder (Var x); // Insert a variable in the decision order priority queue.
Lit pickBranchLit (); // Return the next decision variable.
void newDecisionLevel (); // Begins a new decision level.
void uncheckedEnqueue (Lit p, CRef from = CRef_Undef); // Enqueue a literal. Assumes value of literal is undefined.
bool enqueue (Lit p, CRef from = CRef_Undef); // Test if fact 'p' contradicts current state, enqueue otherwise.
CRef propagate (); // Perform unit propagation. Returns possibly conflicting clause.
void cancelUntil (int level); // Backtrack until a certain level.
void analyze (CRef confl, vec<Lit>& out_learnt, vec<Lit> & selectors, int& out_btlevel,unsigned int &nblevels,unsigned int &szWithoutSelectors); // (bt = backtrack)
void analyzeFinal (Lit p, vec<Lit>& out_conflict); // COULD THIS BE IMPLEMENTED BY THE ORDINARIY "analyze" BY SOME REASONABLE GENERALIZATION?
bool litRedundant (Lit p, uint32_t abstract_levels); // (helper method for 'analyze()')
lbool search (int& nof_conflicts); // Search for a given number of conflicts.
lbool solve_ (); // Main solve method (assumptions given in 'assumptions').
void reduceDB (); // Reduce the set of learnt clauses.
void removeSatisfied (vec<CRef>& cs); // Shrink 'cs' to contain only non-satisfied clauses.
void rebuildOrderHeap ();
// Maintaining Variable/Clause activity:
//
void varDecayActivity (); // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead.
void varBumpActivity (Var v, double inc); // Increase a variable with the current 'bump' value.
void varBumpActivity (Var v); // Increase a variable with the current 'bump' value.
void claDecayActivity (); // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead.
void claBumpActivity (Clause& c); // Increase a clause with the current 'bump' value.
// Operations on clauses:
//
void attachClause (CRef cr); // Attach a clause to watcher lists.
void detachClause (CRef cr, bool strict = false); // Detach a clause to watcher lists.
void removeClause (CRef cr); // Detach and free a clause.
bool locked (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state.
bool satisfied (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state.
unsigned int computeLBD(const vec<Lit> & lits,int end=-1);
unsigned int computeLBD(const Clause &c);
void minimisationWithBinaryResolution(vec<Lit> &out_learnt);
void relocAll (ClauseAllocator& to);
// Misc:
//
int decisionLevel () const; // Gives the current decisionlevel.
uint32_t abstractLevel (Var x) const; // Used to represent an abstraction of sets of decision levels.
CRef reason (Var x) const;
int level (Var x) const;
double progressEstimate () const; // DELETE THIS ?? IT'S NOT VERY USEFUL ...
bool withinBudget () const;
inline bool isSelector(Var v) {return (incremental && v>nbVarsInitialFormula);}
// Static helpers:
//
// Returns a random float 0 <= x < 1. Seed must never be 0.
static inline double drand(double& seed) {
seed *= 1389796;
int q = (int)(seed / 2147483647);
seed -= (double)q * 2147483647;
return seed / 2147483647; }
// Returns a random integer 0 <= x < size. Seed must never be 0.
static inline int irand(double& seed, int size) {
return (int)(drand(seed) * size); }
};
//=================================================================================================
// Implementation of inline methods:
inline CRef Solver::reason(Var x) const { return vardata[x].reason; }
inline int Solver::level (Var x) const { return vardata[x].level; }
inline void Solver::insertVarOrder(Var x) {
if (!order_heap.inHeap(x) && decision[x]) order_heap.insert(x); }
inline void Solver::varDecayActivity() { var_inc *= (1 / var_decay); }
inline void Solver::varBumpActivity(Var v) { varBumpActivity(v, var_inc); }
inline void Solver::varBumpActivity(Var v, double inc) {
if ( (activity[v] += inc) > 1e100 ) {
// Rescale:
for (int i = 0; i < nVars(); i++)
activity[i] *= 1e-100;
var_inc *= 1e-100; }
// Update order_heap with respect to new activity:
if (order_heap.inHeap(v))
order_heap.decrease(v); }
inline void Solver::claDecayActivity() { cla_inc *= (1 / clause_decay); }
inline void Solver::claBumpActivity (Clause& c) {
if ( (c.activity() += cla_inc) > 1e20 ) {
// Rescale:
for (int i = 0; i < learnts.size(); i++)
ca[learnts[i]].activity() *= 1e-20;
cla_inc *= 1e-20; } }
inline void Solver::checkGarbage(void){ return checkGarbage(garbage_frac); }
inline void Solver::checkGarbage(double gf){
if (ca.wasted() > ca.size() * gf)
garbageCollect(); }
// NOTE: enqueue does not set the ok flag! (only public methods do)
inline bool Solver::enqueue (Lit p, CRef from) { return value(p) != l_Undef ? value(p) != l_False : (uncheckedEnqueue(p, from), true); }
inline bool Solver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); }
inline bool Solver::addEmptyClause () { add_tmp.clear(); return addClause_(add_tmp); }
inline bool Solver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
inline bool Solver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
inline bool Solver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
inline bool Solver::locked (const Clause& c) const {
if(c.size()>2)
return value(c[0]) == l_True && reason(var(c[0])) != CRef_Undef && ca.lea(reason(var(c[0]))) == &c;
return
(value(c[0]) == l_True && reason(var(c[0])) != CRef_Undef && ca.lea(reason(var(c[0]))) == &c)
||
(value(c[1]) == l_True && reason(var(c[1])) != CRef_Undef && ca.lea(reason(var(c[1]))) == &c);
}
inline void Solver::newDecisionLevel() { trail_lim.push(trail.size()); }
inline int Solver::decisionLevel () const { return trail_lim.size(); }
inline uint32_t Solver::abstractLevel (Var x) const { return 1 << (level(x) & 31); }
inline lbool Solver::value (Var x) const { return assigns[x]; }
inline lbool Solver::value (Lit p) const { return assigns[var(p)] ^ sign(p); }
inline lbool Solver::modelValue (Var x) const { return model[x]; }
inline lbool Solver::modelValue (Lit p) const { return model[var(p)] ^ sign(p); }
inline int Solver::nAssigns () const { return trail.size(); }
inline int Solver::nClauses () const { return clauses.size(); }
inline int Solver::nLearnts () const { return learnts.size(); }
inline int Solver::nVars () const { return vardata.size(); }
inline int Solver::nFreeVars () const { return (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]); }
inline void Solver::setPolarity (Var v, bool b) { polarity[v] = b; }
inline void Solver::setDecisionVar(Var v, bool b)
{
if ( b && !decision[v]) dec_vars++;
else if (!b && decision[v]) dec_vars--;
decision[v] = b;
insertVarOrder(v);
}
inline void Solver::setConfBudget(int64_t x){ conflict_budget = conflicts + x; }
inline void Solver::setPropBudget(int64_t x){ propagation_budget = propagations + x; }
inline void Solver::interrupt(){ asynch_interrupt = true; }
inline void Solver::clearInterrupt(){ asynch_interrupt = false; }
inline void Solver::budgetOff(){ conflict_budget = propagation_budget = -1; }
inline bool Solver::withinBudget() const {
return !asynch_interrupt &&
(conflict_budget < 0 || conflicts < (uint64_t)conflict_budget) &&
(propagation_budget < 0 || propagations < (uint64_t)propagation_budget); }
// FIXME: after the introduction of asynchronous interrruptions the solve-versions that return a
// pure bool do not give a safe interface. Either interrupts must be possible to turn off here, or
// all calls to solve must return an 'lbool'. I'm not yet sure which I prefer.
inline bool Solver::solve () { budgetOff(); assumptions.clear(); return solve_() == l_True; }
inline bool Solver::solve (Lit p) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_() == l_True; }
inline bool Solver::solve (Lit p, Lit q) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_() == l_True; }
inline bool Solver::solve (Lit p, Lit q, Lit r) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_() == l_True; }
inline bool Solver::solve (const vec<Lit>& assumps){ budgetOff(); assumps.copyTo(assumptions); return solve_() == l_True; }
inline lbool Solver::solveLimited (const vec<Lit>& assumps){ assumps.copyTo(assumptions); return solve_(); }
inline bool Solver::okay () const { return ok; }
inline void Solver::toDimacs (const char* file){ vec<Lit> as; toDimacs(file, as); }
inline void Solver::toDimacs (const char* file, Lit p){ vec<Lit> as; as.push(p); toDimacs(file, as); }
inline void Solver::toDimacs (const char* file, Lit p, Lit q){ vec<Lit> as; as.push(p); as.push(q); toDimacs(file, as); }
inline void Solver::toDimacs (const char* file, Lit p, Lit q, Lit r){ vec<Lit> as; as.push(p); as.push(q); as.push(r); toDimacs(file, as); }
//=================================================================================================
// Debug etc:
inline void Solver::printLit(Lit l)
{
printf("%s%d:%c", sign(l) ? "-" : "", var(l)+1, value(l) == l_True ? '1' : (value(l) == l_False ? '0' : 'X'));
}
inline void Solver::printClause(CRef cr)
{
Clause &c = ca[cr];
for (int i = 0; i < c.size(); i++){
printLit(c[i]);
printf(" ");
}
}
inline void Solver::printInitialClause(CRef cr)
{
Clause &c = ca[cr];
for (int i = 0; i < c.size(); i++){
if(!isSelector(var(c[i]))) {
printLit(c[i]);
printf(" ");
}
}
}
//=================================================================================================
}
#endif
/***************************************************************************************[Solver.cc]
Glucose -- Copyright (c) 2013, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of
Glucose are exactly the same as Minisat on which it is based on. (see below).
---------------
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#include <math.h>
#define M mark
#define Q conflicts
#define P push
#define B claBumpActivity
namespace GHack {
//=================================================================================================
// Options:
static const char* _cat = "CORE";
static const char* _cr = "CORE -- RESTART";
static const char* _cred = "CORE -- REDUCE";
static const char* _cm = "CORE -- MINIMIZE";
static const char* _certified = "CORE -- CERTIFIED UNSAT";
static BoolOption opt_incremental (_cat,"incremental", "Use incremental SAT solving",false);
static DoubleOption opt_K (_cr, "K", "The constant used to force restart", 0.8, DoubleRange(0, false, 1, false));
static DoubleOption opt_R (_cr, "R", "The constant used to block restart", 1.4, DoubleRange(1, false, 5, false));
static IntOption opt_size_lbd_queue (_cr, "szLBDQueue", "The size of moving average for LBD (restarts)", 50, IntRange(10, INT32_MAX));
static IntOption opt_size_trail_queue (_cr, "szTrailQueue", "The size of moving average for trail (block restarts)", 5000, IntRange(10, INT32_MAX));
static IntOption opt_first_reduce_db (_cred, "firstReduceDB", "The number of conflicts before the first reduce DB", 2000, IntRange(0, INT32_MAX));
static IntOption opt_inc_reduce_db (_cred, "incReduceDB", "Increment for reduce DB", 300, IntRange(0, INT32_MAX));
static IntOption opt_spec_inc_reduce_db (_cred, "specialIncReduceDB", "Special increment for reduce DB", 1000, IntRange(0, INT32_MAX));
static IntOption opt_lb_lbd_frozen_clause (_cred, "minLBDFrozenClause", "Protect clauses if their LBD decrease and is lower than (for one turn)", 30, IntRange(0, INT32_MAX));
static IntOption opt_lb_size_minimzing_clause (_cm, "minSizeMinimizingClause", "The min size required to minimize clause", 30, IntRange(3, INT32_MAX));
static IntOption opt_lb_lbd_minimzing_clause (_cm, "minLBDMinimizingClause", "The min LBD required to minimize clause", 6, IntRange(3, INT32_MAX));
static DoubleOption opt_var_decay (_cat, "var-decay", "The variable activity decay factor", 0.8, DoubleRange(0, false, 1, false));
static DoubleOption opt_clause_decay (_cat, "cla-decay", "The clause activity decay factor", 0.999, DoubleRange(0, false, 1, false));
static DoubleOption opt_random_var_freq (_cat, "rnd-freq", "The frequency with which the decision heuristic tries to choose a random variable", 0, DoubleRange(0, true, 1, true));
static DoubleOption opt_random_seed (_cat, "rnd-seed", "Used by the random variable selection", 91648253, DoubleRange(0, false, HUGE_VAL, false));
static IntOption opt_ccmin_mode (_cat, "ccmin-mode", "Controls conflict clause minimization (0=none, 1=basic, 2=deep)", 2, IntRange(0, 2));
static IntOption opt_phase_saving (_cat, "phase-saving", "Controls the level of phase saving (0=none, 1=limited, 2=full)", 2, IntRange(0, 2));
static BoolOption opt_rnd_init_act (_cat, "rnd-init", "Randomize the initial activity", false);
/*
static IntOption opt_restart_first (_cat, "rfirst", "The base restart interval", 100, IntRange(1, INT32_MAX));
static DoubleOption opt_restart_inc (_cat, "rinc", "Restart interval increase factor", 2, DoubleRange(1, false, HUGE_VAL, false));
*/
static DoubleOption opt_garbage_frac (_cat, "gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered", 0.20, DoubleRange(0, false, HUGE_VAL, false));
static BoolOption opt_certified (_certified, "certified", "Certified UNSAT using DRUP format", false);
static StringOption opt_certified_file (_certified, "certified-output", "Certified UNSAT output file", "NULL");
static BoolOption opt_vbyte (_certified, "vbyte", "Emit proof in variable-byte encoding", false);
//=================================================================================================
// Constructor/Destructor:
inline Solver::Solver() :
// Parameters (user settable):
//
verbosity (0)
, showModel (0)
, K (opt_K)
, R (opt_R)
, sizeLBDQueue (opt_size_lbd_queue)
, sizeTrailQueue (opt_size_trail_queue)
, firstReduceDB (opt_first_reduce_db)
, incReduceDB (opt_inc_reduce_db)
, specialIncReduceDB (opt_spec_inc_reduce_db)
, lbLBDFrozenClause (opt_lb_lbd_frozen_clause)
, lbSizeMinimizingClause (opt_lb_size_minimzing_clause)
, lbLBDMinimizingClause (opt_lb_lbd_minimzing_clause)
, var_decay (opt_var_decay)
, clause_decay (opt_clause_decay)
, random_var_freq (opt_random_var_freq)
, random_seed (opt_random_seed)
, ccmin_mode (opt_ccmin_mode)
, phase_saving (opt_phase_saving)
, rnd_pol (false)
, rnd_init_act (opt_rnd_init_act)
, garbage_frac (opt_garbage_frac)
, certifiedOutput (NULL)
, certifiedUNSAT (opt_certified)
, vbyte (opt_vbyte)
// Statistics: (formerly in 'SolverStats')
//
, nbRemovedClauses(0),nbReducedClauses(0), nbDL2(0),nbBin(0),nbUn(0) , nbReduceDB(0)
, solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0),conflicts(0),conflictsRestarts(0),nbstopsrestarts(0),nbstopsrestartssame(0),lastblockatrestart(0)
, dec_vars(0), clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0)
, curRestart(1)
, ok (true)
, cla_inc (1)
, var_inc (1)
, watches (WatcherDeleted(ca))
, watchesBin (WatcherDeleted(ca))
, qhead (0)
, simpDB_assigns (-1)
, simpDB_props (0)
, order_heap (VarOrderLt(activity))
, progress_estimate (0)
, remove_satisfied (true)
// Resource constraints:
//
, conflict_budget (-1)
, propagation_budget (-1)
, asynch_interrupt (false)
, incremental(opt_incremental)
, nbVarsInitialFormula(INT32_MAX)
{
MYFLAG=H=Y=O=e=0;
G=1; A=4; Z=15000;
// Initialize only first time. Useful for incremental solving, useless otherwise
lbdQueue.initSize(sizeLBDQueue);
trailQueue.initSize(sizeTrailQueue);
sumLBD = 0;
nbclausesbeforereduce = firstReduceDB;
totalTime4Sat=0;totalTime4Unsat=0;
nbSatCalls=0;nbUnsatCalls=0;
if(certifiedUNSAT) {
if(!strcmp(opt_certified_file,"NULL")) {
vbyte = false; // Cannot write binary to stdout
certifiedOutput = fopen("/dev/stdout", "wb");
} else {
certifiedOutput = fopen(opt_certified_file, "wb");
}
// fprintf(certifiedOutput,"o proof DRUP\n");
}
}
inline Solver::~Solver()
{
}
/****************************************************************
Set the incremental mode
****************************************************************/
// This function set the incremental mode to true.
// You can add special code for this mode here.
inline void Solver::setIncrementalMode() {
incremental = true;
}
// Number of variables without selectors
inline void Solver::initNbInitialVars(int nb) {
nbVarsInitialFormula = nb;
}
//=================================================================================================
// Minor methods:
// Creates a new SAT variable in the solver. If 'decision' is cleared, variable will not be
// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result).
//
inline Var Solver::newVar(bool sign, bool dvar)
{
int v = nVars();
watches .init(mkLit(v, false));
watches .init(mkLit(v, true ));
watchesBin .init(mkLit(v, false));
watchesBin .init(mkLit(v, true ));
assigns .push(l_Undef);
vardata .push(mkVarData(CRef_Undef, 0));
//activity .push(0);
activity .push(rnd_init_act ? drand(random_seed) * 0.00001 : 0);
seen .push(0);
permDiff .push(0);
polarity .push(sign);
decision .push();
trail .capacity(v+1);
setDecisionVar(v, dvar);
return v;
}
inline unsigned char b[2097152];
inline void Solver::write_char (unsigned char ch) {
b[e++] = ch; }
//if (putc_unlocked ((int)
#define write_char b[e++] =
//= EOF) exit(1); }
inline void Solver::write_lit (int n) {
for (; n > 127; n >>= 7)
write_char (128 | (n & 127));
write_char (n); if (e > 1048576) fwrite(b, 1, e, certifiedOutput), e = 0; }
inline bool Solver::addClause_(vec<Lit>& ps)
{
assert(decisionLevel() == 0);
if (!ok) return false;
// Check if clause is satisfied and remove false/duplicate literals:
sort(ps);
vec<Lit> oc;
oc.clear();
Lit p; int i, j, flag = 0;
if(certifiedUNSAT) {
for (i = j = 0, p = lit_Undef; i < ps.size(); i++) {
oc.push(ps[i]);
if (value(ps[i]) == l_True || ps[i] == ~p || value(ps[i]) == l_False)
flag = 1;
}
}
for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
if (value(ps[i]) == l_True || ps[i] == ~p)
return true;
else if (value(ps[i]) != l_False && ps[i] != p)
ps[j++] = p = ps[i];
ps.shrink(i - j);
if (i != j && (certifiedUNSAT)) {
if (vbyte) {
write_char('a');
for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
write_lit(2*(var(ps[i])+1) + sign(ps[i]));
write_lit(0);
write_char('d');
for (i = j = 0, p = lit_Undef; i < oc.size(); i++)
write_lit(2*(var(oc[i])+1) + sign(oc[i]));
write_lit(0);
}
else {
for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
fprintf(certifiedOutput, "%i ", (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1));
fprintf(certifiedOutput, "0\n");
fprintf(certifiedOutput, "d ");
for (i = j = 0, p = lit_Undef; i < oc.size(); i++)
fprintf(certifiedOutput, "%i ", (var(oc[i]) + 1) * (-2 * sign(oc[i]) + 1));
fprintf(certifiedOutput, "0\n");
}
}
if (ps.size() == 0)
return ok = false;
else if (ps.size() == 1){
uncheckedEnqueue(ps[0]);
return ok = (propagate() == CRef_Undef);
}else{
CRef cr = ca.alloc(ps, false);
clauses.push(cr);
attachClause(cr);
}
return true;
}
inline void Solver::attachClause(CRef cr) {
const Clause& c = ca[cr];
assert(c.size() > 1);
if(c.size()==2) {
watchesBin[~c[0]].push(Watcher(cr, c[1]));
watchesBin[~c[1]].push(Watcher(cr, c[0]));
} else {
watches[~c[0]].push(Watcher(cr, c[1]));
watches[~c[1]].push(Watcher(cr, c[0]));
}
if (c.learnt()) learnts_literals += c.size();
else clauses_literals += c.size(); }
inline void Solver::detachClause(CRef cr, bool strict) {
const Clause& c = ca[cr];
assert(c.size() > 1);
if(c.size()==2) {
if (strict){
remove(watchesBin[~c[0]], Watcher(cr, c[1]));
remove(watchesBin[~c[1]], Watcher(cr, c[0]));
}else{
// Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause)
watchesBin.smudge(~c[0]);
watchesBin.smudge(~c[1]);
}
} else {
if (strict){
remove(watches[~c[0]], Watcher(cr, c[1]));
remove(watches[~c[1]], Watcher(cr, c[0]));
}else{
// Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause)
watches.smudge(~c[0]);
watches.smudge(~c[1]);
}
}
if (c.learnt()) learnts_literals -= c.size();
else clauses_literals -= c.size(); }
inline void Solver::removeClause(CRef cr) {
Clause& c = ca[cr];
if (certifiedUNSAT) {
if (vbyte) {
write_char ('d');
for (int i = 0; i < c.size(); i++)
write_lit(2*(var(c[i])+1) + sign(c[i]));
write_lit (0);
}
else {
fprintf(certifiedOutput, "d ");
for (int i = 0; i < c.size(); i++)
fprintf(certifiedOutput, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
fprintf(certifiedOutput, "0\n");
}
}
detachClause(cr);
// Don't leave pointers to free'd memory!
if (locked(c)) vardata[var(c[0])].reason = CRef_Undef;
c.mark(1);
ca.free(cr);
}
inline bool Solver::satisfied(const Clause& c) const {
if(incremental) // Check clauses with many selectors is too time consuming
return (value(c[0]) == l_True) || (value(c[1]) == l_True);
// Default mode.
for (int i = 0; i < c.size(); i++)
if (value(c[i]) == l_True)
return true;
return false;
}
/************************************************************
* Compute LBD functions
*************************************************************/
inline unsigned int Solver::computeLBD(const vec<Lit> & lits,int end) {
int nblevels = 0;
MYFLAG++;
if(incremental) { // ----------------- INCREMENTAL MODE
if(end==-1) end = lits.size();
unsigned int nbDone = 0;
for(int i=0;i<lits.size();i++) {
if(nbDone>=end) break;
if(isSelector(var(lits[i]))) continue;
nbDone++;
int l = level(var(lits[i]));
if (permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
} else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ
for(int i=0;i<lits.size();i++) {
int l = level(var(lits[i]));
if (l && permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
}
return nblevels;
}
inline unsigned int Solver::computeLBD(const Clause &c) {
int nblevels = 0;
MYFLAG++;
if(incremental) { // ----------------- INCREMENTAL MODE
int nbDone = 0;
for(int i=0;i<c.size();i++) {
if(nbDone>=c.sizeWithoutSelectors()) break;
if(isSelector(var(c[i]))) continue;
nbDone++;
int l = level(var(c[i]));
if (permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
} else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ
for(int i=0;i<c.size();i++) {
int l = level(var(c[i]));
if (l && permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
}
return nblevels;
}
/******************************************************************
* Minimisation with binary reolution
******************************************************************/
inline void Solver::minimisationWithBinaryResolution(vec<Lit> &out_learnt) {
// Find the LBD measure
unsigned int lbd = computeLBD(out_learnt);
Lit p = ~out_learnt[0];
if(lbd<=lbLBDMinimizingClause){
MYFLAG++;
for(int i = 1;i<out_learnt.size();i++) {
permDiff[var(out_learnt[i])] = MYFLAG;
}
vec<Watcher>& wbin = watchesBin[p];
int nb = 0;
for(int k = 0;k<wbin.size();k++) {
Lit imp = wbin[k].blocker;
if(permDiff[var(imp)]==MYFLAG && value(imp)==l_True) {
nb++;
permDiff[var(imp)]= MYFLAG-1;
}
}
int l = out_learnt.size()-1;
if(nb>0) {
nbReducedClauses++;
for(int i = 1;i<out_learnt.size()-nb;i++) {
if(permDiff[var(out_learnt[i])]!=MYFLAG) {
Lit p = out_learnt[l];
out_learnt[l] = out_learnt[i];
out_learnt[i] = p;
l--;i--;
}
}
out_learnt.shrink(nb);
}
}
}
// Revert to the state at given level (keeping all assignment at 'level' but not beyond).
//
inline void Solver::cancelUntil(int level) {
if (decisionLevel() > level){
for (int c = trail.size()-1; c >= trail_lim[level]; c--){
Var x = var(trail[c]);
assigns [x] = l_Undef;
if (phase_saving > 1 || ((phase_saving == 1) && c > trail_lim.last()))
polarity[x] = sign(trail[c]);
insertVarOrder(x); }
qhead = trail_lim[level];
trail.shrink(trail.size() - trail_lim[level]);
trail_lim.shrink(trail_lim.size() - level);
}
}
//=================================================================================================
// Major methods:
inline Lit Solver::pickBranchLit()
{
Var next = var_Undef;
// Random decision:
if (drand(random_seed) < random_var_freq && !order_heap.empty()){
next = order_heap[irand(random_seed,order_heap.size())];
if (value(next) == l_Undef && decision[next])
rnd_decisions++; }
// Activity based decision:
while (next == var_Undef || value(next) != l_Undef || !decision[next])
if (order_heap.empty()){
next = var_Undef;
break;
}else
next = order_heap.removeMin();
return next == var_Undef ? lit_Undef : mkLit(next, rnd_pol ? drand(random_seed) < 0.5 : polarity[next]);
}
/*_________________________________________________________________________________________________
|
| analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&) -> [void]
|
| Description:
| Analyze conflict and produce a reason clause.
|
| Pre-conditions:
| * 'out_learnt' is assumed to be cleared.
| * Current decision level must be greater than root level.
|
| Post-conditions:
| * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'.
| * If out_learnt.size() > 1 then 'out_learnt[1]' has the greatest decision level of the
| rest of literals. There may be others from the same level though.
|
|________________________________________________________________________________________________@*/
inline void Solver::analyze(CRef confl, vec<Lit>& out_learnt,vec<Lit>&selectors, int& out_btlevel,unsigned int &lbd,unsigned int &szWithoutSelectors)
{
int pathC = 0;
Lit p = lit_Undef;
// Generate conflict clause:
//
out_learnt.push(); // (leave room for the asserting literal)
int index = trail.size() - 1;
do{
assert(confl != CRef_Undef); // (otherwise should be UIP)
Clause& c = ca[confl];
// Special case for binary clauses
// The first one has to be SAT
if( p != lit_Undef && c.size()==2 && value(c[0])==l_False) {
assert(value(c[1])==l_True);
Lit tmp = c[0];
c[0] = c[1], c[1] = tmp;
}
if (0 && c.learnt())
claBumpActivity(c);
#ifdef DYNAMICNBLEVEL
// DYNAMIC NBLEVEL trick (see competition'09 companion paper)
if(c.learnt() && c.M() != 3) {
unsigned int nblevels = I = computeLBD(c);
if(nblevels<c.lbd() ) { // improve the LBD
if(c.lbd()<=lbLBDFrozenClause) {
c.setCanBeDel(false);
}
// seems to be interesting : keep it for the next round
c.setLBD(nblevels); // Update it
if (I < A){
C.P(confl);
c.M(3);
}else if (I < 7 && !c.M()){
T.P(confl);
c.M(2); }
}
if (c.M() == 2) c.t = Q;
if (!c.M()) B(c);
}
#endif
for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){
Lit q = c[j];
if (!seen[var(q)] && level(var(q)) > 0){
if(!isSelector(var(q)))
varBumpActivity(var(q));
seen[var(q)] = 1;
if (level(var(q)) >= decisionLevel()) {
pathC++;
#ifdef UPDATEVARACTIVITY
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(q)) && (reason(var(q))!= CRef_Undef) && ca[reason(var(q))].learnt())
lastDecisionLevel.push(q);
#endif
} else {
if(isSelector(var(q))) {
assert(value(q) == l_False);
selectors.push(q);
} else
out_learnt.push(q);
}
}
}
// Select next clause to look at:
while (!seen[var(trail[index--])]);
p = trail[index+1];
confl = reason(var(p));
seen[var(p)] = 0;
pathC--;
}while (pathC > 0);
out_learnt[0] = ~p;
// Simplify conflict clause:
//
int i, j;
for(int i = 0;i<selectors.size();i++)
out_learnt.push(selectors[i]);
out_learnt.copyTo(analyze_toclear);
if (ccmin_mode == 2){
uint32_t abstract_level = 0;
for (i = 1; i < out_learnt.size(); i++)
abstract_level |= abstractLevel(var(out_learnt[i])); // (maintain an abstraction of levels involved in conflict)
for (i = j = 1; i < out_learnt.size(); i++)
if (reason(var(out_learnt[i])) == CRef_Undef || !litRedundant(out_learnt[i], abstract_level))
out_learnt[j++] = out_learnt[i];
}else if (ccmin_mode == 1){
for (i = j = 1; i < out_learnt.size(); i++){
Var x = var(out_learnt[i]);
if (reason(x) == CRef_Undef)
out_learnt[j++] = out_learnt[i];
else{
Clause& c = ca[reason(var(out_learnt[i]))];
// Thanks to Siert Wieringa for this bug fix!
for (int k = ((c.size()==2) ? 0:1); k < c.size(); k++)
if (!seen[var(c[k])] && level(var(c[k])) > 0){
out_learnt[j++] = out_learnt[i];
break; }
}
}
}else
i = j = out_learnt.size();
max_literals += out_learnt.size();
out_learnt.shrink(i - j);
tot_literals += out_learnt.size();
/* ***************************************
Minimisation with binary clauses of the asserting clause
First of all : we look for small clauses
Then, we reduce clauses with small LBD.
Otherwise, this can be useless
*/
if(!incremental && out_learnt.size()<=lbSizeMinimizingClause) {
minimisationWithBinaryResolution(out_learnt);
}
// Find correct backtrack level:
//
if (out_learnt.size() == 1)
out_btlevel = 0;
else{
int max_i = 1;
// Find the first literal assigned at the next-highest level:
for (int i = 2; i < out_learnt.size(); i++)
if (level(var(out_learnt[i])) > level(var(out_learnt[max_i])))
max_i = i;
// Swap-in this literal at index 1:
Lit p = out_learnt[max_i];
out_learnt[max_i] = out_learnt[1];
out_learnt[1] = p;
out_btlevel = level(var(p));
}
// Compute the size of the clause without selectors (incremental mode)
if(incremental) {
szWithoutSelectors = 0;
for(int i=0;i<out_learnt.size();i++) {
if(!isSelector(var((out_learnt[i])))) szWithoutSelectors++;
else if(i>0) break;
}
} else
szWithoutSelectors = out_learnt.size();
// Compute LBD
lbd = computeLBD(out_learnt,out_learnt.size()-selectors.size());
#ifdef UPDATEVARACTIVITY
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(lastDecisionLevel.size()>0) {
for(int i = 0;i<lastDecisionLevel.size();i++) {
if(ca[reason(var(lastDecisionLevel[i]))].lbd()<lbd)
varBumpActivity(var(lastDecisionLevel[i]));
}
lastDecisionLevel.clear();
}
#endif
lbd--;
for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared)
for(int j = 0 ; j<selectors.size() ; j++) seen[var(selectors[j])] = 0;
}
// Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is
// visiting literals at levels that cannot be removed later.
inline bool Solver::litRedundant(Lit p, uint32_t abstract_levels)
{
analyze_stack.clear(); analyze_stack.push(p);
int top = analyze_toclear.size();
while (analyze_stack.size() > 0){
assert(reason(var(analyze_stack.last())) != CRef_Undef);
Clause& c = ca[reason(var(analyze_stack.last()))]; analyze_stack.pop();
if(c.size()==2 && value(c[0])==l_False) {
assert(value(c[1])==l_True);
Lit tmp = c[0];
c[0] = c[1], c[1] = tmp;
}
for (int i = 1; i < c.size(); i++){
Lit p = c[i];
if (!seen[var(p)] && level(var(p)) > 0){
if (reason(var(p)) != CRef_Undef && (abstractLevel(var(p)) & abstract_levels) != 0){
seen[var(p)] = 1;
analyze_stack.push(p);
analyze_toclear.push(p);
}else{
for (int j = top; j < analyze_toclear.size(); j++)
seen[var(analyze_toclear[j])] = 0;
analyze_toclear.shrink(analyze_toclear.size() - top);
return false;
}
}
}
}
return true;
}
/*_________________________________________________________________________________________________
|
| analyzeFinal : (p : Lit) -> [void]
|
| Description:
| Specialized analysis procedure to express the final conflict in terms of assumptions.
| Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and
| stores the result in 'out_conflict'.
|________________________________________________________________________________________________@*/
inline void Solver::analyzeFinal(Lit p, vec<Lit>& out_conflict)
{
out_conflict.clear();
out_conflict.push(p);
if (decisionLevel() == 0)
return;
seen[var(p)] = 1;
for (int i = trail.size()-1; i >= trail_lim[0]; i--){
Var x = var(trail[i]);
if (seen[x]){
if (reason(x) == CRef_Undef){
assert(level(x) > 0);
out_conflict.push(~trail[i]);
}else{
Clause& c = ca[reason(x)];
// for (int j = 1; j < c.size(); j++) Minisat (glucose 2.0) loop
// Bug in case of assumptions due to special data structures for Binary.
// Many thanks to Sam Bayless (sbayless@cs.ubc.ca) for discover this bug.
for (int j = ((c.size()==2) ? 0:1); j < c.size(); j++)
if (level(var(c[j])) > 0)
seen[var(c[j])] = 1;
}
seen[x] = 0;
}
}
seen[var(p)] = 0;
}
inline void Solver::uncheckedEnqueue(Lit p, CRef from)
{
assert(value(p) == l_Undef);
assigns[var(p)] = lbool(!sign(p));
vardata[var(p)] = mkVarData(from, decisionLevel());
trail.push_(p);
}
/*_________________________________________________________________________________________________
|
| propagate : [void] -> [Clause*]
|
| Description:
| Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned,
| otherwise CRef_Undef.
|
| Post-conditions:
| * the propagation queue is empty, even if there was a conflict.
|________________________________________________________________________________________________@*/
inline CRef Solver::propagate()
{
CRef confl = CRef_Undef;
int num_props = 0;
watches.cleanAll();
watchesBin.cleanAll();
while (qhead < trail.size()){
Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate.
vec<Watcher>& ws = watches[p];
Watcher *i, *j, *end;
num_props++;
// First, Propagate binary clauses
vec<Watcher>& wbin = watchesBin[p];
for(int k = 0;k<wbin.size();k++) {
Lit imp = wbin[k].blocker;
if(value(imp) == l_False) {
return wbin[k].cref;
}
if(value(imp) == l_Undef) {
uncheckedEnqueue(imp,wbin[k].cref);
}
}
for (i = j = (Watcher*)ws, end = i + ws.size(); i != end;){
// Try to avoid inspecting the clause:
Lit blocker = i->blocker;
if (value(blocker) == l_True){
*j++ = *i++; continue; }
// Make sure the false literal is data[1]:
CRef cr = i->cref;
Clause& c = ca[cr];
Lit false_lit = ~p;
if (c[0] == false_lit)
c[0] = c[1], c[1] = false_lit;
assert(c[1] == false_lit);
i++;
// If 0th watch is true, then clause is already satisfied.
Lit first = c[0];
Watcher w = Watcher(cr, first);
if (first != blocker && value(first) == l_True){
*j++ = w; continue; }
// Look for new watch:
if(incremental) { // ----------------- INCREMENTAL MODE
int choosenPos = -1;
for (int k = 2; k < c.size(); k++) {
if (value(c[k]) != l_False){
if(decisionLevel()>assumptions.size()) {
choosenPos = k;
break;
} else {
choosenPos = k;
if(value(c[k])==l_True || !isSelector(var(c[k]))) {
break;
}
}
}
}
if(choosenPos!=-1) {
c[1] = c[choosenPos]; c[choosenPos] = false_lit;
watches[~c[1]].push(w);
goto NextClause; }
} else { // ----------------- DEFAULT MODE (NOT INCREMENTAL)
for (int k = 2; k < c.size(); k++) {
if (value(c[k]) != l_False){
c[1] = c[k]; c[k] = false_lit;
watches[~c[1]].push(w);
goto NextClause; }
}
}
// Did not find watch -- clause is unit under assignment:
*j++ = w;
if (value(first) == l_False){
confl = cr;
qhead = trail.size();
// Copy the remaining watches:
while (i < end)
*j++ = *i++;
}else {
uncheckedEnqueue(first, cr);
}
NextClause:;
}
ws.shrink(i - j);
}
propagations += num_props;
simpDB_props -= num_props;
return confl;
}
/*_________________________________________________________________________________________________
|
| reduceDB : () -> [void]
|
| Description:
| Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked
| clauses are clauses that are reason to some assignment. Binary clauses are never removed.
|________________________________________________________________________________________________@*/
struct reduceDB_lt {
ClauseAllocator& ca;
reduceDB_lt(ClauseAllocator& ca_) : ca(ca_) {}
bool operator () (CRef x, CRef y) {
/*
// Main criteria... Like in MiniSat we keep all binary clauses
if(ca[x].size()> 2 && ca[y].size()==2) return 1;
if(ca[y].size()>2 && ca[x].size()==2) return 0;
if(ca[x].size()==2 && ca[y].size()==2) return 0;
// Second one based on literal block distance
if(ca[x].lbd()> ca[y].lbd()) return 1;
if(ca[x].lbd()< ca[y].lbd()) return 0;
*/
// Finally we can use old activity or size, we choose the last one
return ca[x].activity() < ca[y].activity();
//return x->size() < y->size();
//return ca[x].size() > 2 && (ca[y].size() == 2 || ca[x].activity() < ca[y].activity()); }
}
};
inline void Solver::reduceDB()
{
int i, j;
nbReduceDB++;
sort(learnts, reduceDB_lt(ca));
// We have a lot of "good" clauses, it is difficult to compare them. Keep more !
//if(ca[learnts[learnts.size() / RATIOREMOVECLAUSES]].lbd()<=3) nbclausesbeforereduce +=specialIncReduceDB;
// Useless :-)
//if(ca[learnts.last()].lbd()<=5) nbclausesbeforereduce +=specialIncReduceDB;
// Don't delete binary or locked clauses. From the rest, delete clauses from the first half
// Keep clauses which seem to be usefull (their lbd was reduce during this sequence)
int limit = learnts.size() / 2;
for (i = j = 0; i < learnts.size(); i++){
Clause& c = ca[learnts[i]];
if (!c.M())
if (c.lbd()>2 && c.size() > 2 && c.canBeDel() && !locked(c) && (i < limit)) {
removeClause(learnts[i]);
nbRemovedClauses++;
}
else {
if(!c.canBeDel()) limit++; //we keep c, so we can delete an other clause
c.setCanBeDel(true); // At the next step, c can be delete
learnts[j++] = learnts[i];
}
}
learnts.shrink(i - j);
checkGarbage();
}
inline void Solver::removeSatisfied(vec<CRef>& cs)
{
int i, j;
for (i = j = 0; i < cs.size(); i++){
Clause& c = ca[cs[i]];
if (c.M() == O)
if (satisfied(c))
removeClause(cs[i]);
else
cs[j++] = cs[i];
}
cs.shrink(i - j);
}
inline void Solver::rebuildOrderHeap()
{
vec<Var> vs;
for (Var v = 0; v < nVars(); v++)
if (decision[v] && value(v) == l_Undef)
vs.push(v);
order_heap.build(vs);
}
/*_________________________________________________________________________________________________
|
| simplify : [void] -> [bool]
|
| Description:
| Simplify the clause database according to the current top-level assigment. Currently, the only
| thing done here is the removal of satisfied clauses, but more things can be put here.
|________________________________________________________________________________________________@*/
inline bool Solver::simplify()
{
assert(decisionLevel() == 0);
if (!ok || propagate() != CRef_Undef)
return ok = false;
if (nAssigns() == simpDB_assigns || (simpDB_props > 0))
return true;
// Remove satisfied clauses:
#define S removeSatisfied
O = 3; S(C);
O = 2; S(T);
O = 0;
removeSatisfied(learnts);
if (remove_satisfied) // Can be turned off.
removeSatisfied(clauses);
checkGarbage();
rebuildOrderHeap();
simpDB_assigns = nAssigns();
simpDB_props = clauses_literals + learnts_literals; // (shouldn't depend on stats really, but it will do for now)
return true;
}
/*_________________________________________________________________________________________________
|
| search : (nof_conflicts : int) (params : const SearchParams&) -> [lbool]
|
| Description:
| Search for a model the specified number of conflicts.
| NOTE! Use negative value for 'nof_conflicts' indicate infinity.
|
| Output:
| 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If
| all variables are decision variables, this means that the clause set is satisfiable. 'l_False'
| if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached.
|________________________________________________________________________________________________@*/
inline lbool Solver::search(int& n//of_conflicts
)
{
assert(ok);
int backtrack_level;
int conflictC = 0;
vec<Lit> learnt_clause,selectors;
unsigned int nblevels,szWoutSelectors;
bool blocked=false;
starts++;
for (;;){
CRef confl = propagate();
if (confl != CRef_Undef){
// CONFLICT
conflicts++; conflictC++;conflictsRestarts++;
Y--; Z--; n--;
if (Q == 100000 && C.size() < 100) A = 6;
if(0 && conflicts%5000==0 && var_decay<0.95)
var_decay += 0.01;
if (0 && verbosity >= 1 && conflicts%verbEveryConflicts==0){
printf("c | %8d %7d %5d | %7d %8d %8d | %5d %8d %6d %8d | %6.3f %% |\n",
(int)starts,(int)nbstopsrestarts, (int)(conflicts/starts),
(int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]), nClauses(), (int)clauses_literals,
(int)nbReduceDB, nLearnts(), (int)nbDL2,(int)nbRemovedClauses, progressEstimate()*100);
}
if (decisionLevel() == 0) {
return l_False;
}
/*
trailQueue.push(trail.size());
// BLOCK RESTART (CP 2012 paper)
if( conflictsRestarts>LOWER_BOUND_FOR_BLOCKING_RESTART && lbdQueue.isvalid() && trail.size()>R*trailQueue.getavg()) {
lbdQueue.fastclear();
nbstopsrestarts++;
if(!blocked) {lastblockatrestart=starts;nbstopsrestartssame++;blocked=true;}
}
*/
learnt_clause.clear();
selectors.clear();
analyze(confl, learnt_clause, selectors,backtrack_level,nblevels,szWoutSelectors);
if (G){
H++;
lbdQueue.push(nblevels);
sumLBD += nblevels > 50 ? 50 : nblevels;
}
cancelUntil(backtrack_level);
if (certifiedUNSAT) {
if (vbyte) {
write_char('a');
for (int i = 0; i < learnt_clause.size(); i++)
write_lit(2*(var(learnt_clause[i])+1) + sign(learnt_clause[i]));
write_lit(0);
}
else {
for (int i = 0; i < learnt_clause.size(); i++)
fprintf(certifiedOutput, "%i " , (var(learnt_clause[i]) + 1) *
(-2 * sign(learnt_clause[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
if (learnt_clause.size() == 1){
uncheckedEnqueue(learnt_clause[0]);nbUn++;
}else{
#define EE ca[cr]
CRef cr = ca.alloc(learnt_clause, true);
ca[cr].setLBD(I = nblevels);
ca[cr].setSizeWithoutSelectors(szWoutSelectors);
if(nblevels<=2) nbDL2++; // stats
if(ca[cr].size()==2) nbBin++; // stats
if (I < A){
C.P(cr);
EE.M(3);
}else if (I < 7){
T.P(cr);
EE.M(2);
EE.t = Q;
}else{
learnts.push(cr); B(EE); }
attachClause(cr);
//claBumpActivity(ca[cr]);
uncheckedEnqueue(learnt_clause[0], cr);
}
varDecayActivity();
claDecayActivity();
}else{
// Our dynamic restart, see the SAT09 competition compagnion paper
if ((!G && n <= 0) || (G &&
( lbdQueue.isvalid() && ((lbdQueue.getavg()*(n > 0 ? K : .9)) > (sumLBD / H//conflictsRestarts
))))) {
lbdQueue.fastclear();
progress_estimate = progressEstimate();
int bt = 0;
if(incremental) { // DO NOT BACKTRACK UNTIL 0.. USELESS
bt = (decisionLevel()<assumptions.size()) ? decisionLevel() : assumptions.size();
}
cancelUntil(bt);
return l_Undef; }
// Simplify the set of problem clauses:
if (decisionLevel() == 0 && !simplify()) {
return l_False;
}
if (Y <= 0){
for (I = Y = 0; I < T.size(); I++){
Clause& c = ca[T[I]];
if (c.M() == 2)
if (!locked(c) && c.t + 30000 < Q){
learnts.P(T[I]);
c.M(0);
c.activity() = 0;
B(c);
}else
T[Y++] = T[I];
}
T.shrink(I - Y);
Y = 10000;
}
// Perform clause database reduction !
if(Z <= 0)//conflicts>=curRestart* nbclausesbeforereduce)
{
assert(learnts.size()>0);
curRestart = (conflicts/ nbclausesbeforereduce)+1;
reduceDB();
nbclausesbeforereduce += incReduceDB;
Z = 15000;
}
Lit next = lit_Undef;
while (decisionLevel() < assumptions.size()){
// Perform user provided assumption:
Lit p = assumptions[decisionLevel()];
if (value(p) == l_True){
// Dummy decision level:
newDecisionLevel();
}else if (value(p) == l_False){
analyzeFinal(~p, conflict);
return l_False;
}else{
next = p;
break;
}
}
if (next == lit_Undef){
// New variable decision:
decisions++;
next = pickBranchLit();
if (next == lit_Undef){
// printf("c last restart ## conflicts : %d %d \n",conflictC,decisionLevel());
// Model found:
return l_True;
}
}
// Increase decision level and enqueue 'next'
newDecisionLevel();
uncheckedEnqueue(next);
}
}
}
inline double Solver::progressEstimate() const
{
double progress = 0;
double F = 1.0 / nVars();
for (int i = 0; i <= decisionLevel(); i++){
int beg = i == 0 ? 0 : trail_lim[i - 1];
int end = i == decisionLevel() ? trail.size() : trail_lim[i];
progress += pow(F, i) * (end - beg);
}
return progress / nVars();
}
inline void Solver::printIncrementalStats() {
printf("c---------- Glucose Stats -------------------------\n");
printf("c restarts : %lld\n", starts);
printf("c nb ReduceDB : %lld\n", nbReduceDB);
printf("c nb removed Clauses : %lld\n",nbRemovedClauses);
printf("c nb learnts DL2 : %lld\n", nbDL2);
printf("c nb learnts size 2 : %lld\n", nbBin);
printf("c nb learnts size 1 : %lld\n", nbUn);
printf("c conflicts : %lld \n",conflicts);
printf("c decisions : %lld\n",decisions);
printf("c propagations : %lld\n",propagations);
printf("c SAT Calls : %d in %g seconds\n",nbSatCalls,totalTime4Sat);
printf("c UNSAT Calls : %d in %g seconds\n",nbUnsatCalls,totalTime4Unsat);
printf("c--------------------------------------------------\n");
}
// NOTE: assumptions passed in member-variable 'assumptions'.
inline lbool Solver::solve_()
{
if(incremental && certifiedUNSAT) {
printf("Can not use incremental and certified unsat in the same time\n");
exit(-1);
}
model.clear();
conflict.clear();
if (!ok) return l_False;
double curTime = cpuTime();
solves++;
lbool status = l_Undef;
if(!incremental && verbosity>=1) {
printf("c ========================================[ MAGIC CONSTANTS ]==============================================\n");
printf("c | Constants are supposed to work well together :-) |\n");
printf("c | however, if you find better choices, please let us known... |\n");
printf("c |-------------------------------------------------------------------------------------------------------|\n");
printf("c | | | |\n");
printf("c | - Restarts: | - Reduce Clause DB: | - Minimize Asserting: |\n");
printf("c | * LBD Queue : %6d | * First : %6d | * size < %3d |\n",lbdQueue.maxSize(),nbclausesbeforereduce,lbSizeMinimizingClause);
printf("c | * Trail Queue : %6d | * Inc : %6d | * lbd < %3d |\n",trailQueue.maxSize(),incReduceDB,lbLBDMinimizingClause);
printf("c | * K : %6.2f | * Special : %6d | |\n",K,specialIncReduceDB);
printf("c | * R : %6.2f | * Protected : (lbd)< %2d | |\n",R,lbLBDFrozenClause);
printf("c | | | |\n");
printf("c ==================================[ Search Statistics (every %6d conflicts) ]=========================\n",verbEveryConflicts);
printf("c | |\n");
printf("c | RESTARTS | ORIGINAL | LEARNT | Progress |\n");
printf("c | NB Blocked Avg Cfc | Vars Clauses Literals | Red Learnts LBD2 Removed | |\n");
printf("c =========================================================================================================\n");
}
// Search:
int curr_restarts = 0, a = 91, w;
while (status == l_Undef){
w = !H ? 10000 : a + G * a;
var_decay = G ? .95 : .999;
while (status == l_Undef && w > 0)
status = search(w); // the parameter is useless in glucose, kept to allow modifications
//if (!withinBudget()) break;
curr_restarts++;
if (!(G = !G)) a += a / 10;
}
if (!incremental && verbosity >= 1)
printf("c =========================================================================================================\n");
if (certifiedUNSAT){ // Want certified output
if (status == l_False) {
if (vbyte) {
write_char('a');
write_lit(0);
fwrite(b, 1, e, certifiedOutput), e = 0;
}
else {
fprintf(certifiedOutput, "0\n");
}
}
fclose(certifiedOutput);
}
if (status == l_True){
// Extend & copy model:
model.growTo(nVars());
for (int i = 0; i < nVars(); i++) model[i] = value(i);
}else if (status == l_False && conflict.size() == 0)
ok = false;
cancelUntil(0);
double finalTime = cpuTime();
if(status==l_True) {
nbSatCalls++;
totalTime4Sat +=(finalTime-curTime);
}
if(status==l_False) {
nbUnsatCalls++;
totalTime4Unsat +=(finalTime-curTime);
}
return status;
}
//=================================================================================================
// Writing CNF to DIMACS:
//
// FIXME: this needs to be rewritten completely.
static Var mapVar(Var x, vec<Var>& map, Var& max)
{
if (map.size() <= x || map[x] == -1){
map.growTo(x+1, -1);
map[x] = max++;
}
return map[x];
}
inline void Solver::toDimacs(FILE* f, Clause& c, vec<Var>& map, Var& max)
{
if (satisfied(c)) return;
for (int i = 0; i < c.size(); i++)
if (value(c[i]) != l_False)
fprintf(f, "%s%d ", sign(c[i]) ? "-" : "", mapVar(var(c[i]), map, max)+1);
fprintf(f, "0\n");
}
inline void Solver::toDimacs(const char *file, const vec<Lit>& assumps)
{
FILE* f = fopen(file, "wr");
if (f == NULL)
fprintf(stderr, "could not open file %s\n", file), exit(1);
toDimacs(f, assumps);
fclose(f);
}
inline void Solver::toDimacs(FILE* f, const vec<Lit>& assumps)
{
// Handle case when solver is in contradictory state:
if (!ok){
fprintf(f, "p cnf 1 2\n1 0\n-1 0\n");
return; }
assumps.copyTo(assumptions);
vec<Var> map; Var max = 0;
// Cannot use removeClauses here because it is not safe
// to deallocate them at this point. Could be improved.
int cnt = 0;
for (int i = 0; i < clauses.size(); i++)
if (!satisfied(ca[clauses[i]]))
cnt++;
for (int i = 0; i < clauses.size(); i++)
if (!satisfied(ca[clauses[i]])){
Clause& c = ca[clauses[i]];
for (int j = 0; j < c.size(); j++)
if (value(c[j]) != l_False)
mapVar(var(c[j]), map, max);
}
// Assumptions are added as unit clauses:
cnt += assumptions.size();
fprintf(f, "p cnf %d %d\n", max, cnt);
for (int i = 0; i < assumptions.size(); i++){
assert(value(assumptions[i]) != l_False);
fprintf(f, "%s%d 0\n", sign(assumptions[i]) ? "-" : "", mapVar(var(assumptions[i]), map, max)+1);
}
for (int i = 0; i < clauses.size(); i++)
toDimacs(f, ca[clauses[i]], map, max);
if (verbosity > 0)
printf("Wrote %d clauses with %d variables.\n", cnt, max);
}
//=================================================================================================
// Garbage Collection methods:
inline void Solver::relocAll(ClauseAllocator& to)
{
// All watchers:
//
// for (int i = 0; i < watches.size(); i++)
watches.cleanAll();
watchesBin.cleanAll();
for (int v = 0; v < nVars(); v++)
for (int s = 0; s < 2; s++){
Lit p = mkLit(v, s);
// printf(" >>> RELOCING: %s%d\n", sign(p)?"-":"", var(p)+1);
vec<Watcher>& ws = watches[p];
for (int j = 0; j < ws.size(); j++)
ca.reloc(ws[j].cref, to);
vec<Watcher>& ws2 = watchesBin[p];
for (int j = 0; j < ws2.size(); j++)
ca.reloc(ws2[j].cref, to);
}
// All reasons:
//
for (int i = 0; i < trail.size(); i++){
Var v = var(trail[i]);
if (reason(v) != CRef_Undef && (ca[reason(v)].reloced() || locked(ca[reason(v)])))
ca.reloc(vardata[v].reason, to);
}
// All learnt:
//
#define X(V) for (I = 0; I < V.size();) ca.reloc(V[I++], to);
X(C);
X(T);
for (int i = 0; i < learnts.size(); i++)
ca.reloc(learnts[i], to);
// All original:
//
for (int i = 0; i < clauses.size(); i++)
ca.reloc(clauses[i], to);
}
inline void Solver::garbageCollect()
{
// Initialize the next region to a size corresponding to the estimated utilization degree. This
// is not precise but should avoid some unnecessary reallocations for the new region:
ClauseAllocator to(ca.size() - ca.wasted());
relocAll(to);
if (verbosity >= 2)
printf("| Garbage collection: %12d bytes => %12d bytes |\n",
ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
to.moveTo(ca);
}
}
/************************************************************************************[SimpSolver.h]
Copyright (c) 2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
#ifndef Ghack_SimpSolver_h
#define Ghack_SimpSolver_h
namespace GHack {
//=================================================================================================
class SimpSolver : public Solver {
public:
// Constructor/Destructor:
//
SimpSolver();
~SimpSolver();
// Problem specification:
//
Var newVar (bool polarity = true, bool dvar = true);
bool addClause (const vec<Lit>& ps);
bool addEmptyClause(); // Add the empty clause to the solver.
bool addClause (Lit p); // Add a unit clause to the solver.
bool addClause (Lit p, Lit q); // Add a binary clause to the solver.
bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
bool addClause_( vec<Lit>& ps);
bool substitute(Var v, Lit x); // Replace all occurences of v with x (may cause a contradiction).
// Variable mode:
//
void setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated.
bool isEliminated(Var v) const;
// Solving:
//
bool solve (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
lbool solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
bool solve ( bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p , bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p, Lit q, bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false);
bool eliminate (bool turn_off_elim = false); // Perform variable elimination based simplification.
// Memory managment:
//
virtual void garbageCollect();
// Generate a (possibly simplified) DIMACS file:
//
#if 0
void toDimacs (const char* file, const vec<Lit>& assumps);
void toDimacs (const char* file);
void toDimacs (const char* file, Lit p);
void toDimacs (const char* file, Lit p, Lit q);
void toDimacs (const char* file, Lit p, Lit q, Lit r);
#endif
// Mode of operation:
//
int parsing;
int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero).
int clause_lim; // Variables are not eliminated if it produces a resolvent with a length above this limit.
// -1 means no limit.
int subsumption_lim; // Do not check if subsumption against a clause larger than this. -1 means no limit.
double simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac').
bool use_asymm; // Shrink clauses by asymmetric branching.
bool use_rcheck; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
bool use_elim; // Perform variable elimination.
// Statistics:
//
int merges;
int asymm_lits;
int eliminated_vars;
protected:
// Helper structures:
//
struct ElimLt {
const vec<int>& n_occ;
explicit ElimLt(const vec<int>& no) : n_occ(no) {}
// TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating
// 32-bit implementation instead then, but this will have to do for now.
uint64_t cost (Var x) const { return (uint64_t)n_occ[toInt(mkLit(x))] * (uint64_t)n_occ[toInt(~mkLit(x))]; }
bool operator()(Var x, Var y) const { return cost(x) < cost(y); }
// TODO: investigate this order alternative more.
// bool operator()(Var x, Var y) const {
// int c_x = cost(x);
// int c_y = cost(y);
// return c_x < c_y || c_x == c_y && x < y; }
};
struct ClauseDeleted {
const ClauseAllocator& ca;
explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } };
// Solver state:
//
int elimorder;
bool use_simplification;
vec<uint32_t> elimclauses;
vec<char> touched;
OccLists<Var, vec<CRef>, ClauseDeleted>
occurs;
vec<int> n_occ;
Heap<ElimLt> elim_heap;
Queue<CRef> subsumption_queue;
vec<char> frozen;
vec<char> eliminated;
int bwdsub_assigns;
int n_touched;
// Temporaries:
//
CRef bwdsub_tmpunit;
// Main internal methods:
//
lbool solve_ (bool do_simp = true, bool turn_off_simp = false);
bool asymm (Var v, CRef cr);
bool asymmVar (Var v);
void updateElimHeap (Var v);
void gatherTouchedClauses ();
bool merge (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause);
bool merge (const Clause& _ps, const Clause& _qs, Var v, int& size);
bool backwardSubsumptionCheck (bool verbose = false);
bool eliminateVar (Var v);
void extendModel ();
void removeClause (CRef cr);
bool strengthenClause (CRef cr, Lit l);
void cleanUpClauses ();
bool implied (const vec<Lit>& c);
void relocAll (ClauseAllocator& to);
};
//=================================================================================================
// Implementation of inline methods:
inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; }
inline void SimpSolver::updateElimHeap(Var v) {
assert(use_simplification);
// if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)
if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef))
elim_heap.update(v); }
inline bool SimpSolver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); }
inline bool SimpSolver::addEmptyClause() { add_tmp.clear(); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
inline void SimpSolver::setFrozen (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } }
inline bool SimpSolver::solve ( bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p , bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p, Lit q, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; }
inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); }
//=================================================================================================
}
#endif
/***********************************************************************************[SimpSolver.cc]
Copyright (c) 2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
namespace GHack {
//=================================================================================================
// Options:
static BoolOption opt_use_asymm ("SIMP", "asymm", "Shrink clauses by asymmetric branching.", false);
static BoolOption opt_use_rcheck ("SIMP", "rcheck", "Check if a clause is already implied. (costly)", false);
static BoolOption opt_use_elim ("SIMP", "elim", "Perform variable elimination.", true);
static IntOption opt_grow ("SIMP", "grow", "Allow a variable elimination step to grow by a number of clauses.", 0);
static IntOption opt_clause_lim ("SIMP", "cl-lim", "Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit", 20, IntRange(-1, INT32_MAX));
static IntOption opt_subsumption_lim ("SIMP", "sub-lim", "Do not check if subsumption against a clause larger than this. -1 means no limit.", 1000, IntRange(-1, INT32_MAX));
static DoubleOption opt_simp_garbage_frac("SIMP", "simp-gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered during simplification.", 0.5, DoubleRange(0, false, HUGE_VAL, false));
//=================================================================================================
// Constructor/Destructor:
inline SimpSolver::SimpSolver() :
grow (opt_grow)
, clause_lim (opt_clause_lim)
, subsumption_lim (opt_subsumption_lim)
, simp_garbage_frac (opt_simp_garbage_frac)
, use_asymm (opt_use_asymm)
, use_rcheck (opt_use_rcheck)
, use_elim (opt_use_elim)
, merges (0)
, asymm_lits (0)
, eliminated_vars (0)
, elimorder (1)
, use_simplification (true)
, occurs (ClauseDeleted(ca))
, elim_heap (ElimLt(n_occ))
, bwdsub_assigns (0)
, n_touched (0)
{
vec<Lit> dummy(1,lit_Undef);
ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below.
bwdsub_tmpunit = ca.alloc(dummy);
remove_satisfied = false;
}
inline SimpSolver::~SimpSolver()
{
}
inline Var SimpSolver::newVar(bool sign, bool dvar) {
Var v = Solver::newVar(sign, dvar);
frozen .push((char)false);
eliminated.push((char)false);
if (use_simplification){
n_occ .push(0);
n_occ .push(0);
occurs .init(v);
touched .push(0);
elim_heap .insert(v);
}
return v; }
inline lbool SimpSolver::solve_(bool do_simp, bool turn_off_simp)
{
vec<Var> extra_frozen;
lbool result = l_True;
do_simp &= use_simplification;
if (do_simp){
// Assumptions must be temporarily frozen to run variable elimination:
for (int i = 0; i < assumptions.size(); i++){
Var v = var(assumptions[i]);
// If an assumption has been eliminated, remember it.
assert(!isEliminated(v));
if (!frozen[v]){
// Freeze and store.
setFrozen(v, true);
extra_frozen.push(v);
} }
result = lbool(eliminate(turn_off_simp));
}
if (result == l_True)
result = Solver::solve_();
else if (verbosity >= 1)
printf("===============================================================================\n");
if (result == l_True)
extendModel();
if (do_simp)
// Unfreeze the assumptions that were frozen:
for (int i = 0; i < extra_frozen.size(); i++)
setFrozen(extra_frozen[i], false);
return result;
}
inline bool SimpSolver::addClause_(vec<Lit>& ps)
{
#ifndef NDEBUG
for (int i = 0; i < ps.size(); i++)
assert(!isEliminated(var(ps[i])));
#endif
int nclauses = clauses.size();
if (use_rcheck && implied(ps))
return true;
if (!Solver::addClause_(ps))
return false;
if(!parsing && certifiedUNSAT) {
if (vbyte) {
write_char('a');
for (int i = 0; i < ps.size(); i++)
write_lit(2*(var(ps[i])+1) + sign(ps[i]));
write_lit(0);
}
else {
for (int i = 0; i < ps.size(); i++)
fprintf(certifiedOutput, "%i " , (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
if (use_simplification && clauses.size() == nclauses + 1){
CRef cr = clauses.last();
const Clause& c = ca[cr];
// NOTE: the clause is added to the queue immediately and then
// again during 'gatherTouchedClauses()'. If nothing happens
// in between, it will only be checked once. Otherwise, it may
// be checked twice unnecessarily. This is an unfortunate
// consequence of how backward subsumption is used to mimic
// forward subsumption.
subsumption_queue.insert(cr);
for (int i = 0; i < c.size(); i++){
occurs[var(c[i])].push(cr);
n_occ[toInt(c[i])]++;
touched[var(c[i])] = 1;
n_touched++;
if (elim_heap.inHeap(var(c[i])))
elim_heap.increase(var(c[i]));
}
}
return true;
}
inline void SimpSolver::removeClause(CRef cr)
{
const Clause& c = ca[cr];
if (use_simplification)
for (int i = 0; i < c.size(); i++){
n_occ[toInt(c[i])]--;
updateElimHeap(var(c[i]));
occurs.smudge(var(c[i]));
}
Solver::removeClause(cr);
}
inline bool SimpSolver::strengthenClause(CRef cr, Lit l)
{
Clause& c = ca[cr];
assert(decisionLevel() == 0);
assert(use_simplification);
// FIX: this is too inefficient but would be nice to have (properly implemented)
// if (!find(subsumption_queue, &c))
subsumption_queue.insert(cr);
if (certifiedUNSAT) {
if (vbyte) {
write_char('a');
for (int i = 0; i < c.size(); i++)
if (c[i] != l) write_lit(2*(var(c[i])+1) + sign(c[i]));
write_lit(0);
}
else {
for (int i = 0; i < c.size(); i++)
if (c[i] != l) fprintf(certifiedOutput, "%i " , (var(c[i]) + 1) * (-2 * sign(c[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
if (c.size() == 2){
removeClause(cr);
c.strengthen(l);
}else{
if (certifiedUNSAT) {
if (vbyte) {
write_char('d');
for (int i = 0; i < c.size(); i++)
write_lit(2*(var(c[i])+1) + sign(c[i]));
write_lit(0);
}
else {
fprintf(certifiedOutput, "d ");
for (int i = 0; i < c.size(); i++)
fprintf(certifiedOutput, "%i " , (var(c[i]) + 1) * (-2 * sign(c[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
detachClause(cr, true);
c.strengthen(l);
attachClause(cr);
remove(occurs[var(l)], cr);
n_occ[toInt(l)]--;
updateElimHeap(var(l));
}
return c.size() == 1 ? enqueue(c[0]) && propagate() == CRef_Undef : true;
}
// Returns FALSE if clause is always satisfied ('out_clause' should not be used).
inline bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause)
{
merges++;
out_clause.clear();
bool ps_smallest = _ps.size() < _qs.size();
const Clause& ps = ps_smallest ? _qs : _ps;
const Clause& qs = ps_smallest ? _ps : _qs;
for (int i = 0; i < qs.size(); i++){
if (var(qs[i]) != v){
for (int j = 0; j < ps.size(); j++)
if (var(ps[j]) == var(qs[i]))
if (ps[j] == ~qs[i])
return false;
else
goto next;
out_clause.push(qs[i]);
}
next:;
}
for (int i = 0; i < ps.size(); i++)
if (var(ps[i]) != v)
out_clause.push(ps[i]);
return true;
}
// Returns FALSE if clause is always satisfied.
inline bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, int& size)
{
merges++;
bool ps_smallest = _ps.size() < _qs.size();
const Clause& ps = ps_smallest ? _qs : _ps;
const Clause& qs = ps_smallest ? _ps : _qs;
const Lit* __ps = (const Lit*)ps;
const Lit* __qs = (const Lit*)qs;
size = ps.size()-1;
for (int i = 0; i < qs.size(); i++){
if (var(__qs[i]) != v){
for (int j = 0; j < ps.size(); j++)
if (var(__ps[j]) == var(__qs[i]))
if (__ps[j] == ~__qs[i])
return false;
else
goto next;
size++;
}
next:;
}
return true;
}
inline void SimpSolver::gatherTouchedClauses()
{
if (n_touched == 0) return;
int i,j;
for (i = j = 0; i < subsumption_queue.size(); i++)
if (ca[subsumption_queue[i]].mark() == 0)
ca[subsumption_queue[i]].mark(2);
for (i = 0; i < touched.size(); i++)
if (touched[i]){
const vec<CRef>& cs = occurs.lookup(i);
for (j = 0; j < cs.size(); j++)
if (ca[cs[j]].mark() == 0){
subsumption_queue.insert(cs[j]);
ca[cs[j]].mark(2);
}
touched[i] = 0;
}
for (i = 0; i < subsumption_queue.size(); i++)
if (ca[subsumption_queue[i]].mark() == 2)
ca[subsumption_queue[i]].mark(0);
n_touched = 0;
}
inline bool SimpSolver::implied(const vec<Lit>& c)
{
assert(decisionLevel() == 0);
trail_lim.push(trail.size());
for (int i = 0; i < c.size(); i++)
if (value(c[i]) == l_True){
cancelUntil(0);
return false;
}else if (value(c[i]) != l_False){
assert(value(c[i]) == l_Undef);
uncheckedEnqueue(~c[i]);
}
bool result = propagate() != CRef_Undef;
cancelUntil(0);
return result;
}
// Backward subsumption + backward subsumption resolution
inline bool SimpSolver::backwardSubsumptionCheck(bool verbose)
{
int cnt = 0;
int subsumed = 0;
int deleted_literals = 0;
assert(decisionLevel() == 0);
while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){
// Empty subsumption queue and return immediately on user-interrupt:
if (asynch_interrupt){
subsumption_queue.clear();
bwdsub_assigns = trail.size();
break; }
// Check top-level assignments by creating a dummy clause and placing it in the queue:
if (subsumption_queue.size() == 0 && bwdsub_assigns < trail.size()){
Lit l = trail[bwdsub_assigns++];
ca[bwdsub_tmpunit][0] = l;
ca[bwdsub_tmpunit].calcAbstraction();
subsumption_queue.insert(bwdsub_tmpunit); }
CRef cr = subsumption_queue.peek(); subsumption_queue.pop();
Clause& c = ca[cr];
if (c.mark()) continue;
if (verbose && verbosity >= 2 && cnt++ % 1000 == 0)
printf("subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals);
assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point.
// Find best variable to scan:
Var best = var(c[0]);
for (int i = 1; i < c.size(); i++)
if (occurs[var(c[i])].size() < occurs[best].size())
best = var(c[i]);
// Search all candidates:
vec<CRef>& _cs = occurs.lookup(best);
CRef* cs = (CRef*)_cs;
for (int j = 0; j < _cs.size(); j++)
if (c.mark())
break;
else if (!ca[cs[j]].mark() && cs[j] != cr && (subsumption_lim == -1 || ca[cs[j]].size() < subsumption_lim)){
Lit l = c.subsumes(ca[cs[j]]);
if (l == lit_Undef)
subsumed++, removeClause(cs[j]);
else if (l != lit_Error){
deleted_literals++;
if (!strengthenClause(cs[j], ~l))
return false;
// Did current candidate get deleted from cs? Then check candidate at index j again:
if (var(l) == best)
j--;
}
}
}
return true;
}
inline bool SimpSolver::asymm(Var v, CRef cr)
{
Clause& c = ca[cr];
assert(decisionLevel() == 0);
if (c.mark() || satisfied(c)) return true;
trail_lim.push(trail.size());
Lit l = lit_Undef;
for (int i = 0; i < c.size(); i++)
if (var(c[i]) != v && value(c[i]) != l_False)
uncheckedEnqueue(~c[i]);
else
l = c[i];
if (propagate() != CRef_Undef){
cancelUntil(0);
asymm_lits++;
if (!strengthenClause(cr, l))
return false;
}else
cancelUntil(0);
return true;
}
inline bool SimpSolver::asymmVar(Var v)
{
assert(use_simplification);
const vec<CRef>& cls = occurs.lookup(v);
if (value(v) != l_Undef || cls.size() == 0)
return true;
for (int i = 0; i < cls.size(); i++)
if (!asymm(v, cls[i]))
return false;
return backwardSubsumptionCheck();
}
static void mkElimClause(vec<uint32_t>& elimclauses, Lit x)
{
elimclauses.push(toInt(x));
elimclauses.push(1);
}
static void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c)
{
int first = elimclauses.size();
int v_pos = -1;
// Copy clause to elimclauses-vector. Remember position where the
// variable 'v' occurs:
for (int i = 0; i < c.size(); i++){
elimclauses.push(toInt(c[i]));
if (var(c[i]) == v)
v_pos = i + first;
}
assert(v_pos != -1);
// Swap the first literal with the 'v' literal, so that the literal
// containing 'v' will occur first in the clause:
uint32_t tmp = elimclauses[v_pos];
elimclauses[v_pos] = elimclauses[first];
elimclauses[first] = tmp;
// Store the length of the clause last:
elimclauses.push(c.size());
}
inline bool SimpSolver::eliminateVar(Var v)
{
assert(!frozen[v]);
assert(!isEliminated(v));
assert(value(v) == l_Undef);
// Split the occurrences into positive and negative:
//
const vec<CRef>& cls = occurs.lookup(v);
vec<CRef> pos, neg;
for (int i = 0; i < cls.size(); i++)
(find(ca[cls[i]], mkLit(v)) ? pos : neg).push(cls[i]);
// Check wether the increase in number of clauses stays within the allowed ('grow'). Moreover, no
// clause must exceed the limit on the maximal clause size (if it is set):
//
int cnt = 0;
int clause_size = 0;
for (int i = 0; i < pos.size(); i++)
for (int j = 0; j < neg.size(); j++)
if (merge(ca[pos[i]], ca[neg[j]], v, clause_size) &&
(++cnt > cls.size() + grow || (clause_lim != -1 && clause_size > clause_lim)))
return true;
// Delete and store old clauses:
eliminated[v] = true;
setDecisionVar(v, false);
eliminated_vars++;
if (pos.size() > neg.size()){
for (int i = 0; i < neg.size(); i++)
mkElimClause(elimclauses, v, ca[neg[i]]);
mkElimClause(elimclauses, mkLit(v));
}else{
for (int i = 0; i < pos.size(); i++)
mkElimClause(elimclauses, v, ca[pos[i]]);
mkElimClause(elimclauses, ~mkLit(v));
}
// Produce clauses in cross product:
vec<Lit>& resolvent = add_tmp;
for (int i = 0; i < pos.size(); i++)
for (int j = 0; j < neg.size(); j++)
if (merge(ca[pos[i]], ca[neg[j]], v, resolvent) && !addClause_(resolvent))
return false;
for (int i = 0; i < cls.size(); i++)
removeClause(cls[i]);
// Free occurs list for this variable:
occurs[v].clear(true);
// Free watchers lists for this variable, if possible:
if (watches[ mkLit(v)].size() == 0) watches[ mkLit(v)].clear(true);
if (watches[~mkLit(v)].size() == 0) watches[~mkLit(v)].clear(true);
return backwardSubsumptionCheck();
}
inline bool SimpSolver::substitute(Var v, Lit x)
{
assert(!frozen[v]);
assert(!isEliminated(v));
assert(value(v) == l_Undef);
if (!ok) return false;
eliminated[v] = true;
setDecisionVar(v, false);
const vec<CRef>& cls = occurs.lookup(v);
vec<Lit>& subst_clause = add_tmp;
for (int i = 0; i < cls.size(); i++){
Clause& c = ca[cls[i]];
subst_clause.clear();
for (int j = 0; j < c.size(); j++){
Lit p = c[j];
subst_clause.push(var(p) == v ? x ^ sign(p) : p);
}
if (!addClause_(subst_clause))
return ok = false;
removeClause(cls[i]);
}
return true;
}
inline void SimpSolver::extendModel()
{
int i, j;
Lit x;
for (i = elimclauses.size()-1; i > 0; i -= j){
for (j = elimclauses[i--]; j > 1; j--, i--)
if (modelValue(toLit(elimclauses[i])) != l_False)
goto next;
x = toLit(elimclauses[i]);
model[var(x)] = lbool(!sign(x));
next:;
}
}
inline bool SimpSolver::eliminate(bool turn_off_elim)
{
if (!simplify())
return false;
else if (!use_simplification)
return true;
// Main simplification loop:
//
int toPerform = 1; clauses.size()<=4800000;
if(!toPerform) {
printf("c Too many clauses... No preprocessing\n");
}
while (toPerform && (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0)){
gatherTouchedClauses();
// printf(" ## (time = %6.2f s) BWD-SUB: queue = %d, trail = %d\n", cpuTime(), subsumption_queue.size(), trail.size() - bwdsub_assigns);
if ((subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()) &&
!backwardSubsumptionCheck(true)){
ok = false; goto cleanup; }
// Empty elim_heap and return immediately on user-interrupt:
if (asynch_interrupt){
assert(bwdsub_assigns == trail.size());
assert(subsumption_queue.size() == 0);
assert(n_touched == 0);
elim_heap.clear();
goto cleanup; }
// printf(" ## (time = %6.2f s) ELIM: vars = %d\n", cpuTime(), elim_heap.size());
for (int cnt = 0; !elim_heap.empty(); cnt++){
Var elim = elim_heap.removeMin();
if (asynch_interrupt) break;
if (isEliminated(elim) || value(elim) != l_Undef) continue;
if (verbosity >= 2 && cnt % 100 == 0)
printf("elimination left: %10d\r", elim_heap.size());
if (use_asymm){
// Temporarily freeze variable. Otherwise, it would immediately end up on the queue again:
bool was_frozen = frozen[elim];
frozen[elim] = true;
if (!asymmVar(elim)){
ok = false; goto cleanup; }
frozen[elim] = was_frozen; }
// At this point, the variable may have been set by assymetric branching, so check it
// again. Also, don't eliminate frozen variables:
if (use_elim && value(elim) == l_Undef && !frozen[elim] && !eliminateVar(elim)){
ok = false; goto cleanup; }
checkGarbage(simp_garbage_frac);
}
assert(subsumption_queue.size() == 0);
}
cleanup:
// If no more simplification is needed, free all simplification-related data structures:
if (turn_off_elim){
touched .clear(true);
occurs .clear(true);
n_occ .clear(true);
elim_heap.clear(true);
subsumption_queue.clear(true);
use_simplification = false;
remove_satisfied = true;
ca.extra_clause_field = false;
// Force full cleanup (this is safe and desirable since it only happens once):
rebuildOrderHeap();
garbageCollect();
}else{
// Cheaper cleanup:
cleanUpClauses(); // TODO: can we make 'cleanUpClauses()' not be linear in the problem size somehow?
checkGarbage();
}
if (verbosity >= 1 && elimclauses.size() > 0)
printf("c | Eliminated clauses: %10.2f Mb |\n",
double(elimclauses.size() * sizeof(uint32_t)) / (1024*1024));
return ok;
}
inline void SimpSolver::cleanUpClauses()
{
occurs.cleanAll();
int i,j;
for (i = j = 0; i < clauses.size(); i++)
if (ca[clauses[i]].mark() == 0)
clauses[j++] = clauses[i];
clauses.shrink(i - j);
}
//=================================================================================================
// Garbage Collection methods:
inline void SimpSolver::relocAll(ClauseAllocator& to)
{
if (!use_simplification) return;
// All occurs lists:
//
for (int i = 0; i < nVars(); i++){
vec<CRef>& cs = occurs[i];
for (int j = 0; j < cs.size(); j++)
ca.reloc(cs[j], to);
}
// Subsumption queue:
//
for (int i = 0; i < subsumption_queue.size(); i++)
ca.reloc(subsumption_queue[i], to);
// Temporary clause:
//
ca.reloc(bwdsub_tmpunit, to);
}
inline void SimpSolver::garbageCollect()
{
// Initialize the next region to a size corresponding to the estimated utilization degree. This
// is not precise but should avoid some unnecessary reallocations for the new region:
ClauseAllocator to(ca.size() - ca.wasted());
cleanUpClauses();
to.extra_clause_field = ca.extra_clause_field; // NOTE: this is important to keep (or lose) the extra fields.
relocAll(to);
Solver::relocAll(to);
if (verbosity >= 2)
printf("| Garbage collection: %12d bytes => %12d bytes |\n",
ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
to.moveTo(ca);
}
}
#undef write_char
#undef var_Undef
#undef DYNAMICNBLEVEL
#undef CONSTANTREMOVECLAUSE
#undef UPDATEVARACTIVITY
#undef RATIOREMOVECLAUSES
#undef LOWER_BOUND_FOR_BLOCKING_RESTART
#undef M
#undef Q
#undef P
#undef B
#undef S
#undef EE
#undef X
| 35.979949
| 243
| 0.556745
|
osamamowafy
|
44cbb1b0cfc3179102cd0bb74edd30370d79a44c
| 383
|
cpp
|
C++
|
Introductory-Problems/repetitions.cpp
|
LazyCoder-1506/CSES-Solutions
|
23430cf2bed7197130a022b7b44a90ee8e13237c
|
[
"MIT"
] | null | null | null |
Introductory-Problems/repetitions.cpp
|
LazyCoder-1506/CSES-Solutions
|
23430cf2bed7197130a022b7b44a90ee8e13237c
|
[
"MIT"
] | null | null | null |
Introductory-Problems/repetitions.cpp
|
LazyCoder-1506/CSES-Solutions
|
23430cf2bed7197130a022b7b44a90ee8e13237c
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define int long long int
void solve() {
string s;
cin >> s;
int n = s.length();
int rep = 0;
int cnt = 1;
for (int i = 1; i < n ; i++) {
if (s[i] == s[i - 1]) {
cnt++;
}
else {
rep = max(rep, cnt);
cnt = 1;
}
}
cout << max(rep, cnt) << "\n";
}
signed main() {
solve();
return 0;
}
| 14.730769
| 32
| 0.456919
|
LazyCoder-1506
|
44cc781daca41bf2f50fe61cfe53117d575f1a82
| 5,069
|
hpp
|
C++
|
falcon/literal/utility.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | 2
|
2018-02-02T14:19:59.000Z
|
2018-05-13T02:48:24.000Z
|
falcon/literal/utility.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | null | null | null |
falcon/literal/utility.hpp
|
jonathanpoelen/falcon
|
5b60a39787eedf15b801d83384193a05efd41a89
|
[
"MIT"
] | null | null | null |
#ifndef FALCON_LITERAL_UTILITY_HPP
#define FALCON_LITERAL_UTILITY_HPP
#include <falcon/literal/detail/literal_support.hpp>
#include <type_traits>
#include <limits>
#include <falcon/type_traits/eval_if.hpp>
#include <falcon/type_traits/use.hpp>
namespace falcon {
namespace literal {
template<typename _CharT, _CharT c>
struct is_digit
: std::integral_constant<bool, (_CharT('0') <= c && c <= _CharT('9'))>
{};
template<std::size_t position>
struct check_false
: std::false_type
{ static const std::size_t last_position = position; };
template<std::size_t position>
struct check_true
: std::true_type
{ static const std::size_t last_position = position; };
template<std::size_t position, typename _CharT, _CharT... chars>
struct __is_integral_base_10;
template<std::size_t position, typename _CharT, _CharT c, _CharT... chars>
struct __is_integral_base_10<position, _CharT, c, chars...>
: if_c<
is_digit<_CharT, c>,
__is_integral_base_10<position + 1, _CharT, chars...>,
check_false<position>
>::type
{ static const std::size_t last_position = position; };
template<std::size_t position, typename _CharT>
struct __is_integral_base_10<position, _CharT>
: check_true<position>
{};
template<typename _CharT, _CharT... chars>
struct is_integral
: __is_integral_base_10<0, _CharT, chars...>
{};
template<typename _CharT>
struct is_integral<_CharT>
: check_false<0>
{};
template<std::size_t position, typename _CharT, _CharT... chars>
struct __is_floating_point_base_10;
template<std::size_t position, typename _CharT, _CharT c, _CharT... chars>
struct __is_floating_point_base_10<position, _CharT, c, chars...>
: eval_if<
c == _CharT('.'),
use<__is_integral_base_10<position + 1, _CharT, chars...>>,
if_c<
is_digit<_CharT, c>,
__is_floating_point_base_10<position + 1, _CharT, chars...>,
check_false<position>
>
>::type
{};
template<std::size_t position, typename _CharT>
struct __is_floating_point_base_10<position, _CharT>
: check_true<position>
{};
template<typename _CharT, _CharT... chars>
struct is_floating_point
: __is_floating_point_base_10<0, _CharT, chars...>
{};
template<typename _CharT>
struct is_floating_point<_CharT>
: check_false<0>
{};
template<typename _CharT, _CharT c>
struct is_floating_point<_CharT, c>
: if_<(c == _CharT('.')), check_false<1>, check_true<1>>::type
{};
template<typename _To, typename _CharT, _CharT... chars>
struct __check_convert_integral
{
static_assert(is_integral<_CharT, chars...>::value, "value is not integral");
};
template<typename _To, unsigned long long ullvalue>
struct __to_value
{
static_assert((ullvalue <= static_cast<unsigned long long>(std::numeric_limits<_To>::max())), "overflow in implicit constant conversion");
static const _To __value = static_cast<_To>(ullvalue);
};
template<typename _To, _To value, typename _CharT, _CharT c>
struct __to_value_base_10
: __to_value<_To, value * 10 + (static_cast<_To>(c) - _To('0'))>
{};
template<typename _To, _To value, typename _CharT, _CharT... chars>
struct __convert_to_integral_base_10;
template<typename _To, _To value, typename _CharT, _CharT c, _CharT... chars>
struct __convert_to_integral_base_10<_To, value, _CharT, c, chars...>
: __convert_to_integral_base_10<
_To,
__to_value_base_10<_To, value, _CharT, c>::__value,
_CharT,
chars...
>
{ static_assert(is_digit<_CharT, c>(), "value is not integral"); };
template<typename _To, _To value, typename _CharT>
struct __convert_to_integral_base_10<_To, value, _CharT>
: std::integral_constant<_To, value>
{};
template<typename _To, typename _CharT, _CharT... chars>
struct __convert_to_integral
: __convert_to_integral_base_10<_To, _To(0), _CharT, chars...>
{ static_assert(sizeof...(chars), "value is empty"); };
template<bool, bool, typename _To, typename _CharT, _CharT... chars>
struct __convert_to;
template<typename _To, typename _CharT, _CharT... chars>
struct __convert_to<true, false, _To, _CharT, chars...>
: __convert_to_integral<_To, _CharT, chars...>
{};
// template<typename _To, typename _CharT, _CharT... chars>
// struct __convert_to<false, true, _To, _CharT, chars...>
// : __convert_to_floating_point<_To, _CharT, chars...>
// {};
template<typename _To, typename _CharT, _CharT... chars>
struct basic_convert_to
: __convert_to<
std::is_integral<_To>::value,
std::is_floating_point<_To>::value,
_To, _CharT, chars...>
{};
template<typename _To, char... chars>
using convert_to = basic_convert_to<_To, char, chars...>;
template<char... chars>
using to_short = convert_to<short, chars...>;
template<char... chars>
using to_int = convert_to<int, chars...>;
template<char... chars>
using to_long = convert_to<long, chars...>;
template<char... chars>
using to_long_long = convert_to<long long, chars...>;
template<char... chars>
using to_ushort = convert_to<unsigned short, chars...>;
template<char... chars>
using to_uint = convert_to<unsigned int, chars...>;
template<char... chars>
using to_ulong = convert_to<unsigned long, chars...>;
template<char... chars>
using to_ulong_long = convert_to<unsigned long long, chars...>;
}
}
#endif
| 27.4
| 139
| 0.744526
|
jonathanpoelen
|
44cd4518f0eff893fb417a964553c796d59ce102
| 7,783
|
cpp
|
C++
|
Cores/Mednafen/mednafen-1.21/src/drivers/Joystick_XInput.cpp
|
werminghoff/Provenance
|
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
|
[
"BSD-3-Clause"
] | 2
|
2021-02-04T22:41:57.000Z
|
2021-03-27T07:28:02.000Z
|
Cores/Mednafen/mednafen-1.21/src/drivers/Joystick_XInput.cpp
|
werminghoff/Provenance
|
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
|
[
"BSD-3-Clause"
] | null | null | null |
Cores/Mednafen/mednafen-1.21/src/drivers/Joystick_XInput.cpp
|
werminghoff/Provenance
|
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
|
[
"BSD-3-Clause"
] | 3
|
2019-02-19T12:55:12.000Z
|
2019-05-30T08:33:23.000Z
|
/******************************************************************************/
/* Mednafen - Multi-system Emulator */
/******************************************************************************/
/* Joystick_XInput.cpp:
** Copyright (C) 2012-2018 Mednafen Team
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// For future reference: XInputGetState(Ex) is reported to have a very high overhead
// when the controller is disconnected.
#include "main.h"
#include "input.h"
#include "Joystick.h"
#include "Joystick_XInput.h"
#include <windows.h>
#include <windowsx.h>
#include <xinput.h>
struct XInputFuncPointers
{
void WINAPI (*p_XInputEnable)(BOOL) = nullptr;
DWORD WINAPI (*p_XInputSetState)(DWORD, XINPUT_VIBRATION*) = nullptr;
DWORD WINAPI (*p_XInputGetState)(DWORD, XINPUT_STATE*) = nullptr; // Pointer to XInputGetState or XInputGetStateEx(if available).
DWORD WINAPI (*p_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*) = nullptr;
};
class Joystick_XInput : public Joystick
{
public:
Joystick_XInput(unsigned index, const XINPUT_CAPABILITIES &caps_in, const XInputFuncPointers* xfps_in);
~Joystick_XInput();
virtual void SetRumble(uint8 weak_intensity, uint8 strong_intensity);
virtual bool IsAxisButton(unsigned axis);
void UpdateInternal(void);
private:
const unsigned joy_index;
const XINPUT_CAPABILITIES caps;
const XInputFuncPointers *xfps;
};
Joystick_XInput::Joystick_XInput(unsigned index, const XINPUT_CAPABILITIES &caps_in, const XInputFuncPointers* xfps_in) : joy_index(index), caps(caps_in), xfps(xfps_in)
{
num_buttons = sizeof(((XINPUT_GAMEPAD*)0)->wButtons) * 8;
num_axes = 6;
num_rel_axes = 0;
button_state.resize(num_buttons);
axis_state.resize(num_axes);
id_09x = (caps.Type << 24) | (caps.SubType << 16); // Don't include the XInput index in the id, it'll just cause problems, especially when multiple different subtypes of controllers are connected. | (index << 8);
// Leave first 8 bytes as 0 to reduce probability of collisions with DirectInput GUIDs?
MDFN_en64msb(&id[0], 0);
id[8] = caps.Type;
id[9] = caps.SubType;
MDFN_en16msb(&id[10], caps.Flags);
MDFN_en16msb(&id[12], caps.Gamepad.wButtons);
MDFN_en16msb(&id[14], 0);
const char* name_cs = "XInput Unknown Controller";
if(caps.Type == XINPUT_DEVTYPE_GAMEPAD)
{
switch(caps.SubType)
{
default: break;
case XINPUT_DEVSUBTYPE_GAMEPAD: name_cs = "XInput Gamepad"; break;
case XINPUT_DEVSUBTYPE_WHEEL: name_cs = "XInput Wheel"; break;
case XINPUT_DEVSUBTYPE_ARCADE_STICK: name_cs = "XInput Arcade Stick"; break;
#ifdef XINPUT_DEVSUBTYPE_FLIGHT_STICK
case XINPUT_DEVSUBTYPE_FLIGHT_STICK: name_cs = "XInput Flight Stick"; break;
#endif
case XINPUT_DEVSUBTYPE_DANCE_PAD: name_cs = "XInput Dance Pad"; break;
#ifdef XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE
case XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE:
#endif
#ifdef XINPUT_DEVSUBTYPE_GUITAR_BASS
case XINPUT_DEVSUBTYPE_GUITAR_BASS:
#endif
case XINPUT_DEVSUBTYPE_GUITAR: name_cs = "XInput Guitar"; break;
case XINPUT_DEVSUBTYPE_DRUM_KIT: name_cs = "XInput Drum Kit"; break;
#ifdef XINPUT_DEVSUBTYPE_ARCADE_PAD
case XINPUT_DEVSUBTYPE_ARCADE_PAD: name_cs = "XInput Arcade Pad"; break;
#endif
}
}
name = name_cs;
}
Joystick_XInput::~Joystick_XInput()
{
}
bool Joystick_XInput::IsAxisButton(unsigned axis)
{
if(axis >= 4)
return(true);
return(false);
}
void Joystick_XInput::UpdateInternal(void)
{
XINPUT_STATE joy_state;
memset(&joy_state, 0, sizeof(XINPUT_STATE));
xfps->p_XInputGetState(joy_index, &joy_state);
for(unsigned b = 0; b < num_buttons; b++)
button_state[b] = (joy_state.Gamepad.wButtons >> b) & 1;
axis_state[0] = std::max<int>(-32767, joy_state.Gamepad.sThumbLX);
axis_state[1] = std::max<int>(-32767, joy_state.Gamepad.sThumbLY);
axis_state[2] = std::max<int>(-32767, joy_state.Gamepad.sThumbRX);
axis_state[3] = std::max<int>(-32767, joy_state.Gamepad.sThumbRY);
axis_state[4] = (((unsigned)joy_state.Gamepad.bLeftTrigger * 32767) + 127) / 255;
axis_state[5] = (((unsigned)joy_state.Gamepad.bRightTrigger * 32767) + 127) / 255;
}
void Joystick_XInput::SetRumble(uint8 weak_intensity, uint8 strong_intensity)
{
XINPUT_VIBRATION vib;
memset(&vib, 0, sizeof(XINPUT_VIBRATION));
vib.wLeftMotorSpeed = (((unsigned int)strong_intensity * 65535) + 127) / 255;
vib.wRightMotorSpeed = (((unsigned int)weak_intensity * 65535) + 127) / 255;
xfps->p_XInputSetState(joy_index, &vib);
}
class JoystickDriver_XInput : public JoystickDriver
{
public:
JoystickDriver_XInput();
virtual ~JoystickDriver_XInput();
virtual unsigned NumJoysticks(); // Cached internally on JoystickDriver instantiation.
virtual Joystick *GetJoystick(unsigned index);
virtual void UpdateJoysticks(void);
private:
Joystick_XInput *joys[XUSER_MAX_COUNT];
unsigned joy_count = 0;
HMODULE dll_handle = nullptr;
XInputFuncPointers xfps;
};
template<typename T>
bool GetXIPA(HMODULE dll_handle, T& pf, const char *name)
{
pf = (T)GetProcAddress(dll_handle, name);
return(pf != NULL);
}
JoystickDriver_XInput::JoystickDriver_XInput()
{
if((dll_handle = LoadLibrary("xinput1_3.dll")) == NULL)
{
if((dll_handle = LoadLibrary("xinput1_4.dll")) == NULL)
{
if((dll_handle = LoadLibrary("xinput9_1_0.dll")) == NULL)
{
return;
}
}
}
// 9.1.0 supposedly lacks XInputEnable()
xfps.p_XInputEnable = NULL;
GetXIPA(dll_handle, xfps.p_XInputEnable, "XInputEnable");
if(!GetXIPA(dll_handle, xfps.p_XInputSetState, "XInputSetState") ||
(!GetXIPA(dll_handle, xfps.p_XInputGetState, (const char *)100/*"XInputGetStateEx"*/) && !GetXIPA(dll_handle, xfps.p_XInputGetState, "XInputGetState")) ||
!GetXIPA(dll_handle, xfps.p_XInputGetCapabilities, "XInputGetCapabilities"))
{
FreeLibrary(dll_handle);
return;
}
if(xfps.p_XInputEnable)
xfps.p_XInputEnable(TRUE);
for(unsigned i = 0; i < XUSER_MAX_COUNT; i++)
{
joys[i] = NULL;
try
{
XINPUT_CAPABILITIES caps;
if(xfps.p_XInputGetCapabilities(i, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS)
{
joys[joy_count] = new Joystick_XInput(i, caps, &xfps);
joy_count++; // joys[joy_count++] would not be exception-safe.
}
}
catch(std::exception &e)
{
MDFND_OutputNotice(MDFN_NOTICE_ERROR, e.what());
}
}
}
JoystickDriver_XInput::~JoystickDriver_XInput()
{
if(xfps.p_XInputEnable)
xfps.p_XInputEnable(FALSE);
for(unsigned i = 0; i < joy_count; i++)
{
if(joys[i])
{
delete joys[i];
joys[i] = NULL;
}
}
joy_count = 0;
if(dll_handle != NULL)
{
FreeLibrary(dll_handle);
dll_handle = NULL;
}
}
unsigned JoystickDriver_XInput::NumJoysticks(void)
{
return joy_count;
}
Joystick *JoystickDriver_XInput::GetJoystick(unsigned index)
{
return joys[index];
}
void JoystickDriver_XInput::UpdateJoysticks(void)
{
for(unsigned i = 0; i < joy_count; i++)
joys[i]->UpdateInternal();
}
JoystickDriver *JoystickDriver_XInput_New(void)
{
JoystickDriver_XInput* jdxi = new JoystickDriver_XInput();
if(!jdxi->NumJoysticks())
{
delete jdxi;
jdxi = NULL;
}
return(jdxi);
}
| 27.996403
| 213
| 0.714891
|
werminghoff
|
44cddaff027d71c261189ccf4f9a372801ca72b3
| 107,053
|
cpp
|
C++
|
src/aligner.cpp
|
lnceballosz/vg
|
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
|
[
"MIT"
] | null | null | null |
src/aligner.cpp
|
lnceballosz/vg
|
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
|
[
"MIT"
] | null | null | null |
src/aligner.cpp
|
lnceballosz/vg
|
82d8ba2f38299525c0b0a6b19dcb785d2c439cfa
|
[
"MIT"
] | null | null | null |
// SPDX-FileCopyrightText: 2014 Erik Garrison
//
// SPDX-License-Identifier: MIT
#include "aligner.hpp"
#include "hash_map.hpp"
//#define debug_print_score_matrices
using namespace vg;
using namespace std;
using namespace vg::io;
static const double quality_scale_factor = 10.0 / log(10.0);
static const double exp_overflow_limit = log(std::numeric_limits<double>::max());
GSSWAligner::~GSSWAligner(void) {
free(nt_table);
free(score_matrix);
}
GSSWAligner::GSSWAligner(const int8_t* _score_matrix,
int8_t _gap_open,
int8_t _gap_extension,
int8_t _full_length_bonus,
double _gc_content) : deletion_aligner(_gap_open, _gap_extension) {
log_base = recover_log_base(_score_matrix, _gc_content, 1e-12);
// TODO: now that everything is in terms of score matrices, having match/mismatch is a bit
// misleading, but a fair amount of code depends on them
match = _score_matrix[0];
mismatch = -_score_matrix[1];
gap_open = _gap_open;
gap_extension = _gap_extension;
full_length_bonus = _full_length_bonus;
// table to translate chars to their integer value
nt_table = gssw_create_nt_table();
}
gssw_graph* GSSWAligner::create_gssw_graph(const HandleGraph& g) const {
vector<handle_t> topological_order = handlealgs::lazier_topological_order(&g);
gssw_graph* graph = gssw_graph_create(g.get_node_count());
unordered_map<int64_t, gssw_node*> nodes;
// compute the topological order
for (const handle_t& handle : topological_order) {
auto cleaned_seq = nonATGCNtoN(g.get_sequence(handle));
gssw_node* node = gssw_node_create(nullptr, // TODO: the ID should be enough, don't need Node* too
g.get_id(handle),
cleaned_seq.c_str(),
nt_table,
score_matrix); // TODO: this arg isn't used, could edit
// in gssw
nodes[node->id] = node;
gssw_graph_add_node(graph, node);
}
g.for_each_edge([&](const edge_t& edge) {
if(!g.get_is_reverse(edge.first) && !g.get_is_reverse(edge.second)) {
// This is a normal end to start edge.
gssw_nodes_add_edge(nodes[g.get_id(edge.first)], nodes[g.get_id(edge.second)]);
}
else if (g.get_is_reverse(edge.first) && g.get_is_reverse(edge.second)) {
// This is a start to end edge, but isn't reversing and can be converted to a normal end to start edge.
// Flip the start and end
gssw_nodes_add_edge(nodes[g.get_id(edge.second)], nodes[g.get_id(edge.first)]);
}
else {
// TODO: It's a reversing edge, which gssw doesn't support yet. What
// we should really do is do a topological sort to break cycles, and
// then flip everything at the lower-rank end of this edge around,
// so we don't have to deal with its reversing-ness. But for now we
// just die so we don't get nonsense into gssw.
#pragma omp critical
{
// We need the critical section so we don't throw uncaught
// exceptions in multiple threads at once, leading to C++ trying
// to run termiante in parallel. This doesn't make it safe, just
// slightly safer.
cerr << "Can't gssw over reversing edge " << g.get_id(edge.first) << (g.get_is_reverse(edge.first) ? "-" : "+") << " -> " << g.get_id(edge.second) << (g.get_is_reverse(edge.second) ? "-" : "+") << endl;
// TODO: there's no safe way to kill the program without a way
// to signal the master to do it, via a shared variable in the
// clause that made us parallel.
}
exit(1);
}
return true;
});
return graph;
}
unordered_set<vg::id_t> GSSWAligner::identify_pinning_points(const HandleGraph& graph) const {
unordered_set<vg::id_t> return_val;
// start at the sink nodes
vector<handle_t> sinks = handlealgs::tail_nodes(&graph);
// walk backwards to find non-empty nodes if necessary
for (const handle_t& handle : sinks) {
vector<handle_t> stack(1, handle);
while (!stack.empty()) {
handle_t here = stack.back();
stack.pop_back();
if (graph.get_length(here) > 0) {
return_val.insert(graph.get_id(here));
}
else {
graph.follow_edges(here, true, [&](const handle_t& prev) {
// TODO: technically this won't filter out all redundant walks, but it should
// handle all cases we're practically interested in and it doesn't require a
// second set object
if (!return_val.count(graph.get_id(prev))) {
stack.push_back(prev);
}
});
}
}
}
return return_val;
}
void GSSWAligner::gssw_mapping_to_alignment(gssw_graph* graph,
gssw_graph_mapping* gm,
Alignment& alignment,
bool pinned,
bool pin_left) const {
alignment.clear_path();
alignment.set_score(gm->score);
alignment.set_query_position(0);
Path* path = alignment.mutable_path();
//alignment.set_cigar(graph_cigar(gm));
gssw_graph_cigar* gc = &gm->cigar;
gssw_node_cigar* ncs = gc->elements;
//cerr << "gm->position " << gm->position << endl;
string& to_seq = *alignment.mutable_sequence();
//cerr << "-------------" << endl;
#ifdef debug_print_score_matrices
gssw_graph_print_score_matrices(graph, to_seq.c_str(), to_seq.size(), stderr);
#endif
int to_pos = 0;
int from_pos = gm->position;
for (int i = 0; i < gc->length; ++i) {
// check that the current alignment has a non-zero length
gssw_cigar* c = ncs[i].cigar;
int l = c->length;
if (l == 0) continue;
gssw_cigar_element* e = c->elements;
gssw_node* node = ncs[i].node;
Mapping* mapping = path->add_mapping();
if (i > 0) {
// reset for each node after the first
from_pos = 0;
}
mapping->mutable_position()->set_node_id(node->id);
mapping->mutable_position()->set_offset(from_pos);
mapping->set_rank(path->mapping_size());
//cerr << node->id << ":" << endl;
for (int j=0; j < l; ++j, ++e) {
int32_t length = e->length;
//cerr << e->length << e->type << endl;
Edit* edit;
switch (e->type) {
case 'M':
case 'X':
case 'N': {
//cerr << "j = " << j << ", type = " << e->type << endl;
// do the sequences match?
// emit a stream of "SNPs" and matches
int h = from_pos;
int last_start = from_pos;
int k = to_pos;
for ( ; h < from_pos + length; ++h, ++k) {
//cerr << h << ":" << k << " " << node->seq[h] << " " << to_seq[k] << endl;
if (node->seq[h] != to_seq[k]) {
// emit the last "match" region
if (h - last_start > 0) {
edit = mapping->add_edit();
edit->set_from_length(h-last_start);
edit->set_to_length(h-last_start);
}
// set up the SNP
edit = mapping->add_edit();
edit->set_from_length(1);
edit->set_to_length(1);
edit->set_sequence(to_seq.substr(k,1));
last_start = h+1;
}
}
// handles the match at the end or the case of no SNP
if (h - last_start > 0) {
edit = mapping->add_edit();
edit->set_from_length(h-last_start);
edit->set_to_length(h-last_start);
}
to_pos += length;
from_pos += length;
} break;
case 'D':
edit = mapping->add_edit();
edit->set_from_length(length);
edit->set_to_length(0);
from_pos += length;
break;
case 'I':
edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(length);
edit->set_sequence(to_seq.substr(to_pos, length));
to_pos += length;
break;
case 'S':
// note that soft clips and insertions are semantically equivalent
// and can only be differentiated by their position in the read
// with soft clips coming at the start or end
edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(length);
edit->set_sequence(to_seq.substr(to_pos, length));
to_pos += length;
break;
default:
cerr << "error:[Aligner::gssw_mapping_to_alignment] "
<< "unsupported cigar op type " << e->type << endl;
exit(1);
break;
}
}
}
// compute and set identity
alignment.set_identity(identity(alignment.path()));
}
void GSSWAligner::unreverse_graph(gssw_graph* graph) const {
// this is only for getting correct reference-relative edits, so we can get away with only
// reversing the sequences and not paying attention to the edges
for (size_t i = 0; i < graph->size; i++) {
gssw_node* node = graph->nodes[i];
for (int j = 0, stop = node->len / 2; j < stop; j++) {
std::swap(node->seq[j], node->seq[node->len - j - 1]);
}
}
}
void GSSWAligner::unreverse_graph_mapping(gssw_graph_mapping* gm) const {
gssw_graph_cigar* graph_cigar = &(gm->cigar);
gssw_node_cigar* node_cigars = graph_cigar->elements;
// reverse the order of the node cigars
int32_t num_switching_nodes = graph_cigar->length / 2;
int32_t last_idx = graph_cigar->length - 1;
for (int32_t i = 0; i < num_switching_nodes; i++) {
std::swap(node_cigars[i], node_cigars[last_idx - i]);
}
// reverse the actual cigar string for each node cigar
for (int32_t i = 0; i < graph_cigar->length; i++) {
gssw_cigar* node_cigar = node_cigars[i].cigar;
gssw_cigar_element* elements = node_cigar->elements;
int32_t num_switching_elements = node_cigar->length / 2;
last_idx = node_cigar->length - 1;
for (int32_t j = 0; j < num_switching_elements; j++) {
std::swap(elements[j], elements[last_idx - j]);
}
}
// compute the position in the first node
if (graph_cigar->length > 0) {
gssw_cigar_element* first_node_elements = node_cigars[0].cigar->elements;
int32_t num_first_node_elements = node_cigars[0].cigar->length;
uint32_t num_ref_aligned = 0; // the number of characters on the node sequence that are aligned
for (int32_t i = 0; i < num_first_node_elements; i++) {
switch (first_node_elements[i].type) {
case 'M':
case 'X':
case 'N':
case 'D':
num_ref_aligned += first_node_elements[i].length;
break;
}
}
gm->position = node_cigars[0].node->len - num_ref_aligned - (graph_cigar->length == 1 ? gm->position : 0);
}
else {
gm->position = 0;
}
}
string GSSWAligner::graph_cigar(gssw_graph_mapping* gm) const {
stringstream s;
gssw_graph_cigar* gc = &gm->cigar;
gssw_node_cigar* nc = gc->elements;
int to_pos = 0;
int from_pos = gm->position;
//string& to_seq = *alignment.mutable_sequence();
s << from_pos << '@';
for (int i = 0; i < gc->length; ++i, ++nc) {
if (i > 0) from_pos = 0; // reset for each node after the first
Node* from_node = (Node*) nc->node->data;
s << from_node->id() << ':';
gssw_cigar* c = nc->cigar;
int l = c->length;
gssw_cigar_element* e = c->elements;
for (int j=0; j < l; ++j, ++e) {
s << e->length << e->type;
}
if (i + 1 < gc->length) {
s << ",";
}
}
return s.str();
}
double GSSWAligner::recover_log_base(const int8_t* score_matrix, double gc_content, double tol) const {
// convert gc content into base-wise frequencies
double* nt_freqs = (double*) malloc(sizeof(double) * 4);
nt_freqs[0] = 0.5 * (1 - gc_content);
nt_freqs[1] = 0.5 * gc_content;
nt_freqs[2] = 0.5 * gc_content;
nt_freqs[3] = 0.5 * (1 - gc_content);
if (!verify_valid_log_odds_score_matrix(score_matrix, nt_freqs)) {
cerr << "error:[Aligner] Score matrix is invalid. Must have a negative expected score against random sequence." << endl;
exit(1);
}
// searching for a positive value (because it's a base of a logarithm)
double lower_bound;
double upper_bound;
// arbitrary starting point greater than zero
double lambda = 1.0;
// search for a window containing lambda where total probability is 1
double partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs);
if (partition < 1.0) {
lower_bound = lambda;
while (partition <= 1.0) {
lower_bound = lambda;
lambda *= 2.0;
partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs);
}
upper_bound = lambda;
}
else {
upper_bound = lambda;
while (partition >= 1.0) {
upper_bound = lambda;
lambda /= 2.0;
partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs);
}
lower_bound = lambda;
}
// bisect to find a log base where total probability is 1
while (upper_bound / lower_bound - 1.0 > tol) {
lambda = 0.5 * (lower_bound + upper_bound);
if (alignment_score_partition_function(lambda, score_matrix, nt_freqs) < 1.0) {
lower_bound = lambda;
}
else {
upper_bound = lambda;
}
}
free(nt_freqs);
return 0.5 * (lower_bound + upper_bound);
}
bool GSSWAligner::verify_valid_log_odds_score_matrix(const int8_t* score_matrix, const double* nt_freqs) const {
bool contains_positive_score = false;
for (int i = 0; i < 16; i++) {
if (score_matrix[i] > 0) {
contains_positive_score = 1;
break;
}
}
if (!contains_positive_score) {
return false;
}
double expected_score = 0.0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
expected_score += nt_freqs[i] * nt_freqs[j] * score_matrix[i * 4 + j];
}
}
return expected_score < 0.0;
}
double GSSWAligner::alignment_score_partition_function(double lambda, const int8_t* score_matrix,
const double* nt_freqs) const {
double partition = 0.0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
partition += nt_freqs[i] * nt_freqs[j] * exp(lambda * score_matrix[i * 4 + j]);
}
}
if (isnan(partition)) {
cerr << "error:[Aligner] overflow error in log-odds base recovery subroutine." << endl;
exit(1);
}
return partition;
}
int32_t GSSWAligner::score_gap(size_t gap_length) const {
return gap_length ? -gap_open - (gap_length - 1) * gap_extension : 0;
}
double GSSWAligner::maximum_mapping_quality_exact(const vector<double>& scaled_scores, size_t* max_idx_out,
const vector<double>* multiplicities) {
// work in log transformed values to avoid risk of overflow
double log_sum_exp = numeric_limits<double>::lowest();
double max_score = numeric_limits<double>::lowest();
// go in reverse order because this has fewer numerical problems when the scores are sorted (as usual)
for (int64_t i = scaled_scores.size() - 1; i >= 0; i--) {
// get the value of one copy of the score and check if it's the max
double score = scaled_scores.at(i);
if (score >= max_score) {
// Since we are going in reverse order, make sure to break ties in favor of the earlier item.
*max_idx_out = i;
max_score = score;
}
// add all copies of the score
if (multiplicities && multiplicities->at(i) > 1.0) {
score += log(multiplicities->at(i));
}
// accumulate the sum of all score
log_sum_exp = add_log(log_sum_exp, score);
}
// if necessary, assume a null alignment of 0.0 for comparison since this is local
if (scaled_scores.size() == 1) {
if (multiplicities && multiplicities->at(0) <= 1.0) {
log_sum_exp = add_log(log_sum_exp, 0.0);
}
else if (!multiplicities) {
log_sum_exp = add_log(log_sum_exp, 0.0);
}
}
double direct_mapq = -quality_scale_factor * subtract_log(0.0, max_score - log_sum_exp);
return std::isinf(direct_mapq) ? (double) numeric_limits<int32_t>::max() : direct_mapq;
}
// TODO: this algorithm has numerical problems that would be difficult to solve without increasing the
// time complexity: adding the probability of the maximum likelihood tends to erase the contribution
// of the other terms so that when you subtract them off you get scores of 0 or infinity
//vector<double> Aligner::all_mapping_qualities_exact(vector<double>& scaled_scores) {
//
// double max_score = *max_element(scaled_scores.begin(), scaled_scores.end());
// size_t size = scaled_scores.size();
//
// vector<double> mapping_qualities(size);
//
// if (max_score * size < exp_overflow_limit) {
// // no risk of double overflow, sum exp directly (half as many transcendental function evals)
// vector<double> exp_scaled_scores(size);
// for (size_t i = 0; i < size; i++) {
// exp_scaled_scores[i] = exp(scaled_scores[i]);
// }
// double denom = std::accumulate(exp_scaled_scores.begin(), exp_scaled_scores.end(), 0.0);
// for (size_t i = 0; i < size; i++) {
// mapping_qualities[i] = -10.0 * log10((denom - exp_scaled_scores[i]) / denom);
// }
// }
// else {
// // work in log transformed valued to avoid risk of overflow
// double log_sum_exp = scaled_scores[0];
// for (size_t i = 1; i < size; i++) {
// log_sum_exp = add_log(log_sum_exp, scaled_scores[i]);
// }
// for (size_t i = 0; i < size; i++) {
// mapping_qualities[i] = -10.0 * log10(1.0 - exp(scaled_scores[i] - log_sum_exp));
// }
// }
// return mapping_qualities;
//}
double GSSWAligner::maximum_mapping_quality_approx(const vector<double>& scaled_scores, size_t* max_idx_out,
const vector<double>* multiplicities) {
assert(!scaled_scores.empty());
// determine the maximum score and the count of the next highest score
double max_score = scaled_scores.at(0);
size_t max_idx = 0;
// we start with the possibility of a null score of 0.0
double next_score = 0.0;
double next_count = 1.0;
if (multiplicities) {
if (multiplicities->at(0) > 1.0) {
// there are extra copies of this one, so we'll init with those
next_score = max_score;
next_count = multiplicities->at(0) - 1.0;
}
}
for (int32_t i = 1; i < scaled_scores.size(); ++i) {
double score = scaled_scores.at(i);
if (score > max_score) {
if (multiplicities && multiplicities->at(i) > 1.0) {
// there are extra counts of the new highest score due to multiplicity
next_score = score;
next_count = multiplicities->at(i) - 1.0;
}
else if (next_score == max_score) {
// the next highest was the same score as the old max, so we can
// add its count back in
next_count += 1.0;
}
else {
// the old max score is now the second highest
next_score = max_score;
next_count = multiplicities ? multiplicities->at(max_idx) : 1.0;
}
max_score = score;
max_idx = i;
}
else if (score > next_score) {
// the new score is the second highest
next_score = score;
next_count = multiplicities ? multiplicities->at(i) : 1.0;
}
else if (score == next_score) {
// the new score ties the second highest, so we combine their counts
next_count += multiplicities ? multiplicities->at(i) : 1.0;
}
}
// record the index of the highest score
*max_idx_out = max_idx;
return max(0.0, quality_scale_factor * (max_score - next_score - (next_count > 1.0 ? log(next_count) : 0.0)));
}
double GSSWAligner::group_mapping_quality_exact(const vector<double>& scaled_scores, const vector<size_t>& group,
const vector<double>* multiplicities) const {
// work in log transformed values to avoid risk of overflow
double total_log_sum_exp = numeric_limits<double>::lowest();
double non_group_log_sum_exp = numeric_limits<double>::lowest();
// go in reverse order because this has fewer numerical problems when the scores are sorted (as usual)
int64_t group_idx = group.size() - 1;
for (int64_t i = scaled_scores.size() - 1; i >= 0; i--) {
// the score of one alignment
double score = scaled_scores.at(i);
// the score all the multiples of this score combined
double multiple_score = score;
if (multiplicities && multiplicities->at(i) > 1.0) {
multiple_score += log(multiplicities->at(i));
}
total_log_sum_exp = add_log(total_log_sum_exp, multiple_score);
if (group_idx >= 0 && i == group[group_idx]) {
// this is the next index in the group
group_idx--;
if (multiplicities && multiplicities->at(i) > 1.0) {
// there's some remaining multiples of this score that don't get added into the group
non_group_log_sum_exp = add_log(non_group_log_sum_exp,
score + log(multiplicities->at(i) - 1.0));
}
}
else {
// this index is not part of the group
non_group_log_sum_exp = add_log(non_group_log_sum_exp, multiple_score);
}
}
if (scaled_scores.size() == 1) {
if (multiplicities && multiplicities->at(0) <= 1.0) {
// assume a null alignment of 0.0 for comparison since this is local
non_group_log_sum_exp = add_log(non_group_log_sum_exp, 0.0);
total_log_sum_exp = add_log(total_log_sum_exp, 0.0);
}
else if (!multiplicities) {
//TODO: repetitive, do I need to be this careful to not deref a null?
// assume a null alignment of 0.0 for comparison since this is local
non_group_log_sum_exp = add_log(non_group_log_sum_exp, 0.0);
total_log_sum_exp = add_log(total_log_sum_exp, 0.0);
}
}
double direct_mapq = quality_scale_factor * (total_log_sum_exp - non_group_log_sum_exp);
return (std::isinf(direct_mapq) || direct_mapq > numeric_limits<int32_t>::max()) ?
(double) numeric_limits<int32_t>::max() : direct_mapq;
}
void GSSWAligner::compute_mapping_quality(vector<Alignment>& alignments,
int max_mapping_quality,
bool fast_approximation,
double cluster_mq,
bool use_cluster_mq,
int overlap_count,
double mq_estimate,
double maybe_mq_threshold,
double identity_weight) const {
assert(log_base > 0.0);
if (alignments.empty()) {
return;
}
vector<double> scaled_scores(alignments.size());
for (size_t i = 0; i < alignments.size(); i++) {
scaled_scores[i] = log_base * alignments[i].score();
}
double mapping_quality;
size_t max_idx;
if (!fast_approximation) {
mapping_quality = maximum_mapping_quality_exact(scaled_scores, &max_idx);
}
else {
mapping_quality = maximum_mapping_quality_approx(scaled_scores, &max_idx);
}
if (use_cluster_mq) {
mapping_quality = prob_to_phred(sqrt(phred_to_prob(cluster_mq + mapping_quality)));
}
if (overlap_count) {
mapping_quality -= quality_scale_factor * log(overlap_count);
}
auto& max_aln = alignments.at(max_idx);
int l = max(alignment_to_length(max_aln), alignment_from_length(max_aln));
double identity = 1. - (double)(l * match - max_aln.score()) / (match + mismatch) / l;
mapping_quality /= 2;
mapping_quality *= pow(identity, identity_weight);
if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality) {
mapping_quality = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality)));
}
if (mapping_quality > max_mapping_quality) {
mapping_quality = max_mapping_quality;
}
if (alignments[max_idx].score() == 0) {
mapping_quality = 0;
}
alignments[max_idx].set_mapping_quality(max(0, (int32_t) round(mapping_quality)));
for (int i = 1; i < alignments.size(); ++i) {
alignments[0].add_secondary_score(alignments[i].score());
}
}
int32_t GSSWAligner::compute_mapping_quality(const vector<double>& scores, bool fast_approximation,
const vector<double>* multiplicities) const {
vector<double> scaled_scores(scores.size());
for (size_t i = 0; i < scores.size(); i++) {
scaled_scores[i] = log_base * scores[i];
}
size_t idx;
return (int32_t) (fast_approximation ? maximum_mapping_quality_approx(scaled_scores, &idx, multiplicities)
: maximum_mapping_quality_exact(scaled_scores, &idx, multiplicities));
}
int32_t GSSWAligner::compute_group_mapping_quality(const vector<double>& scores, const vector<size_t>& group,
const vector<double>* multiplicities) const {
// make a non-const local version in case we need to sort it
vector<size_t> non_const_group;
const vector<size_t>* grp_ptr = &group;
// ensure that group is in sorted order as following function expects
if (!is_sorted(group.begin(), group.end())) {
non_const_group = group;
sort(non_const_group.begin(), non_const_group.end());
grp_ptr = &non_const_group;
}
vector<double> scaled_scores(scores.size(), 0.0);
for (size_t i = 0; i < scores.size(); i++) {
scaled_scores[i] = log_base * scores[i];
}
return group_mapping_quality_exact(scaled_scores, *grp_ptr, multiplicities);
}
void GSSWAligner::compute_paired_mapping_quality(pair<vector<Alignment>, vector<Alignment>>& alignment_pairs,
const vector<double>& frag_weights,
int max_mapping_quality1,
int max_mapping_quality2,
bool fast_approximation,
double cluster_mq,
bool use_cluster_mq,
int overlap_count1,
int overlap_count2,
double mq_estimate1,
double mq_estimate2,
double maybe_mq_threshold,
double identity_weight) const {
assert(log_base > 0.0);
size_t size = min(alignment_pairs.first.size(),
alignment_pairs.second.size());
if (size == 0) {
return;
}
vector<double> scaled_scores(size);
for (size_t i = 0; i < size; i++) {
auto& aln1 = alignment_pairs.first[i];
auto& aln2 = alignment_pairs.second[i];
scaled_scores[i] = log_base * (aln1.score() + aln2.score());
// + frag_weights[i]);
// ^^^ we could also incorporate the fragment weights, but this does not seem to help performance in the current form
}
size_t max_idx;
double mapping_quality;
if (!fast_approximation) {
mapping_quality = maximum_mapping_quality_exact(scaled_scores, &max_idx);
}
else {
mapping_quality = maximum_mapping_quality_approx(scaled_scores, &max_idx);
}
if (use_cluster_mq) {
mapping_quality = prob_to_phred(sqrt(phred_to_prob(cluster_mq + mapping_quality)));
}
double mapping_quality1 = mapping_quality;
double mapping_quality2 = mapping_quality;
if (overlap_count1) {
mapping_quality1 -= quality_scale_factor * log(overlap_count1);
}
if (overlap_count2) {
mapping_quality2 -= quality_scale_factor * log(overlap_count2);
}
auto& max_aln1 = alignment_pairs.first.at(max_idx);
int len1 = max(alignment_to_length(max_aln1), alignment_from_length(max_aln1));
double identity1 = 1. - (double)(len1 * match - max_aln1.score()) / (match + mismatch) / len1;
auto& max_aln2 = alignment_pairs.second.at(max_idx);
int len2 = max(alignment_to_length(max_aln2), alignment_from_length(max_aln2));
double identity2 = 1. - (double)(len2 * match - max_aln2.score()) / (match + mismatch) / len2;
mapping_quality1 /= 2;
mapping_quality2 /= 2;
mapping_quality1 *= pow(identity1, identity_weight);
mapping_quality2 *= pow(identity2, identity_weight);
double mq_estimate = min(mq_estimate1, mq_estimate2);
if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality1) {
mapping_quality1 = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality1)));
}
if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality2) {
mapping_quality2 = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality2)));
}
if (mapping_quality1 > max_mapping_quality1) {
mapping_quality1 = max_mapping_quality1;
}
if (mapping_quality2 > max_mapping_quality2) {
mapping_quality2 = max_mapping_quality2;
}
if (alignment_pairs.first[max_idx].score() == 0) {
mapping_quality1 = 0;
}
if (alignment_pairs.second[max_idx].score() == 0) {
mapping_quality2 = 0;
}
mapping_quality = max(0, (int32_t)round(min(mapping_quality1, mapping_quality2)));
alignment_pairs.first[max_idx].set_mapping_quality(mapping_quality);
alignment_pairs.second[max_idx].set_mapping_quality(mapping_quality);
for (int i = 1; i < alignment_pairs.first.size(); ++i) {
alignment_pairs.first[0].add_secondary_score(alignment_pairs.first[i].score());
}
for (int i = 1; i < alignment_pairs.second.size(); ++i) {
alignment_pairs.second[0].add_secondary_score(alignment_pairs.second[i].score());
}
}
double GSSWAligner::mapping_quality_score_diff(double mapping_quality) const {
return mapping_quality / (quality_scale_factor * log_base);
}
double GSSWAligner::estimate_next_best_score(int length, double min_diffs) const {
return ((length - min_diffs) * match - min_diffs * mismatch);
}
double GSSWAligner::max_possible_mapping_quality(int length) const {
double max_score = log_base * length * match;
vector<double> v = { max_score };
size_t max_idx;
return maximum_mapping_quality_approx(v, &max_idx);
}
double GSSWAligner::estimate_max_possible_mapping_quality(int length, double min_diffs, double next_min_diffs) const {
double max_score = log_base * ((length - min_diffs) * match - min_diffs * mismatch);
double next_max_score = log_base * ((length - next_min_diffs) * match - next_min_diffs * mismatch);
vector<double> v = { max_score, next_max_score };
size_t max_idx;
return maximum_mapping_quality_approx(v, &max_idx);
}
double GSSWAligner::score_to_unnormalized_likelihood_ln(double score) const {
// Log base needs to be set, or this can't work.
assert(log_base != 0);
// Likelihood is proportional to e^(lambda * score), so ln is just the exponent.
return log_base * score;
}
size_t GSSWAligner::longest_detectable_gap(const Alignment& alignment, const string::const_iterator& read_pos) const {
return longest_detectable_gap(alignment.sequence().size(), read_pos - alignment.sequence().begin());
}
size_t GSSWAligner::longest_detectable_gap(size_t read_length, size_t read_pos) const {
// algebraic solution for when score is > 0 assuming perfect match other than gap
assert(read_length >= read_pos);
int64_t overhang_length = min(read_pos, read_length - read_pos);
int64_t numer = match * overhang_length + full_length_bonus;
int64_t gap_length = (numer - gap_open) / gap_extension + 1;
return gap_length >= 0 && overhang_length > 0 ? gap_length : 0;
}
size_t GSSWAligner::longest_detectable_gap(const Alignment& alignment) const {
// longest detectable gap across entire read is in the middle
return longest_detectable_gap(alignment.sequence().size(), alignment.sequence().size() / 2);
}
size_t GSSWAligner::longest_detectable_gap(size_t read_length) const {
return longest_detectable_gap(read_length, read_length / 2);
}
int32_t GSSWAligner::score_discontiguous_alignment(const Alignment& aln, const function<size_t(pos_t, pos_t, size_t)>& estimate_distance,
bool strip_bonuses) const {
int score = 0;
int read_offset = 0;
auto& path = aln.path();
// We keep track of whether the last edit was a deletion for coalescing
// adjacent deletions across node boundaries
bool last_was_deletion = false;
for (int i = 0; i < path.mapping_size(); ++i) {
// For each mapping
auto& mapping = path.mapping(i);
for (int j = 0; j < mapping.edit_size(); ++j) {
// For each edit in the mapping
auto& edit = mapping.edit(j);
// Score the edit according to its type
if (edit_is_match(edit)) {
score += score_exact_match(aln, read_offset, edit.to_length());
last_was_deletion = false;
} else if (edit_is_sub(edit)) {
score += score_mismatch(aln.sequence().begin() + read_offset,
aln.sequence().begin() + read_offset + edit.to_length(),
aln.quality().begin() + read_offset);
last_was_deletion = false;
} else if (edit_is_deletion(edit)) {
if (last_was_deletion) {
// No need to charge a gap open
score -= edit.from_length() * gap_extension;
} else {
// We need a gap open
score -= edit.from_length() ? gap_open + (edit.from_length() - 1) * gap_extension : 0;
}
if (edit.from_length()) {
// We already charged a gap open
last_was_deletion = true;
}
// If there's a 0-length deletion, leave the last_was_deletion flag unchanged.
} else if (edit_is_insertion(edit) && !((i == 0 && j == 0) ||
(i == path.mapping_size()-1 && j == mapping.edit_size()-1))) {
// todo how do we score this qual adjusted?
score -= edit.to_length() ? gap_open + (edit.to_length() - 1) * gap_extension : 0;
last_was_deletion = false;
// No need to track if the last edit was an insertion because
// insertions will be all together in a single edit at a point.
} else {
// Edit has no score effect. Probably a softclip.
last_was_deletion = false;
}
read_offset += edit.to_length();
}
// score any intervening gaps in mappings using approximate distances
if (i+1 < path.mapping_size()) {
// what is the distance between the last position of this mapping
// and the first of the next
Position last_pos = mapping.position();
last_pos.set_offset(last_pos.offset() + mapping_from_length(mapping));
Position next_pos = path.mapping(i+1).position();
// Estimate the distance
int dist = estimate_distance(make_pos_t(last_pos), make_pos_t(next_pos), aln.sequence().size());
if (dist > 0) {
// If it's nonzero, score it as a deletion gap
score -= gap_open + (dist - 1) * gap_extension;
}
}
}
if (!strip_bonuses) {
// We should report any bonuses used in the DP in the final score
if (!softclip_start(aln)) {
score += score_full_length_bonus(true, aln);
}
if (!softclip_end(aln)) {
score += score_full_length_bonus(false, aln);
}
}
return score;
}
int32_t GSSWAligner::score_contiguous_alignment(const Alignment& aln, bool strip_bonuses) const {
return score_discontiguous_alignment(aln, [](pos_t, pos_t, size_t){return (size_t) 0;}, strip_bonuses);
}
int32_t GSSWAligner::remove_bonuses(const Alignment& aln, bool pinned, bool pin_left) const {
int32_t score = aln.score();
if (softclip_start(aln) == 0 && !(pinned && pin_left)) {
// No softclip at the start, and a left end bonus was applied.
score -= score_full_length_bonus(true, aln);
}
if (softclip_end(aln) == 0 && !(pinned && !pin_left)) {
// No softclip at the end, and a right end bonus was applied.
score -= score_full_length_bonus(false, aln);
}
return score;
}
Aligner::Aligner(const int8_t* _score_matrix,
int8_t _gap_open,
int8_t _gap_extension,
int8_t _full_length_bonus,
double _gc_content)
: GSSWAligner(_score_matrix, _gap_open, _gap_extension, _full_length_bonus, _gc_content)
{
// add in the 5th row and column of 0s for N matches like GSSW wants
score_matrix = (int8_t*) malloc(sizeof(int8_t) * 25);
for (size_t i = 0, j = 0; i < 25; ++i) {
if (i % 5 == 4 || i / 5 == 4) {
score_matrix[i] = 0;
}
else {
score_matrix[i] = _score_matrix[j];
++j;
}
}
// make an XdropAligner for each thread
int num_threads = get_thread_count();
xdrops.reserve(num_threads);
for (size_t i = 0; i < num_threads; ++i) {
xdrops.emplace_back(_score_matrix, _gap_open, _gap_extension);
}
}
void Aligner::align_internal(Alignment& alignment, vector<Alignment>* multi_alignments, const HandleGraph& g,
bool pinned, bool pin_left,int32_t max_alt_alns, bool traceback_aln) const {
// bench_start(bench);
// check input integrity
if (pin_left && !pinned) {
cerr << "error:[Aligner] cannot choose pinned end in non-pinned alignment" << endl;
exit(EXIT_FAILURE);
}
if (multi_alignments && !pinned) {
cerr << "error:[Aligner] multiple traceback is not implemented in local alignment, only pinned and global" << endl;
exit(EXIT_FAILURE);
}
if (!multi_alignments && max_alt_alns != 1) {
cerr << "error:[Aligner] cannot specify maximum number of alignments in single alignment" << endl;
exit(EXIT_FAILURE);
}
if (max_alt_alns <= 0) {
cerr << "error:[Aligner] cannot do less than 1 alignment" << endl;
exit(EXIT_FAILURE);
}
// alignment pinning algorithm is based on pinning in bottom right corner, if pinning in top
// left we need to reverse all the sequences first and translate the alignment back later
// make a place to reverse the graph and sequence if necessary
ReverseGraph reversed_graph(&g, false);
string reversed_sequence;
// choose forward or reversed objects
const HandleGraph* oriented_graph = &g;
const string* align_sequence = &alignment.sequence();
if (pin_left) {
// choose the reversed graph
oriented_graph = &reversed_graph;
// make and assign the reversed sequence
reversed_sequence.resize(align_sequence->size());
reverse_copy(align_sequence->begin(), align_sequence->end(), reversed_sequence.begin());
align_sequence = &reversed_sequence;
}
// to save compute, we won't make these unless we're doing pinning
unordered_set<vg::id_t> pinning_ids;
NullMaskingGraph* null_masked_graph = nullptr;
const HandleGraph* align_graph = oriented_graph;
if (pinned) {
pinning_ids = identify_pinning_points(*oriented_graph);
null_masked_graph = new NullMaskingGraph(oriented_graph);
align_graph = null_masked_graph;
}
// convert into gssw graph
gssw_graph* graph = create_gssw_graph(*align_graph);
// perform dynamic programming
gssw_graph_fill_pinned(graph, align_sequence->c_str(),
nt_table, score_matrix,
gap_open, gap_extension, full_length_bonus,
pinned ? 0 : full_length_bonus, 15, 2, traceback_aln);
// traceback either from pinned position or optimal local alignment
if (traceback_aln) {
if (pinned) {
// we can only run gssw's DP on non-empty graphs, but we may have masked the entire graph
// if it consists of only empty nodes, so don't both with the DP in that case
gssw_graph_mapping** gms = nullptr;
if (align_graph->get_node_count() > 0) {
gssw_node** pinning_nodes = (gssw_node**) malloc(pinning_ids.size() * sizeof(gssw_node*));
size_t j = 0;
for (size_t i = 0; i < graph->size; i++) {
gssw_node* node = graph->nodes[i];
if (pinning_ids.count(node->id)) {
pinning_nodes[j] = node;
j++;
}
}
// trace back pinned alignment
gms = gssw_graph_trace_back_pinned_multi (graph,
max_alt_alns,
true,
align_sequence->c_str(),
align_sequence->size(),
pinning_nodes,
pinning_ids.size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
full_length_bonus,
0);
free(pinning_nodes);
}
// did we both 1) do DP (i.e. the graph is non-empty), and 2) find a traceback with positive score?
if (gms ? gms[0]->score > 0 : false) {
if (pin_left) {
// translate nodes and mappings into original sequence so that the cigars come out right
unreverse_graph(graph);
for (int32_t i = 0; i < max_alt_alns; i++) {
unreverse_graph_mapping(gms[i]);
}
}
// have a mapping, can just convert normally
gssw_mapping_to_alignment(graph, gms[0], alignment, pinned, pin_left);
if (multi_alignments) {
// determine how many non-null alignments were returned
int32_t num_non_null = max_alt_alns;
for (int32_t i = 1; i < max_alt_alns; i++) {
if (gms[i]->score <= 0) {
num_non_null = i;
break;
}
}
// reserve to avoid illegal access errors that occur when the vector reallocates
multi_alignments->reserve(num_non_null);
// copy the primary alignment
multi_alignments->emplace_back(alignment);
// convert the alternate alignments and store them at the back of the vector (this will not
// execute if we are doing single alignment)
for (int32_t i = 1; i < num_non_null; i++) {
// make new alignment object
multi_alignments->emplace_back();
Alignment& next_alignment = multi_alignments->back();
// copy over sequence information from the primary alignment
next_alignment.set_sequence(alignment.sequence());
next_alignment.set_quality(alignment.quality());
// get path of the alternate alignment
gssw_mapping_to_alignment(graph, gms[i], next_alignment, pinned, pin_left);
}
}
}
else if (g.get_node_count() > 0) {
// we didn't get any alignments either because the graph was empty and we couldn't run
// gssw DP or because they had score 0 and gssw didn't want to do traceback. however,
// we can infer the location of softclips based on the pinning nodes, so we'll just make
// those manually
// find the sink nodes of the oriented graph, which may be empty
auto pinning_points = handlealgs::tail_nodes(oriented_graph);
// impose a consistent ordering for machine independent behavior
sort(pinning_points.begin(), pinning_points.end(), [&](const handle_t& h1, const handle_t& h2) {
return oriented_graph->get_id(h1) < oriented_graph->get_id(h2);
});
for (size_t i = 0; i < max_alt_alns && i < pinning_points.size(); i++) {
// make a record in the multi alignments if we're using them
if (multi_alignments) {
multi_alignments->emplace_back();
}
// choose an alignment object to construct the path in
Alignment& softclip_alignment = i == 0 ? alignment : multi_alignments->back();
handle_t& pinning_point = pinning_points[i];
Mapping* mapping = alignment.mutable_path()->add_mapping();
mapping->set_rank(1);
// locate at the beginning or end of the node
Position* position = mapping->mutable_position();
position->set_node_id(oriented_graph->get_id(pinning_point));
position->set_offset(pin_left ? 0 : oriented_graph->get_length(pinning_point));
// soft clip
Edit* edit = mapping->add_edit();
edit->set_to_length(alignment.sequence().length());
edit->set_sequence(alignment.sequence());
// we want to also have the first alignment in the multi-alignment vector
if (i == 0 && multi_alignments) {
multi_alignments->back() = alignment;
}
}
}
if (gms) {
for (int32_t i = 0; i < max_alt_alns; i++) {
gssw_graph_mapping_destroy(gms[i]);
}
free(gms);
}
}
else {
// trace back local alignment
gssw_graph_mapping* gm = gssw_graph_trace_back (graph,
align_sequence->c_str(),
align_sequence->size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
full_length_bonus,
full_length_bonus);
gssw_mapping_to_alignment(graph, gm, alignment, pinned, pin_left);
gssw_graph_mapping_destroy(gm);
}
} else {
// get the alignment position and score
alignment.set_score(graph->max_node->alignment->score1);
Mapping* m = alignment.mutable_path()->add_mapping();
Position* p = m->mutable_position();
p->set_node_id(graph->max_node->id);
p->set_offset(graph->max_node->alignment->ref_end1); // mark end position; for de-duplication
}
// this might be null if we're not doing pinned alignment, but delete doesn't care
delete null_masked_graph;
gssw_graph_destroy(graph);
// bench_end(bench);
}
void Aligner::align(Alignment& alignment, const HandleGraph& g, bool traceback_aln) const {
align_internal(alignment, nullptr, g, false, false, 1, traceback_aln);
}
void Aligner::align(Alignment& alignment, const HandleGraph& g,
const std::vector<handle_t>& topological_order) const {
// Create a gssw_graph and a mapping from handles to nodes.
gssw_graph* graph = gssw_graph_create(topological_order.size());
hash_map<handle_t, gssw_node*> nodes;
nodes.reserve(topological_order.size());
// Create the nodes. Use offsets in the topological order as node ids.
for (size_t i = 0; i < topological_order.size(); i++) {
handle_t handle = topological_order[i];
auto cleaned_seq = nonATGCNtoN(g.get_sequence(handle));
gssw_node* node = gssw_node_create(nullptr,
i,
cleaned_seq.c_str(),
nt_table,
score_matrix);
nodes[handle] = node;
gssw_graph_add_node(graph, node);
}
// Create the edges.
for (const handle_t& from : topological_order) {
gssw_node* from_node = nodes[from];
g.follow_edges(from, false, [&](const handle_t& to) {
auto iter = nodes.find(to);
if (iter != nodes.end()) {
gssw_nodes_add_edge(from_node, iter->second);
}
});
}
// Align the read to the subgraph.
gssw_graph_fill_pinned(graph, alignment.sequence().c_str(),
nt_table, score_matrix,
gap_open, gap_extension, full_length_bonus, full_length_bonus,
15, 2, true);
gssw_graph_mapping* gm = gssw_graph_trace_back(graph,
alignment.sequence().c_str(), alignment.sequence().length(),
nt_table, score_matrix,
gap_open, gap_extension, full_length_bonus, full_length_bonus);
// Convert the mapping to Alignment.
this->gssw_mapping_to_alignment(graph, gm, alignment, false, false);
Path& path = *(alignment.mutable_path());
for (size_t i = 0; i < path.mapping_size(); i++) {
Position& pos = *(path.mutable_mapping(i)->mutable_position());
handle_t handle = topological_order[pos.node_id()];
pos.set_node_id(g.get_id(handle));
pos.set_is_reverse(g.get_is_reverse(handle));
}
// Destroy the temporary objects.
gssw_graph_mapping_destroy(gm);
gssw_graph_destroy(graph);
}
void Aligner::align_pinned(Alignment& alignment, const HandleGraph& g, bool pin_left, bool xdrop,
uint16_t xdrop_max_gap_length) const {
if (xdrop) {
// XdropAligner manages its own stack, so it can never be threadsafe without be recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
XdropAligner& xdrop = const_cast<XdropAligner&>(xdrops[omp_get_thread_num()]);
// dozeu declines to produce an alignment when the gap is set to 0
xdrop_max_gap_length = max<uint16_t>(xdrop_max_gap_length, 1);
// wrap the graph so that empty pinning points are handled correctly
DozeuPinningOverlay overlay(&g, !pin_left);
if (overlay.get_node_count() == 0 && g.get_node_count() > 0) {
// the only nodes in the graph are empty nodes for pinning, which got masked.
// we can still infer a pinned alignment based purely on the pinning point but
// dozeu won't handle this correctly
g.for_each_handle([&](const handle_t& handle) {
bool can_pin = g.follow_edges(handle, pin_left, [&](const handle_t& next) {return false;});
if (can_pin) {
// manually make the softclip
Mapping* mapping = alignment.mutable_path()->add_mapping();
Position* pos = mapping->mutable_position();
pos->set_node_id(g.get_id(handle));
pos->set_is_reverse(false);
pos->set_offset(pin_left ? 0 : g.get_length(handle));
mapping->set_rank(1);
Edit* edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(alignment.sequence().size());
edit->set_sequence(alignment.sequence());
alignment.set_score(0);
return false;
}
return true;
});
}
else {
// do the alignment
xdrop.align_pinned(alignment, overlay, pin_left, full_length_bonus, xdrop_max_gap_length);
if (overlay.performed_duplications()) {
// the overlay is not a strict subset of the underlying graph, so we may
// need to translate some node IDs
translate_oriented_node_ids(*alignment.mutable_path(), [&](id_t node_id) {
handle_t under = overlay.get_underlying_handle(overlay.get_handle(node_id));
return make_pair(g.get_id(under), g.get_is_reverse(under));
});
}
}
}
else {
align_internal(alignment, nullptr, g, true, pin_left, 1, true);
}
}
void Aligner::align_pinned_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
bool pin_left, int32_t max_alt_alns) const {
if (alt_alignments.size() != 0) {
cerr << "error:[Aligner::align_pinned_multi] output vector must be empty for pinned multi-aligning" << endl;
exit(EXIT_FAILURE);
}
align_internal(alignment, &alt_alignments, g, true, pin_left, max_alt_alns, true);
}
void Aligner::align_global_banded(Alignment& alignment, const HandleGraph& g,
int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align(alignment, g);
return;
}
// We need to figure out what size ints we need to use.
// Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
// TODO: put this all into another template somehow?
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void Aligner::align_global_banded_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
int32_t max_alt_alns, int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align_multi(alignment, alt_alignments, g, max_alt_alns);
return;
}
// We need to figure out what size ints we need to use.
// Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void Aligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<MaximalExactMatch>& mems,
bool reverse_complemented, uint16_t max_gap_length) const
{
align_xdrop(alignment, g, handlealgs::lazier_topological_order(&g), mems, reverse_complemented,
max_gap_length);
}
void Aligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<handle_t>& order,
const vector<MaximalExactMatch>& mems, bool reverse_complemented, uint16_t max_gap_length) const
{
// XdropAligner manages its own stack, so it can never be threadsafe without be recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
XdropAligner& xdrop = const_cast<XdropAligner&>(xdrops[omp_get_thread_num()]);
xdrop.align(alignment, g, order, mems, reverse_complemented, full_length_bonus, max_gap_length);
if (!alignment.has_path() && mems.empty()) {
// dozeu couldn't find an alignment, probably because it's seeding heuristic failed
// we'll just fall back on GSSW
// TODO: This is a bit inconsistent. GSSW gives a full-length bonus at both ends, while
// dozeu only gives it once.
align(alignment, g, order);
}
}
// Scoring an exact match is very simple in an ordinary Aligner
int32_t Aligner::score_exact_match(const Alignment& aln, size_t read_offset, size_t length) const {
return match * length;
}
int32_t Aligner::score_exact_match(const string& sequence) const {
return match * sequence.length();
}
int32_t Aligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end) const {
return match * (seq_end - seq_begin);
}
int32_t Aligner::score_exact_match(const string& sequence, const string& base_quality) const {
return score_exact_match(sequence);
}
int32_t Aligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
return score_exact_match(seq_begin, seq_end);
}
int32_t Aligner::score_mismatch(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
return -mismatch * (seq_end - seq_begin);
}
int32_t Aligner::score_mismatch(size_t length) const {
return -match * length;
}
int32_t Aligner::score_full_length_bonus(bool left_side, string::const_iterator seq_begin,
string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
return full_length_bonus;
}
int32_t Aligner::score_full_length_bonus(bool left_side, const Alignment& alignment) const {
return full_length_bonus;
}
int32_t Aligner::score_partial_alignment(const Alignment& alignment, const HandleGraph& graph, const Path& path,
string::const_iterator seq_begin, bool no_read_end_scoring) const {
int32_t score = 0;
string::const_iterator read_pos = seq_begin;
bool in_deletion = false;
for (size_t i = 0; i < path.mapping_size(); i++) {
const Mapping& mapping = path.mapping(i);
for (size_t j = 0; j < mapping.edit_size(); j++) {
const Edit& edit = mapping.edit(j);
if (edit.from_length() > 0) {
if (edit.to_length() > 0) {
if (edit.sequence().empty()) {
// match
score += match * edit.from_length();
}
else {
// mismatch
score -= mismatch * edit.from_length();
}
// apply full length bonus
if (read_pos == alignment.sequence().begin() && !no_read_end_scoring) {
score += score_full_length_bonus(true, alignment);
}
if (read_pos + edit.to_length() == alignment.sequence().end()
&& !no_read_end_scoring) {
score += score_full_length_bonus(false, alignment);
}
in_deletion = false;
}
else if (in_deletion) {
score -= edit.from_length() * gap_extension;
}
else {
// deletion
score -= gap_open + (edit.from_length() - 1) * gap_extension;
in_deletion = true;
}
}
else if (edit.to_length() > 0) {
// don't score soft clips if scoring read ends
if (no_read_end_scoring ||
(read_pos != alignment.sequence().begin() &&
read_pos + edit.to_length() != alignment.sequence().end())) {
// insert
score -= gap_open + (edit.to_length() - 1) * gap_extension;
}
in_deletion = false;
}
read_pos += edit.to_length();
}
}
return score;
}
QualAdjAligner::QualAdjAligner(const int8_t* _score_matrix,
int8_t _gap_open,
int8_t _gap_extension,
int8_t _full_length_bonus,
double _gc_content)
: GSSWAligner(_score_matrix, _gap_open, _gap_extension, _full_length_bonus, _gc_content)
{
// TODO: this interface could really be improved in GSSW, oh well though
// find the quality-adjusted scores
uint32_t max_base_qual = 255;
// add in the 0s to the 5-th row and column for Ns
score_matrix = qual_adjusted_matrix(_score_matrix, _gc_content, max_base_qual);
// compute the quality adjusted full length bonuses
qual_adj_full_length_bonuses = qual_adjusted_bonuses(_full_length_bonus, max_base_qual);
// make a QualAdjXdropAligner for each thread
int num_threads = get_thread_count();
xdrops.reserve(num_threads);
for (size_t i = 0; i < num_threads; ++i) {
xdrops.emplace_back(_score_matrix, score_matrix, _gap_open, _gap_extension);
}
}
QualAdjAligner::~QualAdjAligner() {
free(qual_adj_full_length_bonuses);
}
int8_t* QualAdjAligner::qual_adjusted_matrix(const int8_t* _score_matrix, double gc_content, uint32_t max_qual) const {
// TODO: duplicative with GSSWAligner()
double* nt_freqs = (double*) malloc(sizeof(double) * 4);
nt_freqs[0] = 0.5 * (1 - gc_content);
nt_freqs[1] = 0.5 * gc_content;
nt_freqs[2] = 0.5 * gc_content;
nt_freqs[3] = 0.5 * (1 - gc_content);
// recover the emission probabilities of the align state of the HMM
double* align_prob = (double*) malloc(sizeof(double) * 16);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
align_prob[i * 4 + j] = (exp(log_base * _score_matrix[i * 4 + j])
* nt_freqs[i] * nt_freqs[j]);
}
}
// compute the sum of the emission probabilities under a base error
double* align_complement_prob = (double*) malloc(sizeof(double) * 16);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
align_complement_prob[i * 4 + j] = 0.0;
for (int k = 0; k < 4; k++) {
if (k != j) {
align_complement_prob[i * 4 + j] += align_prob[i * 4 + k];
}
}
}
}
// quality score of random guessing
int lowest_meaningful_qual = ceil(-10.0 * log10(0.75));
// compute the adjusted alignment scores for each quality level
int8_t* qual_adj_mat = (int8_t*) malloc(25 * (max_qual + 1) * sizeof(int8_t));
for (int q = 0; q <= max_qual; q++) {
double err = pow(10.0, -q / 10.0);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
int8_t score;
if (i == 4 || j == 4 || q < lowest_meaningful_qual) {
score = 0;
}
else {
score = round(log(((1.0 - err) * align_prob[i * 4 + j] + (err / 3.0) * align_complement_prob[i * 4 + j])
/ (nt_freqs[i] * ((1.0 - err) * nt_freqs[j] + (err / 3.0) * (1.0 - nt_freqs[j])))) / log_base);
}
qual_adj_mat[q * 25 + i * 5 + j] = round(score);
}
}
}
free(align_complement_prob);
free(align_prob);
free(nt_freqs);
return qual_adj_mat;
}
int8_t* QualAdjAligner::qual_adjusted_bonuses(int8_t _full_length_bonus, uint32_t max_qual) const {
double p_full_len = exp(log_base * _full_length_bonus) / (1.0 + exp(log_base * _full_length_bonus));
int8_t* qual_adj_bonuses = (int8_t*) calloc(max_qual + 1, sizeof(int8_t));
int lowest_meaningful_qual = ceil(-10.0 * log10(0.75));
// hack because i want the minimum qual value from illumina (2) to have zero score, but phred
// values are spaced out in a way to approximate this singularity well
++lowest_meaningful_qual;
for (int q = lowest_meaningful_qual; q <= max_qual; ++q) {
double err = pow(10.0, -q / 10.0);
double score = log(((1.0 - err * 4.0 / 3.0) * p_full_len + (err * 4.0 / 3.0) * (1.0 - p_full_len)) / (1.0 - p_full_len)) / log_base;
qual_adj_bonuses[q] = round(score);
}
return qual_adj_bonuses;
}
void QualAdjAligner::align_internal(Alignment& alignment, vector<Alignment>* multi_alignments, const HandleGraph& g,
bool pinned, bool pin_left, int32_t max_alt_alns, bool traceback_aln) const {
// check input integrity
if (pin_left && !pinned) {
cerr << "error:[Aligner] cannot choose pinned end in non-pinned alignment" << endl;
exit(EXIT_FAILURE);
}
if (multi_alignments && !pinned) {
cerr << "error:[Aligner] multiple traceback is not implemented in local alignment, only pinned and global" << endl;
exit(EXIT_FAILURE);
}
if (!multi_alignments && max_alt_alns != 1) {
cerr << "error:[Aligner] cannot specify maximum number of alignments in single alignment" << endl;
exit(EXIT_FAILURE);
}
if (max_alt_alns <= 0) {
cerr << "error:[Aligner] cannot do less than 1 alignment" << endl;
exit(EXIT_FAILURE);
}
// alignment pinning algorithm is based on pinning in bottom right corner, if pinning in top
// left we need to reverse all the sequences first and translate the alignment back later
// make a place to reverse the graph and sequence if necessary
ReverseGraph reversed_graph(&g, false);
string reversed_sequence;
string reversed_quality;
// choose forward or reversed objects
const HandleGraph* oriented_graph = &g;
const string* align_sequence = &alignment.sequence();
const string* align_quality = &alignment.quality();
if (pin_left) {
// choose the reversed graph
oriented_graph = &reversed_graph;
// make and assign the reversed sequence
reversed_sequence.resize(align_sequence->size());
reverse_copy(align_sequence->begin(), align_sequence->end(), reversed_sequence.begin());
align_sequence = &reversed_sequence;
// make and assign the reversed quality
reversed_quality.resize(align_quality->size());
reverse_copy(align_quality->begin(), align_quality->end(), reversed_quality.begin());
align_quality = &reversed_quality;
}
if (align_quality->size() != align_sequence->size()) {
cerr << "error:[QualAdjAligner] Read " << alignment.name() << " has sequence and quality strings with different lengths. Cannot perform base quality adjusted alignment. Consider toggling off base quality adjusted alignment at the command line." << endl;
exit(EXIT_FAILURE);
}
// to save compute, we won't make these unless we're doing pinning
unordered_set<vg::id_t> pinning_ids;
NullMaskingGraph* null_masked_graph = nullptr;
const HandleGraph* align_graph = oriented_graph;
if (pinned) {
pinning_ids = identify_pinning_points(*oriented_graph);
null_masked_graph = new NullMaskingGraph(oriented_graph);
align_graph = null_masked_graph;
}
// convert into gssw graph
gssw_graph* graph = create_gssw_graph(*align_graph);
int8_t front_full_length_bonus = qual_adj_full_length_bonuses[align_quality->front()];
int8_t back_full_length_bonus = qual_adj_full_length_bonuses[align_quality->back()];
// perform dynamic programming
// offer a full length bonus on each end, or only on the left if the right end is pinned.
gssw_graph_fill_pinned_qual_adj(graph, align_sequence->c_str(), align_quality->c_str(),
nt_table, score_matrix,
gap_open, gap_extension,
front_full_length_bonus,
pinned ? 0 : back_full_length_bonus,
15, 2, traceback_aln);
// traceback either from pinned position or optimal local alignment
if (traceback_aln) {
if (pinned) {
gssw_graph_mapping** gms = nullptr;
if (align_graph->get_node_count() > 0) {
gssw_node** pinning_nodes = (gssw_node**) malloc(pinning_ids.size() * sizeof(gssw_node*));
size_t j = 0;
for (size_t i = 0; i < graph->size; i++) {
gssw_node* node = graph->nodes[i];
if (pinning_ids.count(node->id)) {
pinning_nodes[j] = node;
j++;
}
}
// trace back pinned alignment
gms = gssw_graph_trace_back_pinned_qual_adj_multi (graph,
max_alt_alns,
true,
align_sequence->c_str(),
align_quality->c_str(),
align_sequence->size(),
pinning_nodes,
pinning_ids.size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
front_full_length_bonus,
0);
free(pinning_nodes);
}
// did we both 1) do DP (i.e. the graph is non-empty), and 2) find a traceback with positive score?
if (gms && gms[0]->score > 0) {
if (pin_left) {
// translate graph and mappings into original node space
unreverse_graph(graph);
for (int32_t i = 0; i < max_alt_alns; i++) {
unreverse_graph_mapping(gms[i]);
}
}
// have a mapping, can just convert normally
gssw_mapping_to_alignment(graph, gms[0], alignment, pinned, pin_left);
if (multi_alignments) {
// determine how many non-null alignments were returned
int32_t num_non_null = max_alt_alns;
for (int32_t i = 1; i < max_alt_alns; i++) {
if (gms[i]->score <= 0) {
num_non_null = i;
break;
}
}
// reserve to avoid illegal access errors that occur when the vector reallocates
multi_alignments->reserve(num_non_null);
// copy the primary alignment
multi_alignments->emplace_back(alignment);
// convert the alternate alignments and store them at the back of the vector (this will not
// execute if we are doing single alignment)
for (int32_t i = 1; i < num_non_null; i++) {
// make new alignment object
multi_alignments->emplace_back();
Alignment& next_alignment = multi_alignments->back();
// copy over sequence information from the primary alignment
next_alignment.set_sequence(alignment.sequence());
next_alignment.set_quality(alignment.quality());
// get path of the alternate alignment
gssw_mapping_to_alignment(graph, gms[i], next_alignment, pinned, pin_left);
}
}
}
else if (g.get_node_count() > 0) {
/// we didn't get any alignments either because the graph was empty and we couldn't run
// gssw DP or because they had score 0 and gssw didn't want to do traceback. however,
// we can infer the location of softclips based on the pinning nodes, so we'll just make
// those manually
// find the sink nodes of the oriented graph, which may be empty
auto pinning_points = handlealgs::tail_nodes(oriented_graph);
// impose a consistent ordering for machine independent behavior
sort(pinning_points.begin(), pinning_points.end(), [&](const handle_t& h1, const handle_t& h2) {
return oriented_graph->get_id(h1) < oriented_graph->get_id(h2);
});
for (size_t i = 0; i < max_alt_alns && i < pinning_points.size(); i++) {
// make a record in the multi alignments if we're using them
if (multi_alignments) {
multi_alignments->emplace_back();
}
// choose an alignment object to construct the path in
Alignment& softclip_alignment = i == 0 ? alignment : multi_alignments->back();
handle_t& pinning_point = pinning_points[i];
Mapping* mapping = alignment.mutable_path()->add_mapping();
mapping->set_rank(1);
// locate at the beginning or end of the node
Position* position = mapping->mutable_position();
position->set_node_id(oriented_graph->get_id(pinning_point));
position->set_offset(pin_left ? 0 : oriented_graph->get_length(pinning_point));
// soft clip
Edit* edit = mapping->add_edit();
edit->set_to_length(alignment.sequence().length());
edit->set_sequence(alignment.sequence());
// we want to also have the first alignment in the multi-alignment vector
if (i == 0 && multi_alignments) {
multi_alignments->back() = alignment;
}
}
}
if (gms) {
for (int32_t i = 0; i < max_alt_alns; i++) {
gssw_graph_mapping_destroy(gms[i]);
}
free(gms);
}
}
else {
// trace back local alignment
gssw_graph_mapping* gm = gssw_graph_trace_back_qual_adj (graph,
align_sequence->c_str(),
align_quality->c_str(),
align_sequence->size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
front_full_length_bonus,
back_full_length_bonus);
gssw_mapping_to_alignment(graph, gm, alignment, pinned, pin_left);
gssw_graph_mapping_destroy(gm);
}
} else {
// get the alignment position and score
alignment.set_score(graph->max_node->alignment->score1);
Mapping* m = alignment.mutable_path()->add_mapping();
Position* p = m->mutable_position();
p->set_node_id(graph->max_node->id);
p->set_offset(graph->max_node->alignment->ref_end1); // mark end position; for de-duplication
}
// this might be null if we're not doing pinned alignment, but delete doesn't care
delete null_masked_graph;
gssw_graph_destroy(graph);
}
void QualAdjAligner::align(Alignment& alignment, const HandleGraph& g, bool traceback_aln) const {
align_internal(alignment, nullptr, g, false, false, 1, traceback_aln);
}
void QualAdjAligner::align_pinned(Alignment& alignment, const HandleGraph& g, bool pin_left, bool xdrop,
uint16_t xdrop_max_gap_length) const {
if (xdrop) {
// QualAdjXdropAligner manages its own stack, so it can never be threadsafe without be recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
QualAdjXdropAligner& xdrop = const_cast<QualAdjXdropAligner&>(xdrops[omp_get_thread_num()]);
// wrap the graph so that empty pinning points are handled correctly
DozeuPinningOverlay overlay(&g, !pin_left);
if (overlay.get_node_count() == 0 && g.get_node_count() > 0) {
// the only nodes in the graph are empty nodes for pinning, which got masked.
// we can still infer a pinned alignment based purely on the pinning point but
// dozeu won't handle this correctly
g.for_each_handle([&](const handle_t& handle) {
bool can_pin = g.follow_edges(handle, pin_left, [&](const handle_t& next) {return false;});
if (can_pin) {
// manually make the softclip
Mapping* mapping = alignment.mutable_path()->add_mapping();
Position* pos = mapping->mutable_position();
pos->set_node_id(g.get_id(handle));
pos->set_is_reverse(false);
pos->set_offset(pin_left ? 0 : g.get_length(handle));
mapping->set_rank(1);
Edit* edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(alignment.sequence().size());
edit->set_sequence(alignment.sequence());
alignment.set_score(0);
return false;
}
return true;
});
}
else {
// dozeu declines to produce an alignment when the gap is set to 0
xdrop_max_gap_length = max<uint16_t>(xdrop_max_gap_length, 1);
// get the quality adjusted bonus
int8_t bonus = qual_adj_full_length_bonuses[pin_left ? alignment.quality().back() : alignment.quality().front()];
xdrop.align_pinned(alignment, overlay, pin_left, bonus, xdrop_max_gap_length);
if (overlay.performed_duplications()) {
// the overlay is not a strict subset of the underlying graph, so we may
// need to translate some node IDs
translate_oriented_node_ids(*alignment.mutable_path(), [&](id_t node_id) {
handle_t under = overlay.get_underlying_handle(overlay.get_handle(node_id));
return make_pair(g.get_id(under), g.get_is_reverse(under));
});
}
}
}
else {
align_internal(alignment, nullptr, g, true, pin_left, 1, true);
}
}
void QualAdjAligner::align_pinned_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
bool pin_left, int32_t max_alt_alns) const {
align_internal(alignment, &alt_alignments, g, true, pin_left, max_alt_alns, true);
}
void QualAdjAligner::align_global_banded(Alignment& alignment, const HandleGraph& g,
int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align(alignment, g);
return;
}
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
// TODO: put this all into another template somehow?
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void QualAdjAligner::align_global_banded_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
int32_t max_alt_alns, int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align_multi(alignment, alt_alignments, g, max_alt_alns);
return;
}
// We need to figure out what size ints we need to use.
// Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void QualAdjAligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<MaximalExactMatch>& mems,
bool reverse_complemented, uint16_t max_gap_length) const
{
align_xdrop(alignment, g, handlealgs::lazier_topological_order(&g), mems, reverse_complemented, max_gap_length);
}
void QualAdjAligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<handle_t>& order,
const vector<MaximalExactMatch>& mems, bool reverse_complemented,
uint16_t max_gap_length) const
{
// QualAdjXdropAligner manages its own stack, so it can never be threadsafe without being recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
QualAdjXdropAligner& xdrop = const_cast<QualAdjXdropAligner&>(xdrops[omp_get_thread_num()]);
// get the quality adjusted bonus
int8_t bonus = qual_adj_full_length_bonuses[reverse_complemented ? alignment.quality().front() : alignment.quality().back()];
xdrop.align(alignment, g, order, mems, reverse_complemented, bonus, max_gap_length);
if (!alignment.has_path() && mems.empty()) {
// dozeu couldn't find an alignment, probably because it's seeding heuristic failed
// we'll just fall back on GSSW
// TODO: This is a bit inconsistent. GSSW gives a full-length bonus at both ends, while
// dozeu only gives it once.
align(alignment, g, true);
}
}
int32_t QualAdjAligner::score_exact_match(const Alignment& aln, size_t read_offset, size_t length) const {
auto& sequence = aln.sequence();
auto& base_quality = aln.quality();
int32_t score = 0;
for (int32_t i = 0; i < length; i++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * base_quality[read_offset + i] + 6 * nt_table[sequence[read_offset + i]]];
}
return score;
}
int32_t QualAdjAligner::score_exact_match(const string& sequence, const string& base_quality) const {
int32_t score = 0;
for (int32_t i = 0; i < sequence.length(); i++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * base_quality[i] + 6 * nt_table[sequence[i]]];
}
return score;
}
int32_t QualAdjAligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
int32_t score = 0;
for (auto seq_iter = seq_begin, qual_iter = base_qual_begin; seq_iter != seq_end; seq_iter++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * (*qual_iter) + 6 * nt_table[*seq_iter]];
qual_iter++;
}
return score;
}
int32_t QualAdjAligner::score_mismatch(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
int32_t score = 0;
for (auto seq_iter = seq_begin, qual_iter = base_qual_begin; seq_iter != seq_end; seq_iter++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * (*qual_iter) + 1];
qual_iter++;
}
return score;
}
int32_t QualAdjAligner::score_full_length_bonus(bool left_side, string::const_iterator seq_begin,
string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
if (seq_begin != seq_end) {
return qual_adj_full_length_bonuses[left_side ? *base_qual_begin : *(base_qual_begin + (seq_end - seq_begin) - 1)];
}
else {
return 0;
}
}
int32_t QualAdjAligner::score_full_length_bonus(bool left_side, const Alignment& alignment) const {
return score_full_length_bonus(left_side, alignment.sequence().begin(), alignment.sequence().end(),
alignment.quality().begin());
}
int32_t QualAdjAligner::score_partial_alignment(const Alignment& alignment, const HandleGraph& graph, const Path& path,
string::const_iterator seq_begin, bool no_read_end_scoring) const {
int32_t score = 0;
string::const_iterator read_pos = seq_begin;
string::const_iterator qual_pos = alignment.quality().begin() + (seq_begin - alignment.sequence().begin());
bool in_deletion = false;
for (size_t i = 0; i < path.mapping_size(); i++) {
const Mapping& mapping = path.mapping(i);
// get the sequence of this node on the proper strand
string node_seq = graph.get_sequence(graph.get_handle(mapping.position().node_id(),
mapping.position().is_reverse()));
string::const_iterator ref_pos = node_seq.begin() + mapping.position().offset();
for (size_t j = 0; j < mapping.edit_size(); j++) {
const Edit& edit = mapping.edit(j);
if (edit.from_length() > 0) {
if (edit.to_length() > 0) {
for (auto siter = read_pos, riter = ref_pos, qiter = qual_pos;
siter != read_pos + edit.to_length(); siter++, qiter++, riter++) {
score += score_matrix[25 * (*qiter) + 5 * nt_table[*riter] + nt_table[*siter]];
}
// apply full length bonus
if (read_pos == alignment.sequence().begin() && !no_read_end_scoring) {
score += score_full_length_bonus(true, alignment);
}
if (read_pos + edit.to_length() == alignment.sequence().end()
&& !no_read_end_scoring) {
score += score_full_length_bonus(false, alignment);
}
in_deletion = false;
}
else if (in_deletion) {
score -= edit.from_length() * gap_extension;
}
else {
// deletion
score -= gap_open + (edit.from_length() - 1) * gap_extension;
in_deletion = true;
}
}
else if (edit.to_length() > 0) {
// don't score soft clips if read end scoring
if (no_read_end_scoring ||
(read_pos != alignment.sequence().begin() &&
read_pos + edit.to_length() != alignment.sequence().end())) {
// insert
score -= gap_open + (edit.to_length() - 1) * gap_extension;
}
in_deletion = false;
}
read_pos += edit.to_length();
qual_pos += edit.to_length();
ref_pos += edit.from_length();
}
}
return score;
}
AlignerClient::AlignerClient(double gc_content_estimate) : gc_content_estimate(gc_content_estimate) {
// Adopt the default scoring parameters and make the aligners
set_alignment_scores(default_score_matrix,
default_gap_open, default_gap_extension,
default_full_length_bonus);
}
const GSSWAligner* AlignerClient::get_aligner(bool have_qualities) const {
return (have_qualities && adjust_alignments_for_base_quality) ?
(GSSWAligner*) get_qual_adj_aligner() :
(GSSWAligner*) get_regular_aligner();
}
const QualAdjAligner* AlignerClient::get_qual_adj_aligner() const {
assert(qual_adj_aligner.get() != nullptr);
return qual_adj_aligner.get();
}
const Aligner* AlignerClient::get_regular_aligner() const {
assert(regular_aligner.get() != nullptr);
return regular_aligner.get();
}
int8_t* AlignerClient::parse_matrix(istream& matrix_stream) {
int8_t* matrix = (int8_t*) malloc(16 * sizeof(int8_t));
for (size_t i = 0; i < 16; i++) {
if (!matrix_stream.good()) {
std::cerr << "error: vg Aligner::parse_matrix requires a 4x4 whitespace separated integer matrix\n";
throw "";
}
int score;
matrix_stream >> score;
if (score > 127 || score < -127) {
std::cerr << "error: vg Aligner::parse_matrix requires values in the range [-127,127]\n";
throw "";
}
matrix[i] = score;
}
return matrix;
}
void AlignerClient::set_alignment_scores(int8_t match, int8_t mismatch, int8_t gap_open, int8_t gap_extend,
int8_t full_length_bonus) {
int8_t* matrix = (int8_t*) malloc(sizeof(int8_t) * 16);
for (size_t i = 0; i < 16; ++i) {
if (i % 5 == 0) {
matrix[i] = match;
}
else {
matrix[i] = -mismatch;
}
}
qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
regular_aligner = unique_ptr<Aligner>(new Aligner(matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
free(matrix);
}
void AlignerClient::set_alignment_scores(const int8_t* score_matrix, int8_t gap_open, int8_t gap_extend, int8_t full_length_bonus) {
qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
regular_aligner = unique_ptr<Aligner>(new Aligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
}
void AlignerClient::set_alignment_scores(std::istream& matrix_stream, int8_t gap_open, int8_t gap_extend, int8_t full_length_bonus) {
int8_t* score_matrix = parse_matrix(matrix_stream);
qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
regular_aligner = unique_ptr<Aligner>(new Aligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
free(score_matrix);
}
| 44.62401
| 261
| 0.545571
|
lnceballosz
|
44d0d8d84f9c14123b958c0932770f98c8761f30
| 8,573
|
cc
|
C++
|
L1Trigger/Phase2L1GMT/plugins/Phase2L1TGMTStubProducer.cc
|
PKUfudawei/cmssw
|
8fbb5ce74398269c8a32956d7c7943766770c093
|
[
"Apache-2.0"
] | 1
|
2021-11-30T16:24:46.000Z
|
2021-11-30T16:24:46.000Z
|
L1Trigger/Phase2L1GMT/plugins/Phase2L1TGMTStubProducer.cc
|
PKUfudawei/cmssw
|
8fbb5ce74398269c8a32956d7c7943766770c093
|
[
"Apache-2.0"
] | 4
|
2021-11-29T13:57:56.000Z
|
2022-03-29T06:28:36.000Z
|
L1Trigger/Phase2L1GMT/plugins/Phase2L1TGMTStubProducer.cc
|
PKUfudawei/cmssw
|
8fbb5ce74398269c8a32956d7c7943766770c093
|
[
"Apache-2.0"
] | 1
|
2021-11-30T16:16:05.000Z
|
2021-11-30T16:16:05.000Z
|
#include <memory>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/StreamID.h"
#include "L1Trigger/Phase2L1GMT/interface/L1TPhase2GMTEndcapStubProcessor.h"
#include "L1Trigger/Phase2L1GMT/interface/L1TPhase2GMTBarrelStubProcessor.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
#include "FWCore/Framework/interface/ESProducts.h"
#include "FWCore/Utilities/interface/ESGetToken.h"
//
// class declaration
//
class Phase2L1TGMTStubProducer : public edm::stream::EDProducer<> {
public:
explicit Phase2L1TGMTStubProducer(const edm::ParameterSet&);
~Phase2L1TGMTStubProducer() override;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void beginStream(edm::StreamID) override;
void produce(edm::Event&, const edm::EventSetup&) override;
void endStream() override;
edm::EDGetTokenT<MuonDigiCollection<CSCDetId, CSCCorrelatedLCTDigi>> srcCSC_;
edm::EDGetTokenT<L1Phase2MuDTPhContainer> srcDT_;
edm::EDGetTokenT<L1MuDTChambThContainer> srcDTTheta_;
edm::EDGetTokenT<RPCDigiCollection> srcRPC_;
L1TPhase2GMTEndcapStubProcessor* procEndcap_;
L1TPhase2GMTBarrelStubProcessor* procBarrel_;
L1TMuon::GeometryTranslator* translator_;
int verbose_;
};
Phase2L1TGMTStubProducer::Phase2L1TGMTStubProducer(const edm::ParameterSet& iConfig)
: srcCSC_(
consumes<MuonDigiCollection<CSCDetId, CSCCorrelatedLCTDigi>>(iConfig.getParameter<edm::InputTag>("srcCSC"))),
srcDT_(consumes<L1Phase2MuDTPhContainer>(iConfig.getParameter<edm::InputTag>("srcDT"))),
srcDTTheta_(consumes<L1MuDTChambThContainer>(iConfig.getParameter<edm::InputTag>("srcDTTheta"))),
srcRPC_(consumes<RPCDigiCollection>(iConfig.getParameter<edm::InputTag>("srcRPC"))),
procEndcap_(new L1TPhase2GMTEndcapStubProcessor(iConfig.getParameter<edm::ParameterSet>("Endcap"))),
procBarrel_(new L1TPhase2GMTBarrelStubProcessor(iConfig.getParameter<edm::ParameterSet>("Barrel"))),
verbose_(iConfig.getParameter<int>("verbose")) {
produces<l1t::MuonStubCollection>();
edm::ConsumesCollector consumesColl(consumesCollector());
translator_ = new L1TMuon::GeometryTranslator(consumesColl);
}
Phase2L1TGMTStubProducer::~Phase2L1TGMTStubProducer() {
// do anything here that needs to be done at destruction time
// (e.g. close files, deallocate resources etc.)
if (procEndcap_ != nullptr)
delete procEndcap_;
if (procBarrel_ != nullptr)
delete procBarrel_;
if (translator_ != nullptr)
delete translator_;
}
//
// member functions
//
// ------------ method called to produce the data ------------
void Phase2L1TGMTStubProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) {
using namespace edm;
translator_->checkAndUpdateGeometry(iSetup);
Handle<MuonDigiCollection<CSCDetId, CSCCorrelatedLCTDigi>> cscDigis;
iEvent.getByToken(srcCSC_, cscDigis);
Handle<RPCDigiCollection> rpcDigis;
iEvent.getByToken(srcRPC_, rpcDigis);
Handle<L1Phase2MuDTPhContainer> dtDigis;
iEvent.getByToken(srcDT_, dtDigis);
Handle<L1MuDTChambThContainer> dtThetaDigis;
iEvent.getByToken(srcDTTheta_, dtThetaDigis);
//Generate a unique stub ID
l1t::MuonStubCollection stubs;
uint count0 = 0;
uint count1 = 0;
uint count2 = 0;
uint count3 = 0;
uint count4 = 0;
l1t::MuonStubCollection stubsEndcap = procEndcap_->makeStubs(*cscDigis, *rpcDigis, translator_, iSetup);
for (auto& stub : stubsEndcap) {
if (stub.tfLayer() == 0) {
stub.setID(count0);
count0++;
} else if (stub.tfLayer() == 1) {
stub.setID(count1);
count1++;
} else if (stub.tfLayer() == 2) {
stub.setID(count2);
count2++;
} else if (stub.tfLayer() == 3) {
stub.setID(count3);
count3++;
} else {
stub.setID(count4);
count4++;
}
stubs.push_back(stub);
}
l1t::MuonStubCollection stubsBarrel = procBarrel_->makeStubs(dtDigis.product(), dtThetaDigis.product());
for (auto& stub : stubsBarrel) {
if (stub.tfLayer() == 0) {
stub.setID(count0);
count0++;
} else if (stub.tfLayer() == 1) {
stub.setID(count1);
count1++;
} else if (stub.tfLayer() == 2) {
stub.setID(count2);
count2++;
} else if (stub.tfLayer() == 3) {
stub.setID(count3);
count3++;
} else {
stub.setID(count4);
count4++;
}
stubs.push_back(stub);
}
iEvent.put(std::make_unique<l1t::MuonStubCollection>(stubs));
}
// ------------ method called once each stream before processing any runs, lumis or events ------------
void Phase2L1TGMTStubProducer::beginStream(edm::StreamID) {}
// ------------ method called once each stream after processing all runs, lumis and events ------------
void Phase2L1TGMTStubProducer::endStream() {}
void Phase2L1TGMTStubProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
// gmtStubs
edm::ParameterSetDescription desc;
desc.add<int>("verbose", 0);
desc.add<edm::InputTag>("srcCSC", edm::InputTag("simCscTriggerPrimitiveDigis"));
desc.add<edm::InputTag>("srcDT", edm::InputTag("dtTriggerPhase2PrimitiveDigis"));
desc.add<edm::InputTag>("srcDTTheta", edm::InputTag("simDtTriggerPrimitiveDigis"));
desc.add<edm::InputTag>("srcRPC", edm::InputTag("simMuonRPCDigis"));
{
edm::ParameterSetDescription psd0;
psd0.add<unsigned int>("verbose", 0);
psd0.add<int>("minBX", 0);
psd0.add<int>("maxBX", 0);
psd0.add<double>("coord1LSB", 0.02453124992);
psd0.add<double>("eta1LSB", 0.024586688);
psd0.add<double>("coord2LSB", 0.02453124992);
psd0.add<double>("eta2LSB", 0.024586688);
psd0.add<double>("phiMatch", 0.05);
psd0.add<double>("etaMatch", 0.1);
desc.add<edm::ParameterSetDescription>("Endcap", psd0);
}
{
edm::ParameterSetDescription psd0;
psd0.add<int>("verbose", 0);
psd0.add<int>("minPhiQuality", 0);
psd0.add<int>("minThetaQuality", 0);
psd0.add<int>("minBX", 0);
psd0.add<int>("maxBX", 0);
psd0.add<double>("phiLSB", 0.02453124992);
psd0.add<int>("phiBDivider", 16);
psd0.add<double>("etaLSB", 0.024586688);
psd0.add<std::vector<int>>(
"eta_1",
{
-46, -45, -43, -41, -39, -37, -35, -30, -28, -26, -23, -20, -18, -15, -9, -6, -3, -1,
1, 3, 6, 9, 15, 18, 20, 23, 26, 28, 30, 35, 37, 39, 41, 43, 45, 1503,
});
psd0.add<std::vector<int>>(
"eta_2",
{
-41, -39, -38, -36, -34, -32, -30, -26, -24, -22, -20, -18, -15, -13, -8, -5, -3, -1,
1, 3, 5, 8, 13, 15, 18, 20, 22, 24, 26, 30, 32, 34, 36, 38, 39, 1334,
});
psd0.add<std::vector<int>>(
"eta_3",
{
-35, -34, -32, -31, -29, -27, -26, -22, -20, -19, -17, -15, -13, -11, -6, -4, -2, -1,
1, 2, 4, 6, 11, 13, 15, 17, 19, 20, 22, 26, 27, 29, 31, 32, 34, 1148,
});
psd0.add<std::vector<int>>("coarseEta_1",
{
0,
23,
41,
});
psd0.add<std::vector<int>>("coarseEta_2",
{
0,
20,
36,
});
psd0.add<std::vector<int>>("coarseEta_3",
{
0,
17,
31,
});
psd0.add<std::vector<int>>("coarseEta_4",
{
0,
14,
27,
});
psd0.add<std::vector<int>>("phiOffset",
{
1,
0,
0,
0,
});
desc.add<edm::ParameterSetDescription>("Barrel", psd0);
}
descriptions.add("gmtStubs", desc);
}
//define this as a plug-in
DEFINE_FWK_MODULE(Phase2L1TGMTStubProducer);
| 36.172996
| 119
| 0.596991
|
PKUfudawei
|
44d11aca04ecf5e58e8615f2f9c3fd92559abda6
| 5,703
|
cpp
|
C++
|
tsf/src/v20180326/model/CreateLaneRuleRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
tsf/src/v20180326/model/CreateLaneRuleRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
tsf/src/v20180326/model/CreateLaneRuleRequest.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#include <tencentcloud/tsf/v20180326/model/CreateLaneRuleRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tsf::V20180326::Model;
using namespace std;
CreateLaneRuleRequest::CreateLaneRuleRequest() :
m_ruleNameHasBeenSet(false),
m_remarkHasBeenSet(false),
m_ruleTagListHasBeenSet(false),
m_ruleTagRelationshipHasBeenSet(false),
m_laneIdHasBeenSet(false),
m_programIdListHasBeenSet(false)
{
}
string CreateLaneRuleRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_ruleNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_ruleName.c_str(), allocator).Move(), allocator);
}
if (m_remarkHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Remark";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator);
}
if (m_ruleTagListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleTagList";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_ruleTagList.begin(); itr != m_ruleTagList.end(); ++itr, ++i)
{
d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(d[key.c_str()][i], allocator);
}
}
if (m_ruleTagRelationshipHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleTagRelationship";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_ruleTagRelationship.c_str(), allocator).Move(), allocator);
}
if (m_laneIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LaneId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_laneId.c_str(), allocator).Move(), allocator);
}
if (m_programIdListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProgramIdList";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_programIdList.begin(); itr != m_programIdList.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateLaneRuleRequest::GetRuleName() const
{
return m_ruleName;
}
void CreateLaneRuleRequest::SetRuleName(const string& _ruleName)
{
m_ruleName = _ruleName;
m_ruleNameHasBeenSet = true;
}
bool CreateLaneRuleRequest::RuleNameHasBeenSet() const
{
return m_ruleNameHasBeenSet;
}
string CreateLaneRuleRequest::GetRemark() const
{
return m_remark;
}
void CreateLaneRuleRequest::SetRemark(const string& _remark)
{
m_remark = _remark;
m_remarkHasBeenSet = true;
}
bool CreateLaneRuleRequest::RemarkHasBeenSet() const
{
return m_remarkHasBeenSet;
}
vector<LaneRuleTag> CreateLaneRuleRequest::GetRuleTagList() const
{
return m_ruleTagList;
}
void CreateLaneRuleRequest::SetRuleTagList(const vector<LaneRuleTag>& _ruleTagList)
{
m_ruleTagList = _ruleTagList;
m_ruleTagListHasBeenSet = true;
}
bool CreateLaneRuleRequest::RuleTagListHasBeenSet() const
{
return m_ruleTagListHasBeenSet;
}
string CreateLaneRuleRequest::GetRuleTagRelationship() const
{
return m_ruleTagRelationship;
}
void CreateLaneRuleRequest::SetRuleTagRelationship(const string& _ruleTagRelationship)
{
m_ruleTagRelationship = _ruleTagRelationship;
m_ruleTagRelationshipHasBeenSet = true;
}
bool CreateLaneRuleRequest::RuleTagRelationshipHasBeenSet() const
{
return m_ruleTagRelationshipHasBeenSet;
}
string CreateLaneRuleRequest::GetLaneId() const
{
return m_laneId;
}
void CreateLaneRuleRequest::SetLaneId(const string& _laneId)
{
m_laneId = _laneId;
m_laneIdHasBeenSet = true;
}
bool CreateLaneRuleRequest::LaneIdHasBeenSet() const
{
return m_laneIdHasBeenSet;
}
vector<string> CreateLaneRuleRequest::GetProgramIdList() const
{
return m_programIdList;
}
void CreateLaneRuleRequest::SetProgramIdList(const vector<string>& _programIdList)
{
m_programIdList = _programIdList;
m_programIdListHasBeenSet = true;
}
bool CreateLaneRuleRequest::ProgramIdListHasBeenSet() const
{
return m_programIdListHasBeenSet;
}
| 27.550725
| 104
| 0.713835
|
suluner
|
44d30c8845789e7c1a30a6f8f4b3b60bc6640599
| 258
|
cpp
|
C++
|
Kernel/Memory/GenericPagingTable.cpp
|
UltraOS/Ultra
|
287035fea303767285e48e5c7867d147790ff55b
|
[
"Apache-2.0"
] | 44
|
2020-07-09T07:31:43.000Z
|
2022-03-29T20:55:01.000Z
|
Kernel/Memory/GenericPagingTable.cpp
|
8infy/UltraOS
|
2ed2879c96a7095b5077df5ba5db5b30a6565417
|
[
"Apache-2.0"
] | 3
|
2021-04-24T13:53:53.000Z
|
2021-09-27T05:50:28.000Z
|
Kernel/Memory/GenericPagingTable.cpp
|
8infy/UltraOS
|
2ed2879c96a7095b5077df5ba5db5b30a6565417
|
[
"Apache-2.0"
] | 3
|
2021-03-01T09:29:12.000Z
|
2021-06-25T17:06:27.000Z
|
#include "GenericPagingTable.h"
#include "MemoryManager.h"
namespace kernel {
#ifdef ULTRA_64
Address GenericPagingTable::accessible_address_of(size_t index)
{
return MemoryManager::physical_memory_base + entry_at(index).physical_address();
}
#endif
}
| 19.846154
| 84
| 0.794574
|
UltraOS
|
44d3365f13f73e2600d5b70a15dedde1615a9b46
| 9,280
|
cc
|
C++
|
third_party/abseil-cpp/absl/strings/internal/cord_rep_btree_reader_test.cc
|
Antidote/dawn-cmake
|
b8c6d669fa3c0087aa86653a4078386ffb42f199
|
[
"BSD-3-Clause"
] | 1
|
2021-12-25T05:54:09.000Z
|
2021-12-25T05:54:09.000Z
|
third_party/abseil-cpp/absl/strings/internal/cord_rep_btree_reader_test.cc
|
Antidote/dawn-cmake
|
b8c6d669fa3c0087aa86653a4078386ffb42f199
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/abseil-cpp/absl/strings/internal/cord_rep_btree_reader_test.cc
|
Antidote/dawn-cmake
|
b8c6d669fa3c0087aa86653a4078386ffb42f199
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2021 The Abseil 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
//
// https://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 "absl/strings/internal/cord_rep_btree_reader.h"
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/strings/cord.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_test_util.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Ne;
using ::testing::Not;
using ::absl::cordrep_testing::CordRepBtreeFromFlats;
using ::absl::cordrep_testing::MakeFlat;
using ::absl::cordrep_testing::CordToString;
using ::absl::cordrep_testing::CreateFlatsFromString;
using ::absl::cordrep_testing::CreateRandomString;
using ReadResult = CordRepBtreeReader::ReadResult;
TEST(CordRepBtreeReaderTest, Next) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
CordRepBtreeReader reader;
absl::string_view chunk = reader.Init(node);
EXPECT_THAT(chunk, Eq(data.substr(0, chunk.length())));
size_t consumed = chunk.length();
EXPECT_THAT(reader.consumed(), Eq(consumed));
while (consumed < data.length()) {
chunk = reader.Next();
EXPECT_THAT(chunk, Eq(data.substr(consumed, chunk.length())));
consumed += chunk.length();
EXPECT_THAT(reader.consumed(), Eq(consumed));
}
EXPECT_THAT(consumed, Eq(data.length()));
EXPECT_THAT(reader.consumed(), Eq(data.length()));
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, Skip) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t skip1 = 0; skip1 < data.length() - kChars; ++skip1) {
for (size_t skip2 = 0; skip2 < data.length() - kChars; ++skip2) {
CordRepBtreeReader reader;
absl::string_view chunk = reader.Init(node);
size_t consumed = chunk.length();
chunk = reader.Skip(skip1);
ASSERT_THAT(chunk, Eq(data.substr(consumed + skip1, chunk.length())));
consumed += chunk.length() + skip1;
ASSERT_THAT(reader.consumed(), Eq(consumed));
if (consumed >= data.length()) continue;
size_t skip = std::min(data.length() - consumed - 1, skip2);
chunk = reader.Skip(skip);
ASSERT_THAT(chunk, Eq(data.substr(consumed + skip, chunk.length())));
}
}
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, SkipBeyondLength) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
tree = CordRepBtree::Append(tree, MakeFlat("def"));
CordRepBtreeReader reader;
reader.Init(tree);
EXPECT_THAT(reader.Skip(100), IsEmpty());
EXPECT_THAT(reader.consumed(), Eq(6));
CordRep::Unref(tree);
}
TEST(CordRepBtreeReaderTest, Seek) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t seek = 0; seek < data.length() - 1; ++seek) {
CordRepBtreeReader reader;
reader.Init(node);
absl::string_view chunk = reader.Seek(seek);
ASSERT_THAT(chunk, Not(IsEmpty()));
ASSERT_THAT(chunk, Eq(data.substr(seek, chunk.length())));
ASSERT_THAT(reader.consumed(), Eq(seek + chunk.length()));
}
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, SeekBeyondLength) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
tree = CordRepBtree::Append(tree, MakeFlat("def"));
CordRepBtreeReader reader;
reader.Init(tree);
EXPECT_THAT(reader.Seek(6), IsEmpty());
EXPECT_THAT(reader.consumed(), Eq(6));
EXPECT_THAT(reader.Seek(100), IsEmpty());
EXPECT_THAT(reader.consumed(), Eq(6));
CordRep::Unref(tree);
}
TEST(CordRepBtreeReaderTest, Read) {
std::string data = "abcdefghijklmno";
std::vector<CordRep*> flats = CreateFlatsFromString(data, 5);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
CordRep* tree;
CordRepBtreeReader reader;
absl::string_view chunk;
// Read zero bytes
chunk = reader.Init(node);
chunk = reader.Read(0, chunk.length(), tree);
EXPECT_THAT(tree, Eq(nullptr));
EXPECT_THAT(chunk, Eq("abcde"));
EXPECT_THAT(reader.consumed(), Eq(5));
EXPECT_THAT(reader.Next(), Eq("fghij"));
// Read in full
chunk = reader.Init(node);
chunk = reader.Read(15, chunk.length(), tree);
EXPECT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("abcdefghijklmno"));
EXPECT_THAT(chunk, Eq(""));
EXPECT_THAT(reader.consumed(), Eq(15));
CordRep::Unref(tree);
// Read < chunk bytes
chunk = reader.Init(node);
chunk = reader.Read(3, chunk.length(), tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("abc"));
EXPECT_THAT(chunk, Eq("de"));
EXPECT_THAT(reader.consumed(), Eq(5));
EXPECT_THAT(reader.Next(), Eq("fghij"));
CordRep::Unref(tree);
// Read < chunk bytes at offset
chunk = reader.Init(node);
chunk = reader.Read(2, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cd"));
EXPECT_THAT(chunk, Eq("e"));
EXPECT_THAT(reader.consumed(), Eq(5));
EXPECT_THAT(reader.Next(), Eq("fghij"));
CordRep::Unref(tree);
// Read from consumed chunk
chunk = reader.Init(node);
chunk = reader.Read(3, 0, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("fgh"));
EXPECT_THAT(chunk, Eq("ij"));
EXPECT_THAT(reader.consumed(), Eq(10));
EXPECT_THAT(reader.Next(), Eq("klmno"));
CordRep::Unref(tree);
// Read across chunks
chunk = reader.Init(node);
chunk = reader.Read(12, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cdefghijklmn"));
EXPECT_THAT(chunk, Eq("o"));
EXPECT_THAT(reader.consumed(), Eq(15));
CordRep::Unref(tree);
// Read across chunks landing on exact edge boundary
chunk = reader.Init(node);
chunk = reader.Read(10 - 2, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cdefghij"));
EXPECT_THAT(chunk, Eq("klmno"));
EXPECT_THAT(reader.consumed(), Eq(15));
CordRep::Unref(tree);
CordRep::Unref(node);
}
TEST(CordRepBtreeReaderTest, ReadExhaustive) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap + 1, cap * cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t read_size : {kChars - 1, kChars, kChars + 7, cap * cap}) {
CordRepBtreeReader reader;
absl::string_view chunk = reader.Init(node);
// `consumed` tracks the end of last consumed chunk which is the start of
// the next chunk: we always read with `chunk_size = chunk.length()`.
size_t consumed = 0;
size_t remaining = data.length();
while (remaining > 0) {
CordRep* tree;
size_t n = (std::min)(remaining, read_size);
chunk = reader.Read(n, chunk.length(), tree);
EXPECT_THAT(tree, Ne(nullptr));
if (tree) {
EXPECT_THAT(CordToString(tree), Eq(data.substr(consumed, n)));
CordRep::Unref(tree);
}
consumed += n;
remaining -= n;
EXPECT_THAT(reader.consumed(), Eq(consumed + chunk.length()));
if (remaining > 0) {
ASSERT_FALSE(chunk.empty());
ASSERT_THAT(chunk, Eq(data.substr(consumed, chunk.length())));
} else {
ASSERT_TRUE(chunk.empty()) << chunk;
}
}
}
CordRep::Unref(node);
}
}
} // namespace
} // namespace cord_internal
ABSL_NAMESPACE_END
} // namespace absl
| 32.447552
| 79
| 0.671013
|
Antidote
|
44d41cf17e0a436311f4dc84aac84ff2a88353bb
| 4,020
|
cpp
|
C++
|
third_party/libigl/include/igl/vertex_components.cpp
|
chefmramos85/monster-mash
|
239a41f6f178ca83c4be638331e32f23606b0381
|
[
"Apache-2.0"
] | 1,125
|
2021-02-01T09:51:56.000Z
|
2022-03-31T01:50:40.000Z
|
third_party/libigl/include/igl/vertex_components.cpp
|
ryan-cranfill/monster-mash
|
c1b906d996885f8a4011bdf7558e62e968e1e914
|
[
"Apache-2.0"
] | 19
|
2021-02-01T12:36:30.000Z
|
2022-03-19T14:02:50.000Z
|
third_party/libigl/include/igl/vertex_components.cpp
|
ryan-cranfill/monster-mash
|
c1b906d996885f8a4011bdf7558e62e968e1e914
|
[
"Apache-2.0"
] | 148
|
2021-02-13T10:54:31.000Z
|
2022-03-28T11:55:20.000Z
|
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "vertex_components.h"
#include "adjacency_matrix.h"
#include <queue>
#include <vector>
template <typename DerivedA, typename DerivedC, typename Derivedcounts>
IGL_INLINE void igl::vertex_components(
const Eigen::SparseCompressedBase<DerivedA> & A,
Eigen::PlainObjectBase<DerivedC> & C,
Eigen::PlainObjectBase<Derivedcounts> & counts)
{
using namespace Eigen;
using namespace std;
assert(A.rows() == A.cols() && "A should be square.");
const size_t n = A.rows();
Array<bool,Dynamic,1> seen = Array<bool,Dynamic,1>::Zero(n,1);
C.resize(n,1);
typename DerivedC::Scalar id = 0;
vector<typename Derivedcounts::Scalar> vcounts;
// breadth first search
for(int k=0; k<A.outerSize(); ++k)
{
if(seen(k))
{
continue;
}
queue<int> Q;
Q.push(k);
vcounts.push_back(0);
while(!Q.empty())
{
const int f = Q.front();
Q.pop();
if(seen(f))
{
continue;
}
seen(f) = true;
C(f,0) = id;
vcounts[id]++;
// Iterate over inside
for(typename DerivedA::InnerIterator it (A,f); it; ++it)
{
const int g = it.index();
if(!seen(g) && it.value())
{
Q.push(g);
}
}
}
id++;
}
assert((size_t) id == vcounts.size());
const size_t ncc = vcounts.size();
assert((size_t)C.maxCoeff()+1 == ncc);
counts.resize(ncc,1);
for(size_t i = 0;i<ncc;i++)
{
counts(i) = vcounts[i];
}
}
template <typename DerivedA, typename DerivedC>
IGL_INLINE void igl::vertex_components(
const Eigen::SparseCompressedBase<DerivedA> & A,
Eigen::PlainObjectBase<DerivedC> & C)
{
Eigen::VectorXi counts;
return vertex_components(A,C,counts);
}
template <typename DerivedF, typename DerivedC>
IGL_INLINE void igl::vertex_components(
const Eigen::MatrixBase<DerivedF> & F,
Eigen::PlainObjectBase<DerivedC> & C)
{
Eigen::SparseMatrix<typename DerivedC::Scalar> A;
adjacency_matrix(F,A);
return vertex_components(A,C);
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
template void igl::vertex_components<Eigen::SparseMatrix<bool, 0, int>, Eigen::Array<int, -1, 1, 0, -1, 1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<bool, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Array<int, -1, 1, 0, -1, 1> >&);
template void igl::vertex_components<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::vertex_components<Eigen::SparseMatrix<int, 0, int>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<int, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::vertex_components<Eigen::SparseMatrix<int, 0, int>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<int, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
template void igl::vertex_components<Eigen::SparseMatrix<double, 0, int>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<double, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
template void igl::vertex_components<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
#endif
| 40.606061
| 356
| 0.650498
|
chefmramos85
|
44d539162d25a56d73e0a8e5b839698853ae1d18
| 52,948
|
cc
|
C++
|
ui/gl/gl_bindings_autogen_glx.cc
|
zipated/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 2,151
|
2020-04-18T07:31:17.000Z
|
2022-03-31T08:39:18.000Z
|
ui/gl/gl_bindings_autogen_glx.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 395
|
2020-04-18T08:22:18.000Z
|
2021-12-08T13:04:49.000Z
|
ui/gl/gl_bindings_autogen_glx.cc
|
cangulcan/src
|
2b8388091c71e442910a21ada3d97ae8bc1845d3
|
[
"BSD-3-Clause"
] | 338
|
2020-04-18T08:03:10.000Z
|
2022-03-29T12:33:22.000Z
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file is auto-generated from
// ui/gl/generate_bindings.py
// It's formatted by clang-format using chromium coding style:
// clang-format -i -style=chromium filename
// DO NOT EDIT!
#include <string>
#include "base/trace_event/trace_event.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_enums.h"
#include "ui/gl/gl_glx_api_implementation.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_version_info.h"
namespace gl {
DriverGLX g_driver_glx; // Exists in .bss
void DriverGLX::InitializeStaticBindings() {
// Ensure struct has been zero-initialized.
char* this_bytes = reinterpret_cast<char*>(this);
DCHECK(this_bytes[0] == 0);
DCHECK(memcmp(this_bytes, this_bytes + 1, sizeof(*this) - 1) == 0);
fn.glXChooseFBConfigFn = reinterpret_cast<glXChooseFBConfigProc>(
GetGLProcAddress("glXChooseFBConfig"));
fn.glXChooseVisualFn = reinterpret_cast<glXChooseVisualProc>(
GetGLProcAddress("glXChooseVisual"));
fn.glXCopyContextFn =
reinterpret_cast<glXCopyContextProc>(GetGLProcAddress("glXCopyContext"));
fn.glXCreateContextFn = reinterpret_cast<glXCreateContextProc>(
GetGLProcAddress("glXCreateContext"));
fn.glXCreateGLXPixmapFn = reinterpret_cast<glXCreateGLXPixmapProc>(
GetGLProcAddress("glXCreateGLXPixmap"));
fn.glXCreateNewContextFn = reinterpret_cast<glXCreateNewContextProc>(
GetGLProcAddress("glXCreateNewContext"));
fn.glXCreatePbufferFn = reinterpret_cast<glXCreatePbufferProc>(
GetGLProcAddress("glXCreatePbuffer"));
fn.glXCreatePixmapFn = reinterpret_cast<glXCreatePixmapProc>(
GetGLProcAddress("glXCreatePixmap"));
fn.glXCreateWindowFn = reinterpret_cast<glXCreateWindowProc>(
GetGLProcAddress("glXCreateWindow"));
fn.glXDestroyContextFn = reinterpret_cast<glXDestroyContextProc>(
GetGLProcAddress("glXDestroyContext"));
fn.glXDestroyGLXPixmapFn = reinterpret_cast<glXDestroyGLXPixmapProc>(
GetGLProcAddress("glXDestroyGLXPixmap"));
fn.glXDestroyPbufferFn = reinterpret_cast<glXDestroyPbufferProc>(
GetGLProcAddress("glXDestroyPbuffer"));
fn.glXDestroyPixmapFn = reinterpret_cast<glXDestroyPixmapProc>(
GetGLProcAddress("glXDestroyPixmap"));
fn.glXDestroyWindowFn = reinterpret_cast<glXDestroyWindowProc>(
GetGLProcAddress("glXDestroyWindow"));
fn.glXGetClientStringFn = reinterpret_cast<glXGetClientStringProc>(
GetGLProcAddress("glXGetClientString"));
fn.glXGetConfigFn =
reinterpret_cast<glXGetConfigProc>(GetGLProcAddress("glXGetConfig"));
fn.glXGetCurrentContextFn = reinterpret_cast<glXGetCurrentContextProc>(
GetGLProcAddress("glXGetCurrentContext"));
fn.glXGetCurrentDisplayFn = reinterpret_cast<glXGetCurrentDisplayProc>(
GetGLProcAddress("glXGetCurrentDisplay"));
fn.glXGetCurrentDrawableFn = reinterpret_cast<glXGetCurrentDrawableProc>(
GetGLProcAddress("glXGetCurrentDrawable"));
fn.glXGetCurrentReadDrawableFn =
reinterpret_cast<glXGetCurrentReadDrawableProc>(
GetGLProcAddress("glXGetCurrentReadDrawable"));
fn.glXGetFBConfigAttribFn = reinterpret_cast<glXGetFBConfigAttribProc>(
GetGLProcAddress("glXGetFBConfigAttrib"));
fn.glXGetFBConfigsFn = reinterpret_cast<glXGetFBConfigsProc>(
GetGLProcAddress("glXGetFBConfigs"));
fn.glXGetSelectedEventFn = reinterpret_cast<glXGetSelectedEventProc>(
GetGLProcAddress("glXGetSelectedEvent"));
fn.glXGetVisualFromFBConfigFn =
reinterpret_cast<glXGetVisualFromFBConfigProc>(
GetGLProcAddress("glXGetVisualFromFBConfig"));
fn.glXIsDirectFn =
reinterpret_cast<glXIsDirectProc>(GetGLProcAddress("glXIsDirect"));
fn.glXMakeContextCurrentFn = reinterpret_cast<glXMakeContextCurrentProc>(
GetGLProcAddress("glXMakeContextCurrent"));
fn.glXMakeCurrentFn =
reinterpret_cast<glXMakeCurrentProc>(GetGLProcAddress("glXMakeCurrent"));
fn.glXQueryContextFn = reinterpret_cast<glXQueryContextProc>(
GetGLProcAddress("glXQueryContext"));
fn.glXQueryDrawableFn = reinterpret_cast<glXQueryDrawableProc>(
GetGLProcAddress("glXQueryDrawable"));
fn.glXQueryExtensionFn = reinterpret_cast<glXQueryExtensionProc>(
GetGLProcAddress("glXQueryExtension"));
fn.glXQueryExtensionsStringFn =
reinterpret_cast<glXQueryExtensionsStringProc>(
GetGLProcAddress("glXQueryExtensionsString"));
fn.glXQueryServerStringFn = reinterpret_cast<glXQueryServerStringProc>(
GetGLProcAddress("glXQueryServerString"));
fn.glXQueryVersionFn = reinterpret_cast<glXQueryVersionProc>(
GetGLProcAddress("glXQueryVersion"));
fn.glXSelectEventFn =
reinterpret_cast<glXSelectEventProc>(GetGLProcAddress("glXSelectEvent"));
fn.glXSwapBuffersFn =
reinterpret_cast<glXSwapBuffersProc>(GetGLProcAddress("glXSwapBuffers"));
fn.glXUseXFontFn =
reinterpret_cast<glXUseXFontProc>(GetGLProcAddress("glXUseXFont"));
fn.glXWaitGLFn =
reinterpret_cast<glXWaitGLProc>(GetGLProcAddress("glXWaitGL"));
fn.glXWaitXFn = reinterpret_cast<glXWaitXProc>(GetGLProcAddress("glXWaitX"));
}
void DriverGLX::InitializeExtensionBindings() {
std::string platform_extensions(GetPlatformExtensions());
ExtensionSet extensions(MakeExtensionSet(platform_extensions));
ALLOW_UNUSED_LOCAL(extensions);
ext.b_GLX_ARB_create_context =
HasExtension(extensions, "GLX_ARB_create_context");
ext.b_GLX_EXT_swap_control = HasExtension(extensions, "GLX_EXT_swap_control");
ext.b_GLX_EXT_texture_from_pixmap =
HasExtension(extensions, "GLX_EXT_texture_from_pixmap");
ext.b_GLX_MESA_copy_sub_buffer =
HasExtension(extensions, "GLX_MESA_copy_sub_buffer");
ext.b_GLX_MESA_swap_control =
HasExtension(extensions, "GLX_MESA_swap_control");
ext.b_GLX_OML_sync_control = HasExtension(extensions, "GLX_OML_sync_control");
ext.b_GLX_SGIX_fbconfig = HasExtension(extensions, "GLX_SGIX_fbconfig");
ext.b_GLX_SGI_video_sync = HasExtension(extensions, "GLX_SGI_video_sync");
if (ext.b_GLX_EXT_texture_from_pixmap) {
fn.glXBindTexImageEXTFn = reinterpret_cast<glXBindTexImageEXTProc>(
GetGLProcAddress("glXBindTexImageEXT"));
}
if (ext.b_GLX_MESA_copy_sub_buffer) {
fn.glXCopySubBufferMESAFn = reinterpret_cast<glXCopySubBufferMESAProc>(
GetGLProcAddress("glXCopySubBufferMESA"));
}
if (ext.b_GLX_ARB_create_context) {
fn.glXCreateContextAttribsARBFn =
reinterpret_cast<glXCreateContextAttribsARBProc>(
GetGLProcAddress("glXCreateContextAttribsARB"));
}
if (ext.b_GLX_SGIX_fbconfig) {
fn.glXGetFBConfigFromVisualSGIXFn =
reinterpret_cast<glXGetFBConfigFromVisualSGIXProc>(
GetGLProcAddress("glXGetFBConfigFromVisualSGIX"));
}
if (ext.b_GLX_OML_sync_control) {
fn.glXGetMscRateOMLFn = reinterpret_cast<glXGetMscRateOMLProc>(
GetGLProcAddress("glXGetMscRateOML"));
}
if (ext.b_GLX_OML_sync_control) {
fn.glXGetSyncValuesOMLFn = reinterpret_cast<glXGetSyncValuesOMLProc>(
GetGLProcAddress("glXGetSyncValuesOML"));
}
if (ext.b_GLX_EXT_texture_from_pixmap) {
fn.glXReleaseTexImageEXTFn = reinterpret_cast<glXReleaseTexImageEXTProc>(
GetGLProcAddress("glXReleaseTexImageEXT"));
}
if (ext.b_GLX_EXT_swap_control) {
fn.glXSwapIntervalEXTFn = reinterpret_cast<glXSwapIntervalEXTProc>(
GetGLProcAddress("glXSwapIntervalEXT"));
}
if (ext.b_GLX_MESA_swap_control) {
fn.glXSwapIntervalMESAFn = reinterpret_cast<glXSwapIntervalMESAProc>(
GetGLProcAddress("glXSwapIntervalMESA"));
}
if (ext.b_GLX_SGI_video_sync) {
fn.glXWaitVideoSyncSGIFn = reinterpret_cast<glXWaitVideoSyncSGIProc>(
GetGLProcAddress("glXWaitVideoSyncSGI"));
}
}
void DriverGLX::ClearBindings() {
memset(this, 0, sizeof(*this));
}
void GLXApiBase::glXBindTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer,
int* attribList) {
driver_->fn.glXBindTexImageEXTFn(dpy, drawable, buffer, attribList);
}
GLXFBConfig* GLXApiBase::glXChooseFBConfigFn(Display* dpy,
int screen,
const int* attribList,
int* nitems) {
return driver_->fn.glXChooseFBConfigFn(dpy, screen, attribList, nitems);
}
XVisualInfo* GLXApiBase::glXChooseVisualFn(Display* dpy,
int screen,
int* attribList) {
return driver_->fn.glXChooseVisualFn(dpy, screen, attribList);
}
void GLXApiBase::glXCopyContextFn(Display* dpy,
GLXContext src,
GLXContext dst,
unsigned long mask) {
driver_->fn.glXCopyContextFn(dpy, src, dst, mask);
}
void GLXApiBase::glXCopySubBufferMESAFn(Display* dpy,
GLXDrawable drawable,
int x,
int y,
int width,
int height) {
driver_->fn.glXCopySubBufferMESAFn(dpy, drawable, x, y, width, height);
}
GLXContext GLXApiBase::glXCreateContextFn(Display* dpy,
XVisualInfo* vis,
GLXContext shareList,
int direct) {
return driver_->fn.glXCreateContextFn(dpy, vis, shareList, direct);
}
GLXContext GLXApiBase::glXCreateContextAttribsARBFn(Display* dpy,
GLXFBConfig config,
GLXContext share_context,
int direct,
const int* attrib_list) {
return driver_->fn.glXCreateContextAttribsARBFn(dpy, config, share_context,
direct, attrib_list);
}
GLXPixmap GLXApiBase::glXCreateGLXPixmapFn(Display* dpy,
XVisualInfo* visual,
Pixmap pixmap) {
return driver_->fn.glXCreateGLXPixmapFn(dpy, visual, pixmap);
}
GLXContext GLXApiBase::glXCreateNewContextFn(Display* dpy,
GLXFBConfig config,
int renderType,
GLXContext shareList,
int direct) {
return driver_->fn.glXCreateNewContextFn(dpy, config, renderType, shareList,
direct);
}
GLXPbuffer GLXApiBase::glXCreatePbufferFn(Display* dpy,
GLXFBConfig config,
const int* attribList) {
return driver_->fn.glXCreatePbufferFn(dpy, config, attribList);
}
GLXPixmap GLXApiBase::glXCreatePixmapFn(Display* dpy,
GLXFBConfig config,
Pixmap pixmap,
const int* attribList) {
return driver_->fn.glXCreatePixmapFn(dpy, config, pixmap, attribList);
}
GLXWindow GLXApiBase::glXCreateWindowFn(Display* dpy,
GLXFBConfig config,
Window win,
const int* attribList) {
return driver_->fn.glXCreateWindowFn(dpy, config, win, attribList);
}
void GLXApiBase::glXDestroyContextFn(Display* dpy, GLXContext ctx) {
driver_->fn.glXDestroyContextFn(dpy, ctx);
}
void GLXApiBase::glXDestroyGLXPixmapFn(Display* dpy, GLXPixmap pixmap) {
driver_->fn.glXDestroyGLXPixmapFn(dpy, pixmap);
}
void GLXApiBase::glXDestroyPbufferFn(Display* dpy, GLXPbuffer pbuf) {
driver_->fn.glXDestroyPbufferFn(dpy, pbuf);
}
void GLXApiBase::glXDestroyPixmapFn(Display* dpy, GLXPixmap pixmap) {
driver_->fn.glXDestroyPixmapFn(dpy, pixmap);
}
void GLXApiBase::glXDestroyWindowFn(Display* dpy, GLXWindow window) {
driver_->fn.glXDestroyWindowFn(dpy, window);
}
const char* GLXApiBase::glXGetClientStringFn(Display* dpy, int name) {
return driver_->fn.glXGetClientStringFn(dpy, name);
}
int GLXApiBase::glXGetConfigFn(Display* dpy,
XVisualInfo* visual,
int attrib,
int* value) {
return driver_->fn.glXGetConfigFn(dpy, visual, attrib, value);
}
GLXContext GLXApiBase::glXGetCurrentContextFn(void) {
return driver_->fn.glXGetCurrentContextFn();
}
Display* GLXApiBase::glXGetCurrentDisplayFn(void) {
return driver_->fn.glXGetCurrentDisplayFn();
}
GLXDrawable GLXApiBase::glXGetCurrentDrawableFn(void) {
return driver_->fn.glXGetCurrentDrawableFn();
}
GLXDrawable GLXApiBase::glXGetCurrentReadDrawableFn(void) {
return driver_->fn.glXGetCurrentReadDrawableFn();
}
int GLXApiBase::glXGetFBConfigAttribFn(Display* dpy,
GLXFBConfig config,
int attribute,
int* value) {
return driver_->fn.glXGetFBConfigAttribFn(dpy, config, attribute, value);
}
GLXFBConfig GLXApiBase::glXGetFBConfigFromVisualSGIXFn(
Display* dpy,
XVisualInfo* visualInfo) {
return driver_->fn.glXGetFBConfigFromVisualSGIXFn(dpy, visualInfo);
}
GLXFBConfig* GLXApiBase::glXGetFBConfigsFn(Display* dpy,
int screen,
int* nelements) {
return driver_->fn.glXGetFBConfigsFn(dpy, screen, nelements);
}
bool GLXApiBase::glXGetMscRateOMLFn(Display* dpy,
GLXDrawable drawable,
int32_t* numerator,
int32_t* denominator) {
return driver_->fn.glXGetMscRateOMLFn(dpy, drawable, numerator, denominator);
}
void GLXApiBase::glXGetSelectedEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long* mask) {
driver_->fn.glXGetSelectedEventFn(dpy, drawable, mask);
}
bool GLXApiBase::glXGetSyncValuesOMLFn(Display* dpy,
GLXDrawable drawable,
int64_t* ust,
int64_t* msc,
int64_t* sbc) {
return driver_->fn.glXGetSyncValuesOMLFn(dpy, drawable, ust, msc, sbc);
}
XVisualInfo* GLXApiBase::glXGetVisualFromFBConfigFn(Display* dpy,
GLXFBConfig config) {
return driver_->fn.glXGetVisualFromFBConfigFn(dpy, config);
}
int GLXApiBase::glXIsDirectFn(Display* dpy, GLXContext ctx) {
return driver_->fn.glXIsDirectFn(dpy, ctx);
}
int GLXApiBase::glXMakeContextCurrentFn(Display* dpy,
GLXDrawable draw,
GLXDrawable read,
GLXContext ctx) {
return driver_->fn.glXMakeContextCurrentFn(dpy, draw, read, ctx);
}
int GLXApiBase::glXMakeCurrentFn(Display* dpy,
GLXDrawable drawable,
GLXContext ctx) {
return driver_->fn.glXMakeCurrentFn(dpy, drawable, ctx);
}
int GLXApiBase::glXQueryContextFn(Display* dpy,
GLXContext ctx,
int attribute,
int* value) {
return driver_->fn.glXQueryContextFn(dpy, ctx, attribute, value);
}
void GLXApiBase::glXQueryDrawableFn(Display* dpy,
GLXDrawable draw,
int attribute,
unsigned int* value) {
driver_->fn.glXQueryDrawableFn(dpy, draw, attribute, value);
}
int GLXApiBase::glXQueryExtensionFn(Display* dpy, int* errorb, int* event) {
return driver_->fn.glXQueryExtensionFn(dpy, errorb, event);
}
const char* GLXApiBase::glXQueryExtensionsStringFn(Display* dpy, int screen) {
return driver_->fn.glXQueryExtensionsStringFn(dpy, screen);
}
const char* GLXApiBase::glXQueryServerStringFn(Display* dpy,
int screen,
int name) {
return driver_->fn.glXQueryServerStringFn(dpy, screen, name);
}
int GLXApiBase::glXQueryVersionFn(Display* dpy, int* maj, int* min) {
return driver_->fn.glXQueryVersionFn(dpy, maj, min);
}
void GLXApiBase::glXReleaseTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer) {
driver_->fn.glXReleaseTexImageEXTFn(dpy, drawable, buffer);
}
void GLXApiBase::glXSelectEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long mask) {
driver_->fn.glXSelectEventFn(dpy, drawable, mask);
}
void GLXApiBase::glXSwapBuffersFn(Display* dpy, GLXDrawable drawable) {
driver_->fn.glXSwapBuffersFn(dpy, drawable);
}
void GLXApiBase::glXSwapIntervalEXTFn(Display* dpy,
GLXDrawable drawable,
int interval) {
driver_->fn.glXSwapIntervalEXTFn(dpy, drawable, interval);
}
void GLXApiBase::glXSwapIntervalMESAFn(unsigned int interval) {
driver_->fn.glXSwapIntervalMESAFn(interval);
}
void GLXApiBase::glXUseXFontFn(Font font, int first, int count, int list) {
driver_->fn.glXUseXFontFn(font, first, count, list);
}
void GLXApiBase::glXWaitGLFn(void) {
driver_->fn.glXWaitGLFn();
}
int GLXApiBase::glXWaitVideoSyncSGIFn(int divisor,
int remainder,
unsigned int* count) {
return driver_->fn.glXWaitVideoSyncSGIFn(divisor, remainder, count);
}
void GLXApiBase::glXWaitXFn(void) {
driver_->fn.glXWaitXFn();
}
void TraceGLXApi::glXBindTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer,
int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXBindTexImageEXT")
glx_api_->glXBindTexImageEXTFn(dpy, drawable, buffer, attribList);
}
GLXFBConfig* TraceGLXApi::glXChooseFBConfigFn(Display* dpy,
int screen,
const int* attribList,
int* nitems) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXChooseFBConfig")
return glx_api_->glXChooseFBConfigFn(dpy, screen, attribList, nitems);
}
XVisualInfo* TraceGLXApi::glXChooseVisualFn(Display* dpy,
int screen,
int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXChooseVisual")
return glx_api_->glXChooseVisualFn(dpy, screen, attribList);
}
void TraceGLXApi::glXCopyContextFn(Display* dpy,
GLXContext src,
GLXContext dst,
unsigned long mask) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCopyContext")
glx_api_->glXCopyContextFn(dpy, src, dst, mask);
}
void TraceGLXApi::glXCopySubBufferMESAFn(Display* dpy,
GLXDrawable drawable,
int x,
int y,
int width,
int height) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCopySubBufferMESA")
glx_api_->glXCopySubBufferMESAFn(dpy, drawable, x, y, width, height);
}
GLXContext TraceGLXApi::glXCreateContextFn(Display* dpy,
XVisualInfo* vis,
GLXContext shareList,
int direct) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateContext")
return glx_api_->glXCreateContextFn(dpy, vis, shareList, direct);
}
GLXContext TraceGLXApi::glXCreateContextAttribsARBFn(Display* dpy,
GLXFBConfig config,
GLXContext share_context,
int direct,
const int* attrib_list) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateContextAttribsARB")
return glx_api_->glXCreateContextAttribsARBFn(dpy, config, share_context,
direct, attrib_list);
}
GLXPixmap TraceGLXApi::glXCreateGLXPixmapFn(Display* dpy,
XVisualInfo* visual,
Pixmap pixmap) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateGLXPixmap")
return glx_api_->glXCreateGLXPixmapFn(dpy, visual, pixmap);
}
GLXContext TraceGLXApi::glXCreateNewContextFn(Display* dpy,
GLXFBConfig config,
int renderType,
GLXContext shareList,
int direct) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateNewContext")
return glx_api_->glXCreateNewContextFn(dpy, config, renderType, shareList,
direct);
}
GLXPbuffer TraceGLXApi::glXCreatePbufferFn(Display* dpy,
GLXFBConfig config,
const int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreatePbuffer")
return glx_api_->glXCreatePbufferFn(dpy, config, attribList);
}
GLXPixmap TraceGLXApi::glXCreatePixmapFn(Display* dpy,
GLXFBConfig config,
Pixmap pixmap,
const int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreatePixmap")
return glx_api_->glXCreatePixmapFn(dpy, config, pixmap, attribList);
}
GLXWindow TraceGLXApi::glXCreateWindowFn(Display* dpy,
GLXFBConfig config,
Window win,
const int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateWindow")
return glx_api_->glXCreateWindowFn(dpy, config, win, attribList);
}
void TraceGLXApi::glXDestroyContextFn(Display* dpy, GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyContext")
glx_api_->glXDestroyContextFn(dpy, ctx);
}
void TraceGLXApi::glXDestroyGLXPixmapFn(Display* dpy, GLXPixmap pixmap) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyGLXPixmap")
glx_api_->glXDestroyGLXPixmapFn(dpy, pixmap);
}
void TraceGLXApi::glXDestroyPbufferFn(Display* dpy, GLXPbuffer pbuf) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyPbuffer")
glx_api_->glXDestroyPbufferFn(dpy, pbuf);
}
void TraceGLXApi::glXDestroyPixmapFn(Display* dpy, GLXPixmap pixmap) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyPixmap")
glx_api_->glXDestroyPixmapFn(dpy, pixmap);
}
void TraceGLXApi::glXDestroyWindowFn(Display* dpy, GLXWindow window) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyWindow")
glx_api_->glXDestroyWindowFn(dpy, window);
}
const char* TraceGLXApi::glXGetClientStringFn(Display* dpy, int name) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetClientString")
return glx_api_->glXGetClientStringFn(dpy, name);
}
int TraceGLXApi::glXGetConfigFn(Display* dpy,
XVisualInfo* visual,
int attrib,
int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetConfig")
return glx_api_->glXGetConfigFn(dpy, visual, attrib, value);
}
GLXContext TraceGLXApi::glXGetCurrentContextFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentContext")
return glx_api_->glXGetCurrentContextFn();
}
Display* TraceGLXApi::glXGetCurrentDisplayFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentDisplay")
return glx_api_->glXGetCurrentDisplayFn();
}
GLXDrawable TraceGLXApi::glXGetCurrentDrawableFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentDrawable")
return glx_api_->glXGetCurrentDrawableFn();
}
GLXDrawable TraceGLXApi::glXGetCurrentReadDrawableFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentReadDrawable")
return glx_api_->glXGetCurrentReadDrawableFn();
}
int TraceGLXApi::glXGetFBConfigAttribFn(Display* dpy,
GLXFBConfig config,
int attribute,
int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetFBConfigAttrib")
return glx_api_->glXGetFBConfigAttribFn(dpy, config, attribute, value);
}
GLXFBConfig TraceGLXApi::glXGetFBConfigFromVisualSGIXFn(
Display* dpy,
XVisualInfo* visualInfo) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu",
"TraceGLAPI::glXGetFBConfigFromVisualSGIX")
return glx_api_->glXGetFBConfigFromVisualSGIXFn(dpy, visualInfo);
}
GLXFBConfig* TraceGLXApi::glXGetFBConfigsFn(Display* dpy,
int screen,
int* nelements) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetFBConfigs")
return glx_api_->glXGetFBConfigsFn(dpy, screen, nelements);
}
bool TraceGLXApi::glXGetMscRateOMLFn(Display* dpy,
GLXDrawable drawable,
int32_t* numerator,
int32_t* denominator) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetMscRateOML")
return glx_api_->glXGetMscRateOMLFn(dpy, drawable, numerator, denominator);
}
void TraceGLXApi::glXGetSelectedEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long* mask) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetSelectedEvent")
glx_api_->glXGetSelectedEventFn(dpy, drawable, mask);
}
bool TraceGLXApi::glXGetSyncValuesOMLFn(Display* dpy,
GLXDrawable drawable,
int64_t* ust,
int64_t* msc,
int64_t* sbc) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetSyncValuesOML")
return glx_api_->glXGetSyncValuesOMLFn(dpy, drawable, ust, msc, sbc);
}
XVisualInfo* TraceGLXApi::glXGetVisualFromFBConfigFn(Display* dpy,
GLXFBConfig config) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetVisualFromFBConfig")
return glx_api_->glXGetVisualFromFBConfigFn(dpy, config);
}
int TraceGLXApi::glXIsDirectFn(Display* dpy, GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXIsDirect")
return glx_api_->glXIsDirectFn(dpy, ctx);
}
int TraceGLXApi::glXMakeContextCurrentFn(Display* dpy,
GLXDrawable draw,
GLXDrawable read,
GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXMakeContextCurrent")
return glx_api_->glXMakeContextCurrentFn(dpy, draw, read, ctx);
}
int TraceGLXApi::glXMakeCurrentFn(Display* dpy,
GLXDrawable drawable,
GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXMakeCurrent")
return glx_api_->glXMakeCurrentFn(dpy, drawable, ctx);
}
int TraceGLXApi::glXQueryContextFn(Display* dpy,
GLXContext ctx,
int attribute,
int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryContext")
return glx_api_->glXQueryContextFn(dpy, ctx, attribute, value);
}
void TraceGLXApi::glXQueryDrawableFn(Display* dpy,
GLXDrawable draw,
int attribute,
unsigned int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryDrawable")
glx_api_->glXQueryDrawableFn(dpy, draw, attribute, value);
}
int TraceGLXApi::glXQueryExtensionFn(Display* dpy, int* errorb, int* event) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryExtension")
return glx_api_->glXQueryExtensionFn(dpy, errorb, event);
}
const char* TraceGLXApi::glXQueryExtensionsStringFn(Display* dpy, int screen) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryExtensionsString")
return glx_api_->glXQueryExtensionsStringFn(dpy, screen);
}
const char* TraceGLXApi::glXQueryServerStringFn(Display* dpy,
int screen,
int name) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryServerString")
return glx_api_->glXQueryServerStringFn(dpy, screen, name);
}
int TraceGLXApi::glXQueryVersionFn(Display* dpy, int* maj, int* min) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryVersion")
return glx_api_->glXQueryVersionFn(dpy, maj, min);
}
void TraceGLXApi::glXReleaseTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXReleaseTexImageEXT")
glx_api_->glXReleaseTexImageEXTFn(dpy, drawable, buffer);
}
void TraceGLXApi::glXSelectEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long mask) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSelectEvent")
glx_api_->glXSelectEventFn(dpy, drawable, mask);
}
void TraceGLXApi::glXSwapBuffersFn(Display* dpy, GLXDrawable drawable) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSwapBuffers")
glx_api_->glXSwapBuffersFn(dpy, drawable);
}
void TraceGLXApi::glXSwapIntervalEXTFn(Display* dpy,
GLXDrawable drawable,
int interval) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSwapIntervalEXT")
glx_api_->glXSwapIntervalEXTFn(dpy, drawable, interval);
}
void TraceGLXApi::glXSwapIntervalMESAFn(unsigned int interval) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSwapIntervalMESA")
glx_api_->glXSwapIntervalMESAFn(interval);
}
void TraceGLXApi::glXUseXFontFn(Font font, int first, int count, int list) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXUseXFont")
glx_api_->glXUseXFontFn(font, first, count, list);
}
void TraceGLXApi::glXWaitGLFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXWaitGL")
glx_api_->glXWaitGLFn();
}
int TraceGLXApi::glXWaitVideoSyncSGIFn(int divisor,
int remainder,
unsigned int* count) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXWaitVideoSyncSGI")
return glx_api_->glXWaitVideoSyncSGIFn(divisor, remainder, count);
}
void TraceGLXApi::glXWaitXFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXWaitX")
glx_api_->glXWaitXFn();
}
void DebugGLXApi::glXBindTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer,
int* attribList) {
GL_SERVICE_LOG("glXBindTexImageEXT"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << buffer << ", "
<< static_cast<const void*>(attribList) << ")");
glx_api_->glXBindTexImageEXTFn(dpy, drawable, buffer, attribList);
}
GLXFBConfig* DebugGLXApi::glXChooseFBConfigFn(Display* dpy,
int screen,
const int* attribList,
int* nitems) {
GL_SERVICE_LOG("glXChooseFBConfig"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << static_cast<const void*>(attribList) << ", "
<< static_cast<const void*>(nitems) << ")");
GLXFBConfig* result =
glx_api_->glXChooseFBConfigFn(dpy, screen, attribList, nitems);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
XVisualInfo* DebugGLXApi::glXChooseVisualFn(Display* dpy,
int screen,
int* attribList) {
GL_SERVICE_LOG("glXChooseVisual"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << static_cast<const void*>(attribList) << ")");
XVisualInfo* result = glx_api_->glXChooseVisualFn(dpy, screen, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXCopyContextFn(Display* dpy,
GLXContext src,
GLXContext dst,
unsigned long mask) {
GL_SERVICE_LOG("glXCopyContext"
<< "(" << static_cast<const void*>(dpy) << ", " << src << ", "
<< dst << ", " << mask << ")");
glx_api_->glXCopyContextFn(dpy, src, dst, mask);
}
void DebugGLXApi::glXCopySubBufferMESAFn(Display* dpy,
GLXDrawable drawable,
int x,
int y,
int width,
int height) {
GL_SERVICE_LOG("glXCopySubBufferMESA"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << x << ", " << y << ", " << width << ", " << height
<< ")");
glx_api_->glXCopySubBufferMESAFn(dpy, drawable, x, y, width, height);
}
GLXContext DebugGLXApi::glXCreateContextFn(Display* dpy,
XVisualInfo* vis,
GLXContext shareList,
int direct) {
GL_SERVICE_LOG("glXCreateContext"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(vis) << ", " << shareList << ", "
<< direct << ")");
GLXContext result = glx_api_->glXCreateContextFn(dpy, vis, shareList, direct);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXContext DebugGLXApi::glXCreateContextAttribsARBFn(Display* dpy,
GLXFBConfig config,
GLXContext share_context,
int direct,
const int* attrib_list) {
GL_SERVICE_LOG("glXCreateContextAttribsARB"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << share_context << ", " << direct << ", "
<< static_cast<const void*>(attrib_list) << ")");
GLXContext result = glx_api_->glXCreateContextAttribsARBFn(
dpy, config, share_context, direct, attrib_list);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXPixmap DebugGLXApi::glXCreateGLXPixmapFn(Display* dpy,
XVisualInfo* visual,
Pixmap pixmap) {
GL_SERVICE_LOG("glXCreateGLXPixmap"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(visual) << ", " << pixmap << ")");
GLXPixmap result = glx_api_->glXCreateGLXPixmapFn(dpy, visual, pixmap);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXContext DebugGLXApi::glXCreateNewContextFn(Display* dpy,
GLXFBConfig config,
int renderType,
GLXContext shareList,
int direct) {
GL_SERVICE_LOG("glXCreateNewContext"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << renderType << ", " << shareList << ", " << direct
<< ")");
GLXContext result = glx_api_->glXCreateNewContextFn(dpy, config, renderType,
shareList, direct);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXPbuffer DebugGLXApi::glXCreatePbufferFn(Display* dpy,
GLXFBConfig config,
const int* attribList) {
GL_SERVICE_LOG("glXCreatePbuffer"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << static_cast<const void*>(attribList) << ")");
GLXPbuffer result = glx_api_->glXCreatePbufferFn(dpy, config, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXPixmap DebugGLXApi::glXCreatePixmapFn(Display* dpy,
GLXFBConfig config,
Pixmap pixmap,
const int* attribList) {
GL_SERVICE_LOG("glXCreatePixmap"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << pixmap << ", "
<< static_cast<const void*>(attribList) << ")");
GLXPixmap result =
glx_api_->glXCreatePixmapFn(dpy, config, pixmap, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXWindow DebugGLXApi::glXCreateWindowFn(Display* dpy,
GLXFBConfig config,
Window win,
const int* attribList) {
GL_SERVICE_LOG("glXCreateWindow"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << win << ", " << static_cast<const void*>(attribList)
<< ")");
GLXWindow result = glx_api_->glXCreateWindowFn(dpy, config, win, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXDestroyContextFn(Display* dpy, GLXContext ctx) {
GL_SERVICE_LOG("glXDestroyContext"
<< "(" << static_cast<const void*>(dpy) << ", " << ctx << ")");
glx_api_->glXDestroyContextFn(dpy, ctx);
}
void DebugGLXApi::glXDestroyGLXPixmapFn(Display* dpy, GLXPixmap pixmap) {
GL_SERVICE_LOG("glXDestroyGLXPixmap"
<< "(" << static_cast<const void*>(dpy) << ", " << pixmap
<< ")");
glx_api_->glXDestroyGLXPixmapFn(dpy, pixmap);
}
void DebugGLXApi::glXDestroyPbufferFn(Display* dpy, GLXPbuffer pbuf) {
GL_SERVICE_LOG("glXDestroyPbuffer"
<< "(" << static_cast<const void*>(dpy) << ", " << pbuf
<< ")");
glx_api_->glXDestroyPbufferFn(dpy, pbuf);
}
void DebugGLXApi::glXDestroyPixmapFn(Display* dpy, GLXPixmap pixmap) {
GL_SERVICE_LOG("glXDestroyPixmap"
<< "(" << static_cast<const void*>(dpy) << ", " << pixmap
<< ")");
glx_api_->glXDestroyPixmapFn(dpy, pixmap);
}
void DebugGLXApi::glXDestroyWindowFn(Display* dpy, GLXWindow window) {
GL_SERVICE_LOG("glXDestroyWindow"
<< "(" << static_cast<const void*>(dpy) << ", " << window
<< ")");
glx_api_->glXDestroyWindowFn(dpy, window);
}
const char* DebugGLXApi::glXGetClientStringFn(Display* dpy, int name) {
GL_SERVICE_LOG("glXGetClientString"
<< "(" << static_cast<const void*>(dpy) << ", " << name
<< ")");
const char* result = glx_api_->glXGetClientStringFn(dpy, name);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXGetConfigFn(Display* dpy,
XVisualInfo* visual,
int attrib,
int* value) {
GL_SERVICE_LOG("glXGetConfig"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(visual) << ", " << attrib << ", "
<< static_cast<const void*>(value) << ")");
int result = glx_api_->glXGetConfigFn(dpy, visual, attrib, value);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXContext DebugGLXApi::glXGetCurrentContextFn(void) {
GL_SERVICE_LOG("glXGetCurrentContext"
<< "("
<< ")");
GLXContext result = glx_api_->glXGetCurrentContextFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
Display* DebugGLXApi::glXGetCurrentDisplayFn(void) {
GL_SERVICE_LOG("glXGetCurrentDisplay"
<< "("
<< ")");
Display* result = glx_api_->glXGetCurrentDisplayFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXDrawable DebugGLXApi::glXGetCurrentDrawableFn(void) {
GL_SERVICE_LOG("glXGetCurrentDrawable"
<< "("
<< ")");
GLXDrawable result = glx_api_->glXGetCurrentDrawableFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXDrawable DebugGLXApi::glXGetCurrentReadDrawableFn(void) {
GL_SERVICE_LOG("glXGetCurrentReadDrawable"
<< "("
<< ")");
GLXDrawable result = glx_api_->glXGetCurrentReadDrawableFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXGetFBConfigAttribFn(Display* dpy,
GLXFBConfig config,
int attribute,
int* value) {
GL_SERVICE_LOG("glXGetFBConfigAttrib"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << attribute << ", " << static_cast<const void*>(value)
<< ")");
int result = glx_api_->glXGetFBConfigAttribFn(dpy, config, attribute, value);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXFBConfig DebugGLXApi::glXGetFBConfigFromVisualSGIXFn(
Display* dpy,
XVisualInfo* visualInfo) {
GL_SERVICE_LOG("glXGetFBConfigFromVisualSGIX"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(visualInfo) << ")");
GLXFBConfig result =
glx_api_->glXGetFBConfigFromVisualSGIXFn(dpy, visualInfo);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXFBConfig* DebugGLXApi::glXGetFBConfigsFn(Display* dpy,
int screen,
int* nelements) {
GL_SERVICE_LOG("glXGetFBConfigs"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << static_cast<const void*>(nelements) << ")");
GLXFBConfig* result = glx_api_->glXGetFBConfigsFn(dpy, screen, nelements);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
bool DebugGLXApi::glXGetMscRateOMLFn(Display* dpy,
GLXDrawable drawable,
int32_t* numerator,
int32_t* denominator) {
GL_SERVICE_LOG("glXGetMscRateOML"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << static_cast<const void*>(numerator) << ", "
<< static_cast<const void*>(denominator) << ")");
bool result =
glx_api_->glXGetMscRateOMLFn(dpy, drawable, numerator, denominator);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXGetSelectedEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long* mask) {
GL_SERVICE_LOG("glXGetSelectedEvent"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << static_cast<const void*>(mask) << ")");
glx_api_->glXGetSelectedEventFn(dpy, drawable, mask);
}
bool DebugGLXApi::glXGetSyncValuesOMLFn(Display* dpy,
GLXDrawable drawable,
int64_t* ust,
int64_t* msc,
int64_t* sbc) {
GL_SERVICE_LOG("glXGetSyncValuesOML"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << static_cast<const void*>(ust) << ", "
<< static_cast<const void*>(msc) << ", "
<< static_cast<const void*>(sbc) << ")");
bool result = glx_api_->glXGetSyncValuesOMLFn(dpy, drawable, ust, msc, sbc);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
XVisualInfo* DebugGLXApi::glXGetVisualFromFBConfigFn(Display* dpy,
GLXFBConfig config) {
GL_SERVICE_LOG("glXGetVisualFromFBConfig"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ")");
XVisualInfo* result = glx_api_->glXGetVisualFromFBConfigFn(dpy, config);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXIsDirectFn(Display* dpy, GLXContext ctx) {
GL_SERVICE_LOG("glXIsDirect"
<< "(" << static_cast<const void*>(dpy) << ", " << ctx << ")");
int result = glx_api_->glXIsDirectFn(dpy, ctx);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXMakeContextCurrentFn(Display* dpy,
GLXDrawable draw,
GLXDrawable read,
GLXContext ctx) {
GL_SERVICE_LOG("glXMakeContextCurrent"
<< "(" << static_cast<const void*>(dpy) << ", " << draw << ", "
<< read << ", " << ctx << ")");
int result = glx_api_->glXMakeContextCurrentFn(dpy, draw, read, ctx);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXMakeCurrentFn(Display* dpy,
GLXDrawable drawable,
GLXContext ctx) {
GL_SERVICE_LOG("glXMakeCurrent"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << ctx << ")");
int result = glx_api_->glXMakeCurrentFn(dpy, drawable, ctx);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXQueryContextFn(Display* dpy,
GLXContext ctx,
int attribute,
int* value) {
GL_SERVICE_LOG("glXQueryContext"
<< "(" << static_cast<const void*>(dpy) << ", " << ctx << ", "
<< attribute << ", " << static_cast<const void*>(value)
<< ")");
int result = glx_api_->glXQueryContextFn(dpy, ctx, attribute, value);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXQueryDrawableFn(Display* dpy,
GLXDrawable draw,
int attribute,
unsigned int* value) {
GL_SERVICE_LOG("glXQueryDrawable"
<< "(" << static_cast<const void*>(dpy) << ", " << draw << ", "
<< attribute << ", " << static_cast<const void*>(value)
<< ")");
glx_api_->glXQueryDrawableFn(dpy, draw, attribute, value);
}
int DebugGLXApi::glXQueryExtensionFn(Display* dpy, int* errorb, int* event) {
GL_SERVICE_LOG("glXQueryExtension"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(errorb) << ", "
<< static_cast<const void*>(event) << ")");
int result = glx_api_->glXQueryExtensionFn(dpy, errorb, event);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
const char* DebugGLXApi::glXQueryExtensionsStringFn(Display* dpy, int screen) {
GL_SERVICE_LOG("glXQueryExtensionsString"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ")");
const char* result = glx_api_->glXQueryExtensionsStringFn(dpy, screen);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
const char* DebugGLXApi::glXQueryServerStringFn(Display* dpy,
int screen,
int name) {
GL_SERVICE_LOG("glXQueryServerString"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << name << ")");
const char* result = glx_api_->glXQueryServerStringFn(dpy, screen, name);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXQueryVersionFn(Display* dpy, int* maj, int* min) {
GL_SERVICE_LOG("glXQueryVersion"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(maj) << ", "
<< static_cast<const void*>(min) << ")");
int result = glx_api_->glXQueryVersionFn(dpy, maj, min);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXReleaseTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer) {
GL_SERVICE_LOG("glXReleaseTexImageEXT"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << buffer << ")");
glx_api_->glXReleaseTexImageEXTFn(dpy, drawable, buffer);
}
void DebugGLXApi::glXSelectEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long mask) {
GL_SERVICE_LOG("glXSelectEvent"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << mask << ")");
glx_api_->glXSelectEventFn(dpy, drawable, mask);
}
void DebugGLXApi::glXSwapBuffersFn(Display* dpy, GLXDrawable drawable) {
GL_SERVICE_LOG("glXSwapBuffers"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ")");
glx_api_->glXSwapBuffersFn(dpy, drawable);
}
void DebugGLXApi::glXSwapIntervalEXTFn(Display* dpy,
GLXDrawable drawable,
int interval) {
GL_SERVICE_LOG("glXSwapIntervalEXT"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << interval << ")");
glx_api_->glXSwapIntervalEXTFn(dpy, drawable, interval);
}
void DebugGLXApi::glXSwapIntervalMESAFn(unsigned int interval) {
GL_SERVICE_LOG("glXSwapIntervalMESA"
<< "(" << interval << ")");
glx_api_->glXSwapIntervalMESAFn(interval);
}
void DebugGLXApi::glXUseXFontFn(Font font, int first, int count, int list) {
GL_SERVICE_LOG("glXUseXFont"
<< "(" << font << ", " << first << ", " << count << ", "
<< list << ")");
glx_api_->glXUseXFontFn(font, first, count, list);
}
void DebugGLXApi::glXWaitGLFn(void) {
GL_SERVICE_LOG("glXWaitGL"
<< "("
<< ")");
glx_api_->glXWaitGLFn();
}
int DebugGLXApi::glXWaitVideoSyncSGIFn(int divisor,
int remainder,
unsigned int* count) {
GL_SERVICE_LOG("glXWaitVideoSyncSGI"
<< "(" << divisor << ", " << remainder << ", "
<< static_cast<const void*>(count) << ")");
int result = glx_api_->glXWaitVideoSyncSGIFn(divisor, remainder, count);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXWaitXFn(void) {
GL_SERVICE_LOG("glXWaitX"
<< "("
<< ")");
glx_api_->glXWaitXFn();
}
} // namespace gl
| 41.56044
| 80
| 0.585348
|
zipated
|
44d7e572a4e13add39ef307b60d9323142d301ad
| 5,868
|
cpp
|
C++
|
tf2_src/utils/vmpi/vmpi_job_watch/GraphControl.cpp
|
IamIndeedGamingAsHardAsICan03489/TeamFortress2
|
1b81dded673d49adebf4d0958e52236ecc28a956
|
[
"MIT"
] | 4
|
2021-10-03T05:16:55.000Z
|
2021-12-28T16:49:27.000Z
|
src/utils/vmpi/vmpi_job_watch/GraphControl.cpp
|
cafeed28/what
|
08e51d077f0eae50afe3b592543ffa07538126f5
|
[
"Unlicense"
] | null | null | null |
src/utils/vmpi/vmpi_job_watch/GraphControl.cpp
|
cafeed28/what
|
08e51d077f0eae50afe3b592543ffa07538126f5
|
[
"Unlicense"
] | 3
|
2022-02-02T18:09:58.000Z
|
2022-03-06T18:54:39.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// GraphControl.cpp : implementation file
//
#include "stdafx.h"
#include "vmpi_browser_job_watch.h"
#include "GraphControl.h"
#include "mathlib/mathlib.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CGraphControl
CGraphControl::CGraphControl()
{
}
CGraphControl::~CGraphControl()
{
}
BEGIN_MESSAGE_MAP(CGraphControl, CWnd)
//{{AFX_MSG_MAP(CGraphControl)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CGraphControl::Clear()
{
CRect rcClient;
GetClientRect( rcClient );
CDC *pDC = GetDC();
CBrush brush( RGB( 0, 0, 0 ) );
CBrush *pOldBrush = pDC->SelectObject( &brush );
pDC->Rectangle( 0, 0, rcClient.Width(), rcClient.Height() );
pDC->SelectObject( pOldBrush );
ReleaseDC( pDC );
}
void CGraphControl::Render( CDC *pDC )
{
// Clear the background.
CRect rcClient;
GetClientRect( rcClient );
CBrush brush( RGB( 0, 0, 0 ) );
CBrush *pOldBrush = pDC->SelectObject( &brush );
pDC->Rectangle( 0, 0, rcClient.Width(), rcClient.Height() );
pDC->SelectObject( pOldBrush );
// Work backwards from the right side to the left.
int nIntervals = rcClient.Width();
DWORD intervalMS = 500; // one interval per pixel
DWORD startTime = 0xFFFFFFFF, endTime = 0;
// First, find which order of magnitude to use on the vertical scale by finding the maximum value.
for ( int iEntry=0; iEntry < m_Entries.Count(); iEntry++ )
{
DWORD msTime = m_Entries[iEntry].m_msTime;
startTime = min( startTime, msTime );
endTime = max( endTime, msTime );
}
int curTime = (int)endTime - nIntervals*intervalMS;
CGraphEntry prevEntry, curEntry;
prevEntry.m_msTime = curEntry.m_msTime = -1;
CUtlVector<POINT> sentPoints;
CUtlVector<POINT> receivedPoints;
int iCurEntry = -1;
int nMaxBytesSent = -1, nMaxBytesReceived = -1;
for ( int x=0; x < nIntervals; x++ )
{
if ( curTime >= 0 )
{
// Now find the graph_entry for the time we're at.
while ( prevEntry.m_msTime == -1 || curTime > curEntry.m_msTime )
{
++iCurEntry;
if ( iCurEntry >= m_Entries.Count() )
goto ENDLOOP;
prevEntry = curEntry;
curEntry = m_Entries[iCurEntry];
}
if ( curTime >= prevEntry.m_msTime && curTime <= curEntry.m_msTime )
{
// Interpolate the bytes sent.
int nBytesSent = (int)RemapVal(
curTime,
prevEntry.m_msTime, curEntry.m_msTime,
prevEntry.m_nBytesSent, curEntry.m_nBytesSent );
POINT sentPoint = { x, nBytesSent };
sentPoints.AddToTail( sentPoint );
nMaxBytesSent = max( nMaxBytesSent, nBytesSent );
int nBytesReceived = (int)RemapVal(
curTime,
prevEntry.m_msTime, curEntry.m_msTime,
prevEntry.m_nBytesReceived, curEntry.m_nBytesReceived );
POINT receivedPoint = { x, nBytesReceived };
receivedPoints.AddToTail( receivedPoint );
nMaxBytesReceived = max( nMaxBytesReceived, nBytesReceived );
}
}
curTime += intervalMS;
}
ENDLOOP:;
// Now normalize all the values.
int largest = max( nMaxBytesSent, nMaxBytesReceived );
int topValue = (largest*11) / 10;
/*
DWORD nZeros;
for( nZeros = 1; nZeros < 20; nZeros++ )
{
if ( largest < pow( 10, nZeros ) )
break;
}
// Now find the value at the top of the graph. We choose the smallest enclosing tenth of the
// order of magnitude we're at (so if we were at 1,000,000, and our max value was 350,000, we'd choose 400,000).
int iTenth;
int topValue;
for ( iTenth=1; iTenth <= 10; iTenth++ )
{
topValue = (DWORD)( pow( 10, nZeros-1 ) * iTenth );
if ( topValue >= largest )
break;
}
*/
for ( int iSample=0; iSample < sentPoints.Count(); iSample++ )
{
double flHeight;
flHeight = ((double)sentPoints[iSample].y / topValue) * (rcClient.Height() - 1);
sentPoints[iSample].y = (int)( rcClient.Height() - flHeight );
flHeight = ((double)receivedPoints[iSample].y / topValue) * (rcClient.Height() - 1);
receivedPoints[iSample].y = (int)( rcClient.Height() - flHeight );
}
// Draw some horizontal lines dividing the space.
int nLines = 10;
for ( int iLine=0; iLine <= nLines; iLine++ )
{
CPen penLine;
COLORREF color;
if ( iLine == 0 || iLine == nLines/2 )
color = RGB( 0, 220, 0 );
else
color = RGB( 0, 100, 0 );
penLine.CreatePen( PS_SOLID, 1, color );
CPen *pOldPen = pDC->SelectObject( &penLine );
int y = (iLine * rcClient.Height()) / nLines;
pDC->MoveTo( 0, y );
pDC->LineTo( rcClient.Width(), y );
pDC->SelectObject( pOldPen );
}
// Now draw the lines for the data.
CPen penSent( PS_SOLID, 1, RGB( 0, 255, 0 ) );
CPen *pOldPen = pDC->SelectObject( &penSent );
pDC->Polyline( sentPoints.Base(), sentPoints.Count() );
pDC->SelectObject( pOldPen );
CPen penReceived( PS_SOLID, 1, RGB( 255, 255, 0 ) );
pOldPen = pDC->SelectObject( &penReceived );
pDC->Polyline( receivedPoints.Base(), receivedPoints.Count() );
pDC->SelectObject( pOldPen );
// Draw text labels.
pDC->SetTextColor( RGB( 200, 200, 200 ) );
pDC->SetBkColor( 0 );
CString str;
str.Format( "%dk", (topValue+511) / 1024 );
pDC->ExtTextOut( 0, 1, 0, NULL, str, NULL );
str.Format( "%dk", (topValue+511) / 1024 / 2 );
pDC->ExtTextOut( 0, rcClient.Height()/2 + 1, 0, NULL, str, NULL );
}
void CGraphControl::Fill( CUtlVector<CGraphEntry> &entries )
{
CDC *pDC = GetDC();
if ( !pDC )
return;
m_Entries = entries;
Render( pDC );
ReleaseDC( pDC );
}
/////////////////////////////////////////////////////////////////////////////
// CGraphControl message handlers
void CGraphControl::OnPaint()
{
CPaintDC dc(this); // device context for painting
Render( &dc );
}
| 23.757085
| 113
| 0.632243
|
IamIndeedGamingAsHardAsICan03489
|
44d9ff95f08b9f006f7274635d2bcf74670b6911
| 2,125
|
cpp
|
C++
|
map/map_tests/transliteration_test.cpp
|
ToshUxanoff/omim
|
a8acb5821c72bd78847d1c49968b14d15b1e06ee
|
[
"Apache-2.0"
] | null | null | null |
map/map_tests/transliteration_test.cpp
|
ToshUxanoff/omim
|
a8acb5821c72bd78847d1c49968b14d15b1e06ee
|
[
"Apache-2.0"
] | null | null | null |
map/map_tests/transliteration_test.cpp
|
ToshUxanoff/omim
|
a8acb5821c72bd78847d1c49968b14d15b1e06ee
|
[
"Apache-2.0"
] | null | null | null |
#include "testing/testing.hpp"
#include "coding/string_utf8_multilang.hpp"
#include "coding/transliteration.hpp"
#include "platform/platform.hpp"
namespace
{
void TestTransliteration(Transliteration const & translit, std::string const & locale,
std::string const & original, std::string const & expected)
{
std::string out;
translit.Transliterate(original, StringUtf8Multilang::GetLangIndex(locale), out);
TEST_EQUAL(expected, out, ());
}
} // namespace
// This test is inside of the map_tests because it uses Platform for obtaining the resource directory.
UNIT_TEST(Transliteration_CompareSamples)
{
Transliteration & translit = Transliteration::Instance();
translit.Init(GetPlatform().ResourcesDir());
TestTransliteration(translit, "ar", "العربية", "alrbyt");
TestTransliteration(translit, "ru", "Русский", "Russkiy");
TestTransliteration(translit, "zh", "中文", "zhong wen");
TestTransliteration(translit, "be", "Беларуская", "Byelaruskaya");
TestTransliteration(translit, "ka", "ქართული", "kartuli");
TestTransliteration(translit, "ko", "한국어", "hangug-eo");
TestTransliteration(translit, "he", "עברית", "bryt");
TestTransliteration(translit, "el", "Ελληνικά", "Ellenika");
TestTransliteration(translit, "zh_pinyin", "拼音", "pin yin");
TestTransliteration(translit, "th", "ไทย", ""); // Thai-Latin transliteration is off.
TestTransliteration(translit, "sr", "Српски", "Srpski");
TestTransliteration(translit, "uk", "Українська", "Ukrayinska");
TestTransliteration(translit, "fa", "فارسی", "farsy");
TestTransliteration(translit, "hy", "Հայերէն", "Hayeren");
TestTransliteration(translit, "kn", "ಕನ್ನಡ", "kannada");
TestTransliteration(translit, "am", "አማርኛ", "amarinya");
TestTransliteration(translit, "ja_kana", "カタカナ", "katakana");
TestTransliteration(translit, "bg", "Български", "Bulgarski");
TestTransliteration(translit, "kk", "Қазақ", "Qazaq");
TestTransliteration(translit, "mn", "Монгол хэл", "Mongol hel");
TestTransliteration(translit, "mk", "Македонски", "Makedonski");
TestTransliteration(translit, "hi", "हिन्दी", "hindi");
}
| 44.270833
| 102
| 0.715294
|
ToshUxanoff
|
44da75c56fd1a30a62e86c302030115c51ae01f3
| 2,851
|
cc
|
C++
|
paddle/fluid/memory/allocation/thread_local_allocator.cc
|
suytingwan/Paddle
|
d4560871878eaec4f1f682af56fb364a5f596b18
|
[
"Apache-2.0"
] | 1
|
2020-05-12T04:00:14.000Z
|
2020-05-12T04:00:14.000Z
|
paddle/fluid/memory/allocation/thread_local_allocator.cc
|
MaJun-cn/Paddle
|
0ec3a42e9740a5f5066053bb49a923d538eba24a
|
[
"Apache-2.0"
] | null | null | null |
paddle/fluid/memory/allocation/thread_local_allocator.cc
|
MaJun-cn/Paddle
|
0ec3a42e9740a5f5066053bb49a923d538eba24a
|
[
"Apache-2.0"
] | 4
|
2020-07-27T13:24:03.000Z
|
2020-08-06T08:20:32.000Z
|
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/memory/allocation/thread_local_allocator.h"
namespace paddle {
namespace memory {
namespace allocation {
ThreadLocalAllocatorImpl::ThreadLocalAllocatorImpl(const platform::Place& p)
: place_(p) {
if (platform::is_gpu_place(place_)) {
buddy_allocator_.reset(new memory::detail::BuddyAllocator(
std::unique_ptr<memory::detail::SystemAllocator>(
new memory::detail::GPUAllocator(
BOOST_GET_CONST(platform::CUDAPlace, place_).device)),
platform::GpuMinChunkSize(), platform::GpuMaxChunkSize()));
} else {
LOG(FATAL) << "Thread local allocator only supports CUDAPlace now.";
}
}
std::shared_ptr<ThreadLocalAllocatorImpl> ThreadLocalCUDAAllocatorPool::Get(
int gpu_id) {
auto pos = std::distance(devices_.begin(),
std::find(devices_.begin(), devices_.end(), gpu_id));
PADDLE_ENFORCE_LT(
pos, devices_.size(),
platform::errors::InvalidArgument(
"The position of device should be less than the size of devices."));
std::call_once(*init_flags_[pos], [this, pos, gpu_id] {
platform::SetDeviceId(devices_[pos]);
allocators_[pos].reset(
new ThreadLocalAllocatorImpl(platform::CUDAPlace(gpu_id)));
});
return allocators_[pos];
}
ThreadLocalCUDAAllocatorPool::ThreadLocalCUDAAllocatorPool()
: devices_(platform::GetSelectedDevices()) {
auto gpu_num = devices_.size();
allocators_.resize(gpu_num);
init_flags_.reserve(gpu_num);
for (size_t i = 0; i < gpu_num; ++i) {
init_flags_.emplace_back(new std::once_flag());
}
}
ThreadLocalAllocation* ThreadLocalAllocatorImpl::AllocateImpl(size_t size) {
VLOG(10) << "ThreadLocalAllocatorImpl::AllocateImpl " << size;
void* ptr = buddy_allocator_->Alloc(size);
auto* tl_allocation = new ThreadLocalAllocation(ptr, size, place_);
tl_allocation->SetThreadLocalAllocatorImpl(shared_from_this());
return tl_allocation;
}
void ThreadLocalAllocatorImpl::FreeImpl(ThreadLocalAllocation* allocation) {
VLOG(10) << "ThreadLocalAllocatorImpl::FreeImpl " << allocation;
buddy_allocator_->Free(allocation->ptr());
delete allocation;
}
} // namespace allocation
} // namespace memory
} // namespace paddle
| 37.025974
| 80
| 0.722203
|
suytingwan
|
44dd43a158a99088eda748363433770d5e6d17ff
| 3,248
|
cpp
|
C++
|
Phoenix3D/PX2Core/PX2Event.cpp
|
PheonixFoundation/Phoenix3D
|
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
|
[
"BSL-1.0"
] | 36
|
2016-04-24T01:40:38.000Z
|
2022-01-18T07:32:26.000Z
|
Phoenix3D/PX2Core/PX2Event.cpp
|
PheonixFoundation/Phoenix3D
|
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
|
[
"BSL-1.0"
] | null | null | null |
Phoenix3D/PX2Core/PX2Event.cpp
|
PheonixFoundation/Phoenix3D
|
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
|
[
"BSL-1.0"
] | 16
|
2016-06-13T08:43:51.000Z
|
2020-09-15T13:25:58.000Z
|
// PX2Event.cpp
#include "PX2Event.hpp"
#include "PX2Assert.hpp"
using namespace PX2;
Event::Event ()
:
mEventType(0),
mSender(0),
mReceiver(0),
mDelayTime(0.0f),
mDelayTiming(0.0f),
mIsDoDelay(false)
{
mEventChannel.FillUserChannel();
}
//----------------------------------------------------------------------------
Event::Event (const Event& event)
{
Initlize(event);
}
//----------------------------------------------------------------------------
Event::~Event ()
{
mSender = 0;
mReceiver = 0;
}
//----------------------------------------------------------------------------
Event& Event::operator= (const Event& event)
{
Initlize(event);
return (*this);
}
//----------------------------------------------------------------------------
void Event::SetEventType (EventType eventType)
{
mEventType = eventType;
}
//----------------------------------------------------------------------------
Event::EventType Event::GetEventType ()
{
return mEventType;
}
//----------------------------------------------------------------------------
void Event::SetChannel (const EventChannel& eventChannel)
{
if (eventChannel.IsEmpty())
{
assertion(false, "input eventChannel must not be empty.");
}
mEventChannel = eventChannel;
}
//----------------------------------------------------------------------------
const EventChannel& Event::GetChannel ()
{
return mEventChannel;
}
//----------------------------------------------------------------------------
void Event::SetTimeDelay (float timeDelay)
{
mDelayTime = timeDelay;
mDelayTiming = timeDelay;
if (mDelayTiming > 0.0f)
mIsDoDelay = true;
}
//----------------------------------------------------------------------------
void Event::SetSender (EventHandler *handler)
{
mSender = handler;
}
//----------------------------------------------------------------------------
EventHandler* Event::GetSender ()
{
return mSender;
}
//----------------------------------------------------------------------------
void Event::SetReceiver (EventHandler *handler)
{
mReceiver = handler;
}
//----------------------------------------------------------------------------
EventHandler* Event::GetReceiver ()
{
return mReceiver;
}
//----------------------------------------------------------------------------
bool Event::IsSystemEvent () const
{
return mEventChannel.IsEmpty();
}
//----------------------------------------------------------------------------
void Event::SetBeSystemEvent ()
{
mEventChannel.Clear();
}
//----------------------------------------------------------------------------
void Event::Initlize (const Event &event)
{
mEventChannel = event.mEventChannel;
mEventType = event.mEventType;
mEventData = event.mEventData;
mSender = event.mSender;
mReceiver = event.mReceiver;
}
//----------------------------------------------------------------------------
void Event::Update (float timeDetail)
{
if (mIsDoDelay)
{
mDelayTiming -= timeDetail;
if (mDelayTiming < 0.0f)
mDelayTiming = 0.0f;
}
}
//----------------------------------------------------------------------------
bool Event::IsDelayActted ()
{
if (mIsDoDelay && 0.0f==mDelayTiming)
{
return true;
}
return false;
}
//----------------------------------------------------------------------------
| 25.178295
| 78
| 0.40117
|
PheonixFoundation
|
44dde9125f17488902a192c50863c28b054d7e7c
| 8,506
|
hpp
|
C++
|
lib/lorina/lorina/genlib.hpp
|
fmozafari/mockturtle
|
ebf32a5643bf818a3720809b867a0401a4bc6eed
|
[
"MIT"
] | null | null | null |
lib/lorina/lorina/genlib.hpp
|
fmozafari/mockturtle
|
ebf32a5643bf818a3720809b867a0401a4bc6eed
|
[
"MIT"
] | null | null | null |
lib/lorina/lorina/genlib.hpp
|
fmozafari/mockturtle
|
ebf32a5643bf818a3720809b867a0401a4bc6eed
|
[
"MIT"
] | 1
|
2021-12-20T20:42:30.000Z
|
2021-12-20T20:42:30.000Z
|
/* lorina: C++ parsing library
* Copyright (C) 2018-2021 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
\file genlib.hpp
\brief Implements GENLIB parser
\author Heinz Riener
\author Shubham Rai
\author Alessandro Tempia Calvino
*/
#pragma once
#include "common.hpp"
#include "detail/utils.hpp"
#include "diagnostics.hpp"
#include <fstream>
#include <istream>
#include <optional>
#include <sstream>
#include <string>
namespace lorina
{
enum class phase_type : uint8_t
{
INV = 0,
NONINV = 1,
UNKNOWN = 2,
};
// PIN <pin-name> <phase> <input-load> <max-load> <rise-block-delay> <rise-fanout-delay> <fall-block-delay> <fall-fanout-delay>
struct pin_spec
{
std::string name;
phase_type phase;
double input_load;
double max_load;
double rise_block_delay;
double rise_fanout_delay;
double fall_block_delay;
double fall_fanout_delay;
}; /* pin_spec */
/*! \brief A reader visitor for a GENLIB format.
*
* Callbacks for the GENLIB format.
*/
class genlib_reader
{
public:
virtual void on_gate( std::string const& name, std::string const& expression, uint32_t num_vars, double area, std::vector<pin_spec> const& pins ) const
{
(void)name;
(void)expression;
(void)num_vars;
(void)area;
(void)pins;
}
}; /* genlib_reader */
/*! \brief Parse for the GENLIB format.
*
*/
class genlib_parser
{
public:
explicit genlib_parser( std::istream& in, genlib_reader const& reader, diagnostic_engine* diag )
: in( in )
, reader( reader )
, diag( diag )
{}
public:
bool run()
{
std::string line;
while ( std::getline( in, line ) )
{
/* remove whitespaces */
detail::trim( line );
/* skip comments and empty lines */
if ( line[0] == '#' || line.empty() )
{
continue;
}
if ( !parse_gate_definition( line ) )
{
return false;
}
}
return true;
}
private:
bool parse_gate_definition( std::string const& line )
{
std::stringstream ss( line );
std::string const deliminators{" \t\r\n"};
std::string token;
std::vector<std::string> tokens;
while ( std::getline( ss, token ) )
{
std::size_t prev = 0, pos;
while ( ( pos = line.find_first_of( deliminators, prev ) ) != std::string::npos )
{
if ( pos > prev )
{
tokens.emplace_back( token.substr( prev, pos - prev ) );
}
prev = pos + 1;
}
if ( prev < line.length() )
{
tokens.emplace_back( token.substr( prev, std::string::npos ) );
}
}
if ( tokens.size() < 4u )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_UNEXPECTED_STRUCTURE ).add_argument( line );
}
return false;
}
if ( tokens[0] != "GATE" )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_GATE ).add_argument( line );
}
return false;
}
auto const beg = tokens[3].find_first_of( "=" );
auto const end = tokens[3].find_first_of( ";" );
if ( beg == std::string::npos || end == std::string::npos )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_EXPRESSION ).add_argument( tokens[3] );
}
return false;
}
std::string const& name = tokens[1];
std::string const& expression = tokens[3].substr( beg + 1, end - beg - 1 );
double const area = std::stod( tokens[2] );
uint32_t num_vars{0};
for ( const auto& c : expression )
{
if ( c >= 'a' && c <= 'z' )
{
uint32_t const var = 1 + ( c - 'a' );
if ( var > num_vars )
{
num_vars = var;
}
}
}
std::vector<pin_spec> pins;
bool generic_pin{false};
uint64_t i{4};
for ( ; i+8 < tokens.size(); i += 9 )
{
/* check PIN specification */
if ( tokens[i] != "PIN" )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_PIN ).add_argument( tokens[i] );
}
return false;
}
std::string const& name = tokens[i+1];
if ( tokens[i+1] == "*" )
{
generic_pin = true;
}
phase_type phase{phase_type::UNKNOWN};
if ( tokens[i+2] == "INV" )
{
phase = phase_type::INV;
}
else if ( tokens[i+2] == "NONINV" )
{
phase = phase_type::NONINV;
}
else
{
if ( tokens[i+2] != "UNKNOWN" )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_PIN_PHASE ).add_argument( tokens[i+1] );
}
}
}
double const input_load = std::stod( tokens[i+3] );
double const max_load = std::stod( tokens[i+4] );
double const rise_block_delay = std::stod( tokens[i+5] );
double const rise_fanout_delay = std::stod( tokens[i+6] );
double const fall_block_delay = std::stod( tokens[i+7] );
double const fall_fanout_delay = std::stod( tokens[i+8] );
pins.emplace_back( pin_spec{name,phase,input_load,max_load,rise_block_delay,rise_fanout_delay,fall_block_delay,fall_fanout_delay} );
}
if ( pins.size() != num_vars && !( pins.size() == 1 && generic_pin ) )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_PIN ).add_argument( tokens[i] );
}
return false;
}
if ( i != tokens.size() )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_FAILED ).add_argument( tokens[i] );
}
return false;
}
reader.on_gate( name, expression, num_vars, area, pins );
return true;
}
protected:
std::istream& in;
genlib_reader const& reader;
diagnostic_engine* diag;
}; /* genlib_parser */
/*! \brief Reader function for the GENLIB format.
*
* Reads GENLIB format from a stream and invokes a callback
* method for each parsed primitive and each detected parse error.
*
* \param in Input stream
* \param reader GENLIB reader with callback methods invoked for parsed primitives
* \param diag An optional diagnostic engine with callback methods for parse errors
* \return Success if parsing has been successful, or parse error if parsing has failed
*/
[[nodiscard]] inline return_code read_genlib( std::istream& in, const genlib_reader& reader, diagnostic_engine* diag = nullptr )
{
genlib_parser parser( in, reader, diag );
auto result = parser.run();
if ( !result )
{
return return_code::parse_error;
}
else
{
return return_code::success;
}
}
/*! \brief Reader function for the GENLIB format.
*
* Reads GENLIB format from a file and invokes a callback
* method for each parsed primitive and each detected parse error.
*
* \param filename Name of the file
* \param reader GENLIB reader with callback methods invoked for parsed primitives
* \param diag An optional diagnostic engine with callback methods for parse errors
* \return Success if parsing has been successful, or parse error if parsing has failed
*/
[[nodiscard]] inline return_code read_genlib( const std::string& filename, const genlib_reader& reader, diagnostic_engine* diag = nullptr )
{
std::ifstream in( detail::word_exp_filename( filename ), std::ifstream::in );
if ( !in.is_open() )
{
if ( diag )
{
diag->report( diag_id::ERR_FILE_OPEN ).add_argument( filename );
}
return return_code::parse_error;
}
else
{
auto const ret = read_genlib( in, reader, diag );
in.close();
return ret;
}
}
} /* lorina */
| 25.932927
| 153
| 0.618152
|
fmozafari
|
44ded4ccb5a4e2954add318cdc7c412c190c51b9
| 1,635
|
cpp
|
C++
|
o12e1ska/skar.cpp
|
czers/oi-tasks
|
b862cd33bd2230c7cea135333056954388ba9502
|
[
"Unlicense"
] | null | null | null |
o12e1ska/skar.cpp
|
czers/oi-tasks
|
b862cd33bd2230c7cea135333056954388ba9502
|
[
"Unlicense"
] | null | null | null |
o12e1ska/skar.cpp
|
czers/oi-tasks
|
b862cd33bd2230c7cea135333056954388ba9502
|
[
"Unlicense"
] | null | null | null |
#include <cstdio>
class FindUnion
{
private:
int rank;
FindUnion *parent;
public:
static void MakeSet(FindUnion &x)
{
x.parent = &x;
x.rank = 0;
}
static void Union(FindUnion &x, FindUnion &y)
{
FindUnion *xRoot = FindUnion::Find(x);
FindUnion *yRoot = FindUnion::Find(y);
if (xRoot == yRoot)
return;
if (xRoot->rank < yRoot->rank)
xRoot->parent = yRoot;
else if (xRoot->rank > yRoot->rank)
yRoot->parent = xRoot;
else
{
yRoot->parent = xRoot;
xRoot->rank += 1;
}
}
static FindUnion* Find(FindUnion &x)
{
if (x.parent != &x)
x.parent = FindUnion::Find(*x.parent);
return x.parent;
}
static int FindIndex(FindUnion &x, FindUnion fu[])
{
return FindUnion::Find(x) - fu;
}
};
int main()
{
int n;
scanf("%d", &n);
FindUnion fu[n];
for (int i = 0; i < n; i++)
FindUnion::MakeSet(fu[i]);
for (int i = 0; i < n; i++)
{
int a;
scanf("%d", &a);
a--;
FindUnion::Union(fu[i], fu[a]);
}
bool setRoot[n];
for (int i = 0; i < n; i++)
setRoot[i] = false;
for (int i = 0; i < n; i++)
setRoot[FindUnion::FindIndex(fu[i], fu)] = true;
int count = 0;
for (int i = 0; i < n; i++)
if (setRoot[i] == true)
count++;
printf("%d\n", count);
return 0;
}
| 24.044118
| 58
| 0.428746
|
czers
|
44e1baffbba192d7088b5f642560792da83e0db0
| 447
|
hpp
|
C++
|
SDK/Examples/FilamentViewer/FilamentViewer/Debugging/LogLights.hpp
|
h-haris/Quesa
|
a438ab824291ce6936a88dfae4fd0482dcba1247
|
[
"BSD-3-Clause"
] | 24
|
2019-10-28T07:01:48.000Z
|
2022-03-04T16:10:39.000Z
|
SDK/Examples/FilamentViewer/FilamentViewer/Debugging/LogLights.hpp
|
h-haris/Quesa
|
a438ab824291ce6936a88dfae4fd0482dcba1247
|
[
"BSD-3-Clause"
] | 8
|
2020-04-22T19:42:45.000Z
|
2021-04-30T16:28:32.000Z
|
SDK/Examples/FilamentViewer/FilamentViewer/Debugging/LogLights.hpp
|
h-haris/Quesa
|
a438ab824291ce6936a88dfae4fd0482dcba1247
|
[
"BSD-3-Clause"
] | 6
|
2019-09-22T14:44:15.000Z
|
2021-04-01T20:04:29.000Z
|
//
// LogLights.hpp
// FilamentViewer
//
// Created by James Walker on 5/27/21.
//
#ifndef LogLights_hpp
#define LogLights_hpp
namespace filament
{
class Engine;
class Scene;
};
/*!
@function LogLights
@abstract Log various information about lights in a Scene to std::cout.
@param inEngine An engine.
@param inScene A scene.
*/
void LogLights( filament::Engine& inEngine, filament::Scene& inScene );
#endif /* LogLights_hpp */
| 15.964286
| 72
| 0.704698
|
h-haris
|
44e311176e7266c61c291f5a3a20165d39ebaa92
| 1,204
|
cpp
|
C++
|
16_SWAPING_VARIABLES_POINTERS/Swapping Variables Pointers.cpp
|
CrispenGari/cool-cpp
|
bcbf9e0df7af07f8b12aa554fd15d977ecb47f60
|
[
"MIT"
] | null | null | null |
16_SWAPING_VARIABLES_POINTERS/Swapping Variables Pointers.cpp
|
CrispenGari/cool-cpp
|
bcbf9e0df7af07f8b12aa554fd15d977ecb47f60
|
[
"MIT"
] | null | null | null |
16_SWAPING_VARIABLES_POINTERS/Swapping Variables Pointers.cpp
|
CrispenGari/cool-cpp
|
bcbf9e0df7af07f8b12aa554fd15d977ecb47f60
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <afxres.h>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
#include <map>
#include <vector>
#include <string>
//#include <Crispen.h>
// #include <sqlite3.h/sqlite3>
#include <utility>
#define TRUE "true"
#define FALSE "false"
#include <time.h>
#include <stdio.h>
#include<stdlib.h>
#include <optional>
#include <cstdlib>
#include <vector>
#define PI 3.1429
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>
#include <iterator>
/*
Write a C++ language program to swap two numbers using pointers and
function.
*/
/* Without using a temporary variable*/
void swap2(int *a, int *b){
*a = *a-*b;
*b = *a+*b;
*a= *b-*a;
}
/*By using a temporary variable*/
void swap1(int *a, int *b){
int temp = *a;
*a =*b;
*b = temp;
}
int main(){
cout<<"Enter two integers a and b respectively: ";
int a,b;
cin>>a>>b;
cout<<"Before swapp"<<endl;
cout<<"a = "<<a<<", b = "<<b<<endl;
cout<<"After swapp"<<endl;
swap2(&a,&b);
cout<<"a = "<<a<<", b = "<<b<<endl;
return 0;
}
// @ competetive coding STRAWBERRY
| 18.242424
| 67
| 0.616279
|
CrispenGari
|
44e5a903b3287a21da7c1b1ffa5bd1197bb25453
| 599
|
cpp
|
C++
|
Difficulty 2/fluortanten.cpp
|
BrynjarGeir/Kattis
|
a151972cbae3db04a8e6764d5fa468d0146c862b
|
[
"MIT"
] | null | null | null |
Difficulty 2/fluortanten.cpp
|
BrynjarGeir/Kattis
|
a151972cbae3db04a8e6764d5fa468d0146c862b
|
[
"MIT"
] | null | null | null |
Difficulty 2/fluortanten.cpp
|
BrynjarGeir/Kattis
|
a151972cbae3db04a8e6764d5fa468d0146c862b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
int calc_sum(vector<int> numbers) {
int ans = 0;
for(int i = 1; i <= numbers.size(); i++) ans += i * numbers.at(i-1);
return ans;
}
int main() {
int n, number, pos;
cin >> n;
vector<pair<int, int>> numbers;
for(int i = 0; i < n; i++) {
cin >> number;
if(number == 0) pos = i;
numbers.push_back(number);
}
int max_happiness = INT32_MIN, ps = -1;
for(int i = 1; i < n; i++) max_happiness = max(max_happiness, calc_sum(swap(numbers, i, pos)));
cout << max_happiness;
}
| 21.392857
| 99
| 0.557596
|
BrynjarGeir
|
44e5dfa02242f7d12230a06294f51d7fe06a5a06
| 1,451
|
hxx
|
C++
|
Legolas/Vector/VirtualVector.hxx
|
LaurentPlagne/Legolas
|
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
|
[
"MIT"
] | null | null | null |
Legolas/Vector/VirtualVector.hxx
|
LaurentPlagne/Legolas
|
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
|
[
"MIT"
] | null | null | null |
Legolas/Vector/VirtualVector.hxx
|
LaurentPlagne/Legolas
|
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
|
[
"MIT"
] | 1
|
2021-02-11T14:43:25.000Z
|
2021-02-11T14:43:25.000Z
|
#pragma once
#include <cstdlib>
namespace Legolas{
class VirtualVector {
public:
// virtual int getSize( void ) const = 0 ;
typedef std::size_t SizeType;
virtual SizeType size( void ) const = 0 ;
virtual const VirtualVector & getElement( SizeType i ) const = 0 ;
virtual VirtualVector & getElement( SizeType i ) = 0 ;
virtual VirtualVector * clone( void ) const = 0 ;
virtual VirtualVector * newVirtualVector( const VirtualVectorShape & shape) const = 0 ;
virtual ~VirtualVector( void ){};
virtual bool sameShape(const VirtualVector & source ) const = 0;
virtual void copy(const VirtualVector & source) = 0 ;
virtual void scale( double a ) =0 ;
virtual double relativeDiffAndCopy( const VirtualVector & source ) = 0;
virtual void plusAssign(double factor, const VirtualVector & source) = 0;
virtual double dot(const VirtualVector & source) const = 0;
virtual void scaleAndPlusAssign(double scaleFactor, double factor,const VirtualVector & source) = 0;
virtual void display( void ) const =0;
typedef VirtualVector * VirtualVectorPtr;
static inline VirtualVector & getClone(VirtualVectorPtr & vecPtr,const VirtualVector & source){
if (!vecPtr){
vecPtr=source.clone();
}
else{
if (!vecPtr->sameShape(source)){
delete vecPtr;
vecPtr=source.clone();
}
else{
vecPtr->copy(source);
}
}
return (*vecPtr);
}
};
}
| 30.87234
| 104
| 0.673329
|
LaurentPlagne
|
44ea1cd2cb3edc3ee3cfe10d4fbfcfd4ae550453
| 3,363
|
cpp
|
C++
|
src/cli/main.cpp
|
brio1009/ElTrazadoDeRayos
|
8c65eb9c7724812ab9f8103fd00a28324753e4b6
|
[
"BSL-1.0",
"MIT"
] | null | null | null |
src/cli/main.cpp
|
brio1009/ElTrazadoDeRayos
|
8c65eb9c7724812ab9f8103fd00a28324753e4b6
|
[
"BSL-1.0",
"MIT"
] | null | null | null |
src/cli/main.cpp
|
brio1009/ElTrazadoDeRayos
|
8c65eb9c7724812ab9f8103fd00a28324753e4b6
|
[
"BSL-1.0",
"MIT"
] | null | null | null |
/*
The MIT License (MIT)
Copyright (c) 2014 CantTouchDis <bauschp@informatik.uni-freiburg.de>
Copyright (c) 2014 brio1009 <christoph1009@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// GLM-define, because degree-methods are deprected.
#define GLM_FORCE_RADIANS
// RayTracerLib.
#include <Image.h>
#include <Ray.h>
#include <Scene.h>
#include <cameras/PerspectiveCamera.h>
#include <materials/Material.h>
#include <parser/SceneFileParser.h>
#include <shapes/Ellipsoid.h>
#include <shapes/Plane.h>
// C Header.
#include <omp.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/vector_angle.hpp>
// C++ Header.
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>
//
void renderScene(const char* fileName, size_t chunks, size_t chunkNr) {
// Create the scene. This also adds all the objects.
Scene scene;
// Load the desired Scene.
SceneFileParser sceneParser;
sceneParser.parse("testScene.xml", &scene);
// Render all the images.
scene.render(chunks, chunkNr);
// Get the cameras and save the images.
for (size_t i = 0; i < scene.cameras().size(); ++i) {
// Save the image under different names.
char buff[100];
#ifdef WINDOWS
_snprintf_s(buff, sizeof(buff), "%s%03lu.bmp", fileName, i);
#else
snprintf(buff, sizeof(buff), "%s%03zu.bmp", fileName, i);
#endif // WINDOWS
scene.cameras().at(i)->getImage().saveAsBMP(buff);
}
}
// The main method.
int main(int argc, char** argv) {
const char* fileName = "Img";
// Print usage info.
if (argc > 5) {
printf(
"Usage: %s <optional: output> <optional: chunks chunknr> "
"<optional: random seed>\n",
argv[0]);
exit(EXIT_FAILURE);
}
omp_set_num_threads(1); // TODO: Need to replace rand() in PhongBRDF with
// thread-safe variant.
// Initialize the rand function.
unsigned int seed = static_cast<unsigned int>(time(NULL));
if (argc > 1) {
fileName = argv[1];
}
size_t chunks = 1;
size_t chunkNr = 0;
if (argc > 3) {
chunks = atol(argv[2]);
chunkNr = atol(argv[3]);
}
if (argc == 5) {
seed = static_cast<unsigned int>(atoi(argv[4]));
}
printf("Random seed used: %u\n\n", seed);
srand(seed);
// Render our test scene.
renderScene(fileName, chunks, chunkNr);
}
| 30.853211
| 78
| 0.704728
|
brio1009
|
44ec4114d7fa6efb661cd63cc83691347994eec8
| 364
|
cpp
|
C++
|
PrimeNumber.cpp
|
tusharxsharma/BasicPrograms
|
8aa30da7c1f63d5c7762bb252e65acb76f1b0edd
|
[
"Unlicense"
] | 1
|
2020-03-18T18:40:48.000Z
|
2020-03-18T18:40:48.000Z
|
PrimeNumber.cpp
|
tusharxsharma/BasicPrograms
|
8aa30da7c1f63d5c7762bb252e65acb76f1b0edd
|
[
"Unlicense"
] | null | null | null |
PrimeNumber.cpp
|
tusharxsharma/BasicPrograms
|
8aa30da7c1f63d5c7762bb252e65acb76f1b0edd
|
[
"Unlicense"
] | null | null | null |
#include<iostream>
using namespace std;
int main()
{
int n , x;
cout <<"Enter the number : \n";
cin>>n;
if(n<2)
cout<<"Number is lesser than 2 and not applicable";
else
{
for(x=2;x<n;x++)
{
if(n%x==0)
{
cout<<"Not Prime Number";
exit(0);
}
else
{
cout<<"Prime Number";
exit(1);
}
}
}
}
| 13.481481
| 54
| 0.478022
|
tusharxsharma
|
44ed03145058d315d8572e1838db40ebe2c60e56
| 5,207
|
cpp
|
C++
|
ext/native/java/lang/reflect/Array_-native.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
ext/native/java/lang/reflect/Array_-native.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
ext/native/java/lang/reflect/Array_-native.cpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/lang/reflect/Array_.hpp>
extern void unimplemented_(const char16_t* name);
java::lang::Object* java::lang::reflect::Array_::get(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"java::lang::Object* java::lang::reflect::Array_::get(::java::lang::Object* array, int32_t index)");
return 0;
}
bool java::lang::reflect::Array_::getBoolean(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"bool java::lang::reflect::Array_::getBoolean(::java::lang::Object* array, int32_t index)");
return 0;
}
int8_t java::lang::reflect::Array_::getByte(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int8_t java::lang::reflect::Array_::getByte(::java::lang::Object* array, int32_t index)");
return 0;
}
char16_t java::lang::reflect::Array_::getChar(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"char16_t java::lang::reflect::Array_::getChar(::java::lang::Object* array, int32_t index)");
return 0;
}
double java::lang::reflect::Array_::getDouble(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"double java::lang::reflect::Array_::getDouble(::java::lang::Object* array, int32_t index)");
return 0;
}
float java::lang::reflect::Array_::getFloat(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"float java::lang::reflect::Array_::getFloat(::java::lang::Object* array, int32_t index)");
return 0;
}
int32_t java::lang::reflect::Array_::getInt(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int32_t java::lang::reflect::Array_::getInt(::java::lang::Object* array, int32_t index)");
return 0;
}
int32_t java::lang::reflect::Array_::getLength(::java::lang::Object* array)
{ /* native */
clinit();
unimplemented_(u"int32_t java::lang::reflect::Array_::getLength(::java::lang::Object* array)");
return 0;
}
int64_t java::lang::reflect::Array_::getLong(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int64_t java::lang::reflect::Array_::getLong(::java::lang::Object* array, int32_t index)");
return 0;
}
int16_t java::lang::reflect::Array_::getShort(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int16_t java::lang::reflect::Array_::getShort(::java::lang::Object* array, int32_t index)");
return 0;
}
/* private: java::lang::Object* java::lang::reflect::Array_::multiNewArray_(::java::lang::Class* componentType, ::int32_tArray* dimensions) */
/* private: java::lang::Object* java::lang::reflect::Array_::newArray_(::java::lang::Class* componentType, int32_t length) */
void java::lang::reflect::Array_::set(::java::lang::Object* array, int32_t index, ::java::lang::Object* value)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::set(::java::lang::Object* array, int32_t index, ::java::lang::Object* value)");
}
void java::lang::reflect::Array_::setBoolean(::java::lang::Object* array, int32_t index, bool z)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setBoolean(::java::lang::Object* array, int32_t index, bool z)");
}
void java::lang::reflect::Array_::setByte(::java::lang::Object* array, int32_t index, int8_t b)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setByte(::java::lang::Object* array, int32_t index, int8_t b)");
}
void java::lang::reflect::Array_::setChar(::java::lang::Object* array, int32_t index, char16_t c)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setChar(::java::lang::Object* array, int32_t index, char16_t c)");
}
void java::lang::reflect::Array_::setDouble(::java::lang::Object* array, int32_t index, double d)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setDouble(::java::lang::Object* array, int32_t index, double d)");
}
void java::lang::reflect::Array_::setFloat(::java::lang::Object* array, int32_t index, float f)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setFloat(::java::lang::Object* array, int32_t index, float f)");
}
void java::lang::reflect::Array_::setInt(::java::lang::Object* array, int32_t index, int32_t i)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setInt(::java::lang::Object* array, int32_t index, int32_t i)");
}
void java::lang::reflect::Array_::setLong(::java::lang::Object* array, int32_t index, int64_t l)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setLong(::java::lang::Object* array, int32_t index, int64_t l)");
}
void java::lang::reflect::Array_::setShort(::java::lang::Object* array, int32_t index, int16_t s)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setShort(::java::lang::Object* array, int32_t index, int16_t s)");
}
| 39.44697
| 142
| 0.677165
|
pebble2015
|
44ed72cc0cc7f5374eb6eef7af91e09a046b67b8
| 415
|
cpp
|
C++
|
Source/Python/Concat.cpp
|
andrei-sa/aspen
|
6644663fc19a83fba0603dc4bbd6dbe71cfd55aa
|
[
"Apache-2.0"
] | 2
|
2020-10-16T19:41:19.000Z
|
2021-02-01T04:55:51.000Z
|
Source/Python/Concat.cpp
|
andrei-sa/aspen
|
6644663fc19a83fba0603dc4bbd6dbe71cfd55aa
|
[
"Apache-2.0"
] | 1
|
2020-04-24T18:17:39.000Z
|
2020-04-24T18:37:01.000Z
|
Source/Python/Concat.cpp
|
andrei-sa/aspen
|
6644663fc19a83fba0603dc4bbd6dbe71cfd55aa
|
[
"Apache-2.0"
] | 2
|
2020-04-17T13:24:29.000Z
|
2020-04-24T18:12:29.000Z
|
#include "Aspen/Python/Concat.hpp"
#include "Aspen/Python/Box.hpp"
using namespace Aspen;
using namespace pybind11;
void Aspen::export_concat(pybind11::module& module) {
export_box<SharedBox<object>>(module, "Box");
export_concat<SharedBox<SharedBox<object>>>(module, "");
module.def("concat",
[] (SharedBox<SharedBox<object>> producer) {
return shared_box(concat(std::move(producer)));
});
}
| 27.666667
| 58
| 0.710843
|
andrei-sa
|
44ed970a155b89b6b66713b2058e473d5fd16ba2
| 628
|
hh
|
C++
|
src/Zynga/Framework/Lockable/Cache/V1/Config/Mock/PgData/DevTest.hh
|
zynga/zynga-hacklang-framework
|
2730f354adb684085fff6dca3c1cac1b31502c6b
|
[
"MIT"
] | 19
|
2018-04-23T09:30:48.000Z
|
2022-03-06T21:35:18.000Z
|
src/Zynga/Framework/Lockable/Cache/V1/Config/Mock/PgData/DevTest.hh
|
zynga/zynga-hacklang-framework
|
2730f354adb684085fff6dca3c1cac1b31502c6b
|
[
"MIT"
] | 22
|
2017-11-27T23:39:25.000Z
|
2019-08-09T08:56:57.000Z
|
src/Zynga/Framework/Lockable/Cache/V1/Config/Mock/PgData/DevTest.hh
|
zynga/zynga-hacklang-framework
|
2730f354adb684085fff6dca3c1cac1b31502c6b
|
[
"MIT"
] | 28
|
2017-11-16T20:53:56.000Z
|
2021-01-04T11:13:17.000Z
|
<?hh // strict
namespace Zynga\Framework\Lockable\Cache\V1\Config\Mock\PgData;
use Zynga\Framework\Testing\TestCase\V2\Base as TestCase;
use
Zynga\Framework\Lockable\Cache\V1\Config\Mock\PgData\Dev as ConfigUnderTest
;
use
Zynga\Framework\Cache\V2\Interfaces\DriverInterface as CacheDriverInterface
;
class DevTest extends TestCase {
public function testCreateKeyFromStorableObject(): void {
$obj = new ConfigUnderTest();
$this->assertInstanceOf(CacheDriverInterface::class, $obj->getCache());
$this->assertEquals('Caching', $obj->getDriver());
$this->assertEquals(10, $obj->getLockTTL());
}
}
| 22.428571
| 77
| 0.745223
|
zynga
|
44ee14f5a59b8bfde4cd42497b82448f1e5a706b
| 1,055
|
cpp
|
C++
|
Source/FactorySkyline/UI/FSKeyMappingWidget.cpp
|
RozeDoyanawa/FactorySkyline
|
381d983d8c8fcac7fa9ce3c386d52bd68d2248b6
|
[
"MIT"
] | 3
|
2021-07-09T06:20:11.000Z
|
2022-01-23T09:29:21.000Z
|
Source/FactorySkyline/UI/FSKeyMappingWidget.cpp
|
Nuwisam/FactorySkyline
|
4e4987d2e7f0a67d992d600fc7f280593cee4f94
|
[
"MIT"
] | null | null | null |
Source/FactorySkyline/UI/FSKeyMappingWidget.cpp
|
Nuwisam/FactorySkyline
|
4e4987d2e7f0a67d992d600fc7f280593cee4f94
|
[
"MIT"
] | 6
|
2021-07-11T15:10:12.000Z
|
2022-02-27T02:16:15.000Z
|
// ILikeBanas
#include "FactorySkyline/UI/FSKeyMappingWidget.h"
#include "Components/Image.h"
#include "Components/HorizontalBox.h"
#include "Components/TextBlock.h"
#include "Components/CanvasPanel.h"
#include "Components/CanvasPanelSlot.h"
#include "Components/HorizontalBoxSlot.h"
UFSKeyMappingWidget::UFSKeyMappingWidget(const FObjectInitializer& ObjectInitializer)
:Super(ObjectInitializer)
{
}
void UFSKeyMappingWidget::SetTitle(const FText& Title)
{
this->Title->SetText(Title);
}
void UFSKeyMappingWidget::SetKey(const FText& Key)
{
this->Key->SetText(Key);
}
void UFSKeyMappingWidget::SetPadding(const float& Padding)
{
UHorizontalBoxSlot* Slot = Cast<UHorizontalBoxSlot>(this->Slot);
Slot->SetPadding(FMargin(Padding, 0.0f));
}
void UFSKeyMappingWidget::SetDefaultView()
{
HighLight->SetVisibility(ESlateVisibility::Hidden);
IsHighLight = false;
}
void UFSKeyMappingWidget::SetHighLightView()
{
HighLight->SetVisibility(ESlateVisibility::SelfHitTestInvisible);
IsHighLight = true;
}
| 23.444444
| 86
| 0.756398
|
RozeDoyanawa
|
6021b37b4b61016702c87a1c89be28a7029a45bc
| 1,781
|
cpp
|
C++
|
modules/burdukov_mikhail_horse_min_range/test/test_burdukov_mikhail_horse_min_range.cpp
|
BalovaElena/devtools-course-practice
|
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
|
[
"CC-BY-4.0"
] | null | null | null |
modules/burdukov_mikhail_horse_min_range/test/test_burdukov_mikhail_horse_min_range.cpp
|
BalovaElena/devtools-course-practice
|
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
|
[
"CC-BY-4.0"
] | null | null | null |
modules/burdukov_mikhail_horse_min_range/test/test_burdukov_mikhail_horse_min_range.cpp
|
BalovaElena/devtools-course-practice
|
f8d5774dbb78ec50200c45fd17665ed40fc8c4c5
|
[
"CC-BY-4.0"
] | null | null | null |
// Copyright 2022 Burdukov Mikhail
#include <gtest/gtest.h>
#include "include/horse_min_range.h"
TEST(minHorseRange, Create) {
ASSERT_NO_THROW(minHorseRange hourse);
}
TEST(minHorseRange, Range_without_barriers) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
minHorseRange a(st, fin);
EXPECT_EQ(1, a.calc_range());
}
TEST(minHorseRange, Range_without_barriers1) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
EXPECT_EQ(1, a.calc_range());
}
TEST(minHorseRange, Range_without_barriers3) {
chess_position_t st('a', 1);
chess_position_t fin('b', 7);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
EXPECT_EQ(3, a.calc_range());
}
TEST(minHorseRange, Range_without_barriers4) {
chess_position_t st('a', 1);
chess_position_t fin('g', 8);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
EXPECT_EQ(5, a.calc_range());
}
TEST(minHorseRange, Range_with_barriers) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
chess_position_t bar('g', 8);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
a.set_barrier(bar);
EXPECT_EQ(1, a.calc_range());
}
TEST(minHorseRange, Range_with_barriers1) {
chess_position_t st('a', 1);
chess_position_t fin('b', 7);
chess_position_t bar('g', 8);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
a.set_barrier(bar);
EXPECT_EQ(3, a.calc_range());
}
TEST(minHorseRange, Range_with_barriers3) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
chess_position_t bar('h', 2);
minHorseRange a(st, fin);
a.set_barrier(bar);
EXPECT_EQ(1, a.calc_range());
}
| 23.434211
| 46
| 0.663672
|
BalovaElena
|
6022c8e3220a876440b9cd873111d480e4c8f781
| 1,860
|
cc
|
C++
|
src/BGL/BGLAffine.cc
|
revarbat/Mandoline
|
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
|
[
"BSD-2-Clause-FreeBSD"
] | 17
|
2015-01-07T10:32:06.000Z
|
2021-07-06T11:00:38.000Z
|
src/BGL/BGLAffine.cc
|
revarbat/Mandoline
|
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
|
[
"BSD-2-Clause-FreeBSD"
] | 2
|
2017-08-17T17:44:42.000Z
|
2018-06-14T23:39:04.000Z
|
src/BGL/BGLAffine.cc
|
revarbat/Mandoline
|
1aafd7e6702ef740bcac6ab8c8c43282a104c60a
|
[
"BSD-2-Clause-FreeBSD"
] | 3
|
2015-01-07T10:32:06.000Z
|
2019-03-22T16:56:51.000Z
|
//
// BGLAffine.cc
// Part of the Belfry Geometry Library
//
// Created by GM on 10/13/10.
// Copyright 2010 Belfry Software. All rights reserved.
//
#include "config.h"
#include "BGLAffine.hh"
namespace BGL {
Affine Affine::translationAffine(double dx, double dy)
{
return Affine(1.0, 0.0, 0.0, 1.0, dx, dy);
}
Affine Affine::scalingAffine(double sx, double sy)
{
return Affine(sx, 0.0, 0.0, sy, 0.0, 0.0);
}
Affine Affine::rotationAffine(double radang)
{
double cosv = cos(radang);
double sinv = sin(radang);
return Affine(cosv, -sinv, sinv, cosv, 0.0, 0.0);
}
Affine& Affine::transform(const Affine& aff)
{
double olda = a;
double oldb = b;
double oldc = c;
double oldd = d;
a = aff.a * olda + aff.b * oldc;
b = aff.a * oldb + aff.b * oldd;
c = aff.c * olda + aff.d * oldc;
d = aff.c * oldb + aff.d * oldd;
tx += aff.tx * olda + aff.ty * oldc;
ty += aff.tx * oldb + aff.ty * oldd;
return *this;
}
Affine& Affine::translate(double dx, double dy)
{
return transform(translationAffine(dx,dy));
}
Affine& Affine::scale(double sx, double sy)
{
return transform(scalingAffine(sx,sy));
}
Affine& Affine::scaleAroundPoint(double sx, double sy, double x, double y)
{
translate(-x,-y);
transform(scalingAffine(sx,sy));
translate(x,y);
return *this;
}
Affine& Affine::rotate(double radang)
{
return transform(rotationAffine(radang));
}
Affine& Affine::rotateAroundPoint(double radang, double x, double y)
{
translate(-x,-y);
transform(rotationAffine(radang));
translate(x,y);
return *this;
}
void Affine::transformPoint(double& x, double &y) const
{
double nx = a * x + b * y + tx;
double ny = c * x + d * y + ty;
x = nx;
y = ny;
}
}
// vim: set ts=4 sw=4 nowrap expandtab: settings
| 17.383178
| 74
| 0.609677
|
revarbat
|
6023f4fffb82ea29d1b3546e9969f026ef7d982e
| 244
|
cpp
|
C++
|
1-Iniciante/12/2879.cpp
|
pedrospaulo/01-C-
|
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
|
[
"MIT"
] | null | null | null |
1-Iniciante/12/2879.cpp
|
pedrospaulo/01-C-
|
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
|
[
"MIT"
] | null | null | null |
1-Iniciante/12/2879.cpp
|
pedrospaulo/01-C-
|
d513a2fd87a82d90780aa69782d1a1b73b53d6c1
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
int main(){
int n, t ;
int cont = 0;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &t);
if(t != 1){
cont++;
}
}
printf("%d\n", cont);
return 0;
}
| 12.842105
| 31
| 0.348361
|
pedrospaulo
|
602cac59487adecd87d9608d2df3641c307f5c89
| 6,426
|
hpp
|
C++
|
include/codegen/include/UnityEngine/RemoteConfigSettingsHelper_Tag.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/UnityEngine/RemoteConfigSettingsHelper_Tag.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/UnityEngine/RemoteConfigSettingsHelper_Tag.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.Enum
#include "System/Enum.hpp"
// Including type: UnityEngine.RemoteConfigSettingsHelper
#include "UnityEngine/RemoteConfigSettingsHelper.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Autogenerated type: UnityEngine.RemoteConfigSettingsHelper/Tag
struct RemoteConfigSettingsHelper::Tag : public System::Enum {
public:
// public System.Int32 value__
// Offset: 0x0
int value;
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown
static constexpr const int kUnknown = 0;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kUnknown();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown
static void _set_kUnknown(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal
static constexpr const int kIntVal = 1;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kIntVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal
static void _set_kIntVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val
static constexpr const int kInt64Val = 2;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kInt64Val();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val
static void _set_kInt64Val(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val
static constexpr const int kUInt64Val = 3;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kUInt64Val();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val
static void _set_kUInt64Val(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal
static constexpr const int kDoubleVal = 4;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kDoubleVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal
static void _set_kDoubleVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal
static constexpr const int kBoolVal = 5;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kBoolVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal
static void _set_kBoolVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal
static constexpr const int kStringVal = 6;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kStringVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal
static void _set_kStringVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal
static constexpr const int kArrayVal = 7;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kArrayVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal
static void _set_kArrayVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal
static constexpr const int kMixedArrayVal = 8;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMixedArrayVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal
static void _set_kMixedArrayVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal
static constexpr const int kMapVal = 9;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMapVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal
static void _set_kMapVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags
static constexpr const int kMaxTags = 10;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMaxTags();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags
static void _set_kMaxTags(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// Creating value type constructor for type: Tag
Tag(int value_ = {}) : value{value_} {}
}; // UnityEngine.RemoteConfigSettingsHelper/Tag
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::RemoteConfigSettingsHelper::Tag, "UnityEngine", "RemoteConfigSettingsHelper/Tag");
#pragma pack(pop)
| 67.642105
| 118
| 0.791161
|
Futuremappermydud
|
602e5783df692bdeec4e840456c43ba5b1171211
| 5,585
|
cpp
|
C++
|
openbabel-2.4.1/src/ops/opconfab.cpp
|
sxhexe/reaction-route-search
|
f7694c84ca1def4a133ade3e1e2e09705cd28312
|
[
"MIT"
] | 1
|
2017-09-16T07:36:29.000Z
|
2017-09-16T07:36:29.000Z
|
openbabel-2.4.1/src/ops/opconfab.cpp
|
sxhexe/reaction-route-search
|
f7694c84ca1def4a133ade3e1e2e09705cd28312
|
[
"MIT"
] | null | null | null |
openbabel-2.4.1/src/ops/opconfab.cpp
|
sxhexe/reaction-route-search
|
f7694c84ca1def4a133ade3e1e2e09705cd28312
|
[
"MIT"
] | null | null | null |
/**********************************************************************
opconfab.cpp - Confab, the conformer generator described in
Journal of Cheminformatics, 3, 1, 8
http://www.jcheminf.com/content/3/1/8
Copyright (C) 2013 by Noel O'Boyle
This file is part of the Open Babel project.
For more information, see <http://openbabel.org/>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***********************************************************************/
#include <openbabel/babelconfig.h>
#include <iostream>
#include<openbabel/op.h>
#include<openbabel/mol.h>
#include<openbabel/forcefield.h>
#include <openbabel/obconversion.h>
#include<openbabel/generic.h>
#define CONFAB_VER "1.1.0"
namespace OpenBabel
{
using namespace std;
//////////////////////////////////////////////////////////
//
// Confab
//
//////////////////////////////////////////////////////////
class Confab
{
public:
Confab() {};
};
class OpConfab : public OBOp
{
public:
OpConfab(const char* ID) : OBOp(ID, false) {
}
const char* Description()
{
return "Confab, the diverse conformer generator\n"
"Typical usage: obabel infile.xxx -O outfile.yyy --confab --conf 1000000\n"
" options:\n"
" --conf # Max number of conformers to test (default is 1 million)\n"
" --rcutoff # RMSD cutoff (default 0.5 Angstrom)\n"
" --ecutoff # Energy cutoff (default 50.0 kcal/mol)\n"
" --original Include the input conformation as the first conformer\n"
" --verbose Verbose output\n"
;
}
virtual bool WorksWith(OBBase* pOb) const
{
return dynamic_cast<OBMol*>(pOb) != NULL;
}
virtual bool Do(OBBase* pOb, const char* OptionText, OpMap* pmap, OBConversion*);
void DisplayConfig(OBConversion* pConv);
void Run(OBConversion* pConv, OBMol* pmol);
double rmsd_cutoff;
double energy_cutoff;
unsigned int conf_cutoff;
bool verbose;
bool include_original;
unsigned int N;
OBForceField *pff;
};
//////////////////////////////////////////////////////////
OpConfab theConfab("confab"); //Global instance
//////////////////////////////////////////////////////////
bool OpConfab::Do(OBBase* pOb, const char* OptionText, OpMap* pmap, OBConversion* pConv=NULL)
{
OBMol* pmol = dynamic_cast<OBMol*>(pOb);
if(!pmol)
return false;
if(pConv->IsFirstInput())
{
pConv->AddOption("writeconformers", OBConversion::GENOPTIONS);
rmsd_cutoff = 0.5;
energy_cutoff = 50.0;
conf_cutoff = 1000000; // 1 Million
verbose = false;
include_original = false;
OpMap::const_iterator iter;
iter = pmap->find("rcutoff");
if(iter!=pmap->end())
rmsd_cutoff = atof(iter->second.c_str());
iter = pmap->find("ecutoff");
if(iter!=pmap->end())
energy_cutoff = atof(iter->second.c_str());
iter = pmap->find("conf");
if(iter!=pmap->end())
conf_cutoff = atoi(iter->second.c_str());
iter = pmap->find("verbose");
if(iter!=pmap->end())
verbose = true;
iter = pmap->find("original");
if(iter!=pmap->end())
include_original = true;
cout << "**Starting Confab " << CONFAB_VER << "\n";
cout << "**To support, cite Journal of Cheminformatics, 2011, 3, 8.\n";
pff = OpenBabel::OBForceField::FindType("mmff94");
if (!pff) {
cout << "!!Cannot find forcefield!" << endl;
exit(-1);
}
DisplayConfig(pConv);
}
Run(pConv, pmol);
return false;
}
void OpConfab::Run(OBConversion* pConv, OBMol* pmol)
{
OBMol mol = *pmol;
N++;
cout << "**Molecule " << N << endl << "..title = " << mol.GetTitle() << endl;
cout << "..number of rotatable bonds = " << mol.NumRotors() << endl;
mol.AddHydrogens();
bool success = pff->Setup(mol);
if (!success) {
cout << "!!Cannot set up forcefield for this molecule\n"
<< "!!Skipping\n" << endl;
return;
}
pff->DiverseConfGen(rmsd_cutoff, conf_cutoff, energy_cutoff, verbose);
pff->GetConformers(mol);
int nconfs = include_original ? mol.NumConformers() : mol.NumConformers() - 1;
cout << "..generated " << nconfs << " conformers" << endl;
unsigned int c = include_original ? 0 : 1;
for (; c < mol.NumConformers(); ++c) {
mol.SetConformer(c);
if(!pConv->GetOutFormat()->WriteMolecule(&mol, pConv))
break;
}
cout << endl;
}
void OpConfab::DisplayConfig(OBConversion* pConv)
{
cout << "..Input format = " << pConv->GetInFormat()->GetID() << endl;
cout << "..Output format = " << pConv->GetOutFormat()->GetID() << endl;
cout << "..RMSD cutoff = " << rmsd_cutoff << endl;
cout << "..Energy cutoff = " << energy_cutoff << endl;
cout << "..Conformer cutoff = " << conf_cutoff << endl;
cout << "..Write input conformation? " << (include_original ? "True" : "False") << endl;
cout << "..Verbose? " << (verbose ? "True" : "False") << endl;
cout << endl;
}
}//namespace
| 30.519126
| 95
| 0.563474
|
sxhexe
|
602e62a0db31d1a5f427d0dd51730f3182861d4b
| 1,763
|
cpp
|
C++
|
tests/test-lru.cpp
|
lcapaldo/c-server-sdk
|
87edbe872b5f5fa6e797a6e26e89faf941958679
|
[
"Apache-2.0"
] | 5
|
2019-10-08T05:05:40.000Z
|
2022-03-23T10:46:27.000Z
|
tests/test-lru.cpp
|
lcapaldo/c-server-sdk
|
87edbe872b5f5fa6e797a6e26e89faf941958679
|
[
"Apache-2.0"
] | 8
|
2020-01-18T02:16:27.000Z
|
2022-02-23T21:28:07.000Z
|
tests/test-lru.cpp
|
lcapaldo/c-server-sdk
|
87edbe872b5f5fa6e797a6e26e89faf941958679
|
[
"Apache-2.0"
] | 6
|
2019-12-13T21:00:11.000Z
|
2021-06-09T09:55:13.000Z
|
#include "gtest/gtest.h"
#include "commonfixture.h"
extern "C" {
#include <launchdarkly/api.h>
#include "lru.h"
#include "utility.h"
}
// Inherit from the CommonFixture to give a reasonable name for the test output.
// Any custom setup and teardown would happen in this derived class.
class LRUFixture : public CommonFixture {
};
TEST_F(LRUFixture, InsertExisting) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(10));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "abc"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "abc"));
LDLRUFree(lru);
}
TEST_F(LRUFixture, MaxCapacity) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(2));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "789"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "789"));
LDLRUFree(lru);
}
TEST_F(LRUFixture, AccessBumpsPosition) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(3));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "789"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "ABC"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456"));
LDLRUFree(lru);
}
TEST_F(LRUFixture, ZeroCapacityAlwaysNew) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(0));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
LDLRUFree(lru);
}
| 26.313433
| 80
| 0.708452
|
lcapaldo
|
602ea5aff6011c0240d47a0ca748cb490bbd778c
| 2,016
|
cpp
|
C++
|
lab9/cpp/task-2/main.cpp
|
mihaimusat/PA-labs-2019
|
113e833dc7fbe2bd5455e2552dde1d8b20931db9
|
[
"MIT"
] | null | null | null |
lab9/cpp/task-2/main.cpp
|
mihaimusat/PA-labs-2019
|
113e833dc7fbe2bd5455e2552dde1d8b20931db9
|
[
"MIT"
] | null | null | null |
lab9/cpp/task-2/main.cpp
|
mihaimusat/PA-labs-2019
|
113e833dc7fbe2bd5455e2552dde1d8b20931db9
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cassert>
using namespace std;
const int kNmax = 50005;
const int inf = 999999;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
int n;
int m;
int source;
vector<pair<int, int> > adj[kNmax];
void read_input() {
ifstream fin("in");
fin >> n >> m >> source;
for (int i = 1, x, y, w; i <= m; i++) {
fin >> x >> y >> w;
adj[x].push_back(make_pair(y, w));
}
fin.close();
}
vector<int> get_result() {
/*
TODO: Gasiti distantele minime de la nodul source la celelalte noduri
folosind BellmanFord pe graful orientat cu n noduri, m arce stocat in adj.
d[node] = costul minim / lungimea minima a unui drum de la source la nodul
node;
d[source] = 0;
d[node] = -1, daca nu se poate ajunge de la source la node.
Atentie:
O muchie este tinuta ca o pereche (nod adiacent, cost muchie):
adj[x][i].first = nodul adiacent lui x,
adj[x][i].second = costul.
In cazul in care exista ciclu de cost negativ, returnati un vector gol:
return vector<int>();
*/
vector<int> d(n + 1, inf);
queue<int> q;
vector<int> visited(n + 1, 0);
d[source] = 0;
q.push(source);
while(!q.empty()) {
int node = q.front();
q.pop();
visited[node]++;
if(visited[node] == n) {
return vector<int>();
}
for(auto& edge : adj[node]) {
if(d[edge.first] >= d[node] + edge.second) {
d[edge.first] = d[node] + edge.second;
q.push(edge.first);
}
}
}
for(int i = 1; i <= n; i++) {
if(d[i] == inf) {
d[i] = -1;
}
}
return d;
}
void print_output(vector<int> result) {
ofstream fout("out");
if (result.size() == 0) {
fout << "Ciclu negativ!\n";
} else {
for (int i = 1; i <= n; i++) {
fout << result[i] << ' ';
}
fout << '\n';
}
fout.close();
}
};
int main() {
Task *task = new Task();
task->solve();
delete task;
return 0;
}
| 19.572816
| 77
| 0.564484
|
mihaimusat
|
603035979813b2c6fa11457dbafc6893d44c09fc
| 13,092
|
cpp
|
C++
|
src/muz/transforms/dl_mk_quantifier_abstraction.cpp
|
akreuzer/z3
|
e8917a1a9f97db86bdc38c569ddbde7f79b76ce7
|
[
"MIT"
] | 3
|
2020-07-15T19:50:12.000Z
|
2020-12-13T17:28:16.000Z
|
src/muz/transforms/dl_mk_quantifier_abstraction.cpp
|
akreuzer/z3
|
e8917a1a9f97db86bdc38c569ddbde7f79b76ce7
|
[
"MIT"
] | null | null | null |
src/muz/transforms/dl_mk_quantifier_abstraction.cpp
|
akreuzer/z3
|
e8917a1a9f97db86bdc38c569ddbde7f79b76ce7
|
[
"MIT"
] | 3
|
2020-04-12T11:00:44.000Z
|
2021-10-20T22:08:44.000Z
|
/*++
Copyright (c) 2013 Microsoft Corporation
Module Name:
dl_mk_quantifier_abstraction.cpp
Abstract:
Create quantified Horn clauses from benchmarks with arrays.
Author:
Ken McMillan
Andrey Rybalchenko
Nikolaj Bjorner (nbjorner) 2013-04-02
Revision History:
--*/
#include "muz/transforms/dl_mk_quantifier_abstraction.h"
#include "muz/base/dl_context.h"
#include "ast/rewriter/expr_safe_replace.h"
#include "ast/expr_abstract.h"
namespace datalog {
// model converter:
// Given model for P^(x, y, i, a[i])
// create model: P(x,y,a) == forall i . P^(x,y,i,a[i])
// requires substitution and list of bound variables.
class mk_quantifier_abstraction::qa_model_converter : public model_converter {
ast_manager& m;
func_decl_ref_vector m_old_funcs;
func_decl_ref_vector m_new_funcs;
vector<expr_ref_vector> m_subst;
vector<sort_ref_vector> m_sorts;
vector<bool_vector > m_bound;
public:
qa_model_converter(ast_manager& m):
m(m), m_old_funcs(m), m_new_funcs(m) {}
~qa_model_converter() override {}
model_converter * translate(ast_translation & translator) override {
return alloc(qa_model_converter, m);
}
void display(std::ostream& out) override { display_add(out, m); }
void get_units(obj_map<expr, bool>& units) override { units.reset(); }
void insert(func_decl* old_p, func_decl* new_p, expr_ref_vector& sub, sort_ref_vector& sorts, bool_vector const& bound) {
m_old_funcs.push_back(old_p);
m_new_funcs.push_back(new_p);
m_subst.push_back(sub);
m_bound.push_back(bound);
m_sorts.push_back(sorts);
}
void operator()(model_ref & old_model) override {
model_ref new_model = alloc(model, m);
for (unsigned i = 0; i < m_new_funcs.size(); ++i) {
func_decl* p = m_new_funcs.get(i);
func_decl* q = m_old_funcs.get(i);
expr_ref_vector const& sub = m_subst[i];
sort_ref_vector const& sorts = m_sorts[i];
bool_vector const& is_bound = m_bound[i];
func_interp* f = old_model->get_func_interp(p);
expr_ref body(m);
SASSERT(0 < p->get_arity());
if (f) {
body = f->get_interp();
SASSERT(!f->is_partial());
SASSERT(body);
}
else {
expr_ref_vector args(m);
for (unsigned i = 0; i < p->get_arity(); ++i) {
args.push_back(m.mk_var(i, p->get_domain(i)));
}
body = m.mk_app(p, args);
}
// Create quantifier wrapper around body.
TRACE("dl", tout << body << "\n";);
// 1. replace variables by the compound terms from
// the original predicate.
expr_safe_replace rep(m);
for (unsigned i = 0; i < sub.size(); ++i) {
rep.insert(m.mk_var(i, sub[i]->get_sort()), sub[i]);
}
rep(body);
rep.reset();
TRACE("dl", tout << body << "\n";);
// 2. replace bound variables by constants.
expr_ref_vector consts(m), bound(m), _free(m);
svector<symbol> names;
ptr_vector<sort> bound_sorts;
for (unsigned i = 0; i < sorts.size(); ++i) {
sort* s = sorts[i];
consts.push_back(m.mk_fresh_const("C", s));
rep.insert(m.mk_var(i, s), consts.back());
if (is_bound[i]) {
bound.push_back(consts.back());
names.push_back(symbol(i));
bound_sorts.push_back(s);
}
else {
_free.push_back(consts.back());
}
}
rep(body);
rep.reset();
TRACE("dl", tout << body << "\n";);
// 3. abstract and quantify those variables that should be bound.
body = expr_abstract(bound, body);
body = m.mk_forall(names.size(), bound_sorts.c_ptr(), names.c_ptr(), body);
TRACE("dl", tout << body << "\n";);
// 4. replace remaining constants by variables.
unsigned j = 0;
for (expr* f : _free) {
rep.insert(f, m.mk_var(j++, f->get_sort()));
}
rep(body);
new_model->register_decl(q, body);
TRACE("dl", tout << body << "\n";);
}
old_model = new_model;
}
};
mk_quantifier_abstraction::mk_quantifier_abstraction(
context & ctx, unsigned priority):
plugin(priority),
m(ctx.get_manager()),
m_ctx(ctx),
a(m),
m_refs(m),
m_mc(nullptr) {
}
mk_quantifier_abstraction::~mk_quantifier_abstraction() {
}
func_decl* mk_quantifier_abstraction::declare_pred(rule_set const& rules, rule_set& dst, func_decl* old_p) {
if (rules.is_output_predicate(old_p)) {
dst.inherit_predicate(rules, old_p, old_p);
return nullptr;
}
unsigned sz = old_p->get_arity();
unsigned num_arrays = 0;
for (unsigned i = 0; i < sz; ++i) {
if (a.is_array(old_p->get_domain(i))) {
num_arrays++;
}
}
if (num_arrays == 0) {
return nullptr;
}
func_decl* new_p = nullptr;
if (!m_old2new.find(old_p, new_p)) {
expr_ref_vector sub(m), vars(m);
bool_vector bound;
sort_ref_vector domain(m), sorts(m);
expr_ref arg(m);
for (unsigned i = 0; i < sz; ++i) {
sort* s0 = old_p->get_domain(i);
unsigned lookahead = 0;
sort* s = s0;
while (a.is_array(s)) {
lookahead += get_array_arity(s);
s = get_array_range(s);
}
arg = m.mk_var(bound.size() + lookahead, s0);
s = s0;
while (a.is_array(s)) {
unsigned arity = get_array_arity(s);
expr_ref_vector args(m);
for (unsigned j = 0; j < arity; ++j) {
sort* s1 = get_array_domain(s, j);
domain.push_back(s1);
args.push_back(m.mk_var(bound.size(), s1));
bound.push_back(true);
sorts.push_back(s1);
}
arg = mk_select(arg, args.size(), args.c_ptr());
s = get_array_range(s);
}
domain.push_back(s);
bound.push_back(false);
sub.push_back(arg);
sorts.push_back(s0);
}
SASSERT(old_p->get_range() == m.mk_bool_sort());
new_p = m.mk_func_decl(old_p->get_name(), domain.size(), domain.c_ptr(), old_p->get_range());
m_refs.push_back(new_p);
m_ctx.register_predicate(new_p, false);
if (m_mc) {
m_mc->insert(old_p, new_p, sub, sorts, bound);
}
m_old2new.insert(old_p, new_p);
}
return new_p;
}
app_ref mk_quantifier_abstraction::mk_head(rule_set const& rules, rule_set& dst, app* p, unsigned idx) {
func_decl* new_p = declare_pred(rules, dst, p->get_decl());
if (!new_p) {
return app_ref(p, m);
}
expr_ref_vector args(m);
expr_ref arg(m);
unsigned sz = p->get_num_args();
for (unsigned i = 0; i < sz; ++i) {
arg = p->get_arg(i);
sort* s = arg->get_sort();
while (a.is_array(s)) {
unsigned arity = get_array_arity(s);
for (unsigned j = 0; j < arity; ++j) {
args.push_back(m.mk_var(idx++, get_array_domain(s, j)));
}
arg = mk_select(arg, arity, args.c_ptr()+args.size()-arity);
s = get_array_range(s);
}
args.push_back(arg);
}
TRACE("dl",
tout << mk_pp(new_p, m) << "\n";
for (unsigned i = 0; i < args.size(); ++i) {
tout << mk_pp(args[i].get(), m) << "\n";
});
return app_ref(m.mk_app(new_p, args.size(), args.c_ptr()), m);
}
app_ref mk_quantifier_abstraction::mk_tail(rule_set const& rules, rule_set& dst, app* p) {
func_decl* old_p = p->get_decl();
func_decl* new_p = declare_pred(rules, dst, old_p);
if (!new_p) {
return app_ref(p, m);
}
SASSERT(new_p->get_arity() > old_p->get_arity());
unsigned num_extra_args = new_p->get_arity() - old_p->get_arity();
var_shifter shift(m);
expr_ref p_shifted(m);
shift(p, num_extra_args, p_shifted);
app* ps = to_app(p_shifted);
expr_ref_vector args(m);
app_ref_vector pats(m);
sort_ref_vector vars(m);
svector<symbol> names;
expr_ref arg(m);
unsigned idx = 0;
unsigned sz = p->get_num_args();
for (unsigned i = 0; i < sz; ++i) {
arg = ps->get_arg(i);
sort* s = arg->get_sort();
bool is_pattern = false;
while (a.is_array(s)) {
is_pattern = true;
unsigned arity = get_array_arity(s);
for (unsigned j = 0; j < arity; ++j) {
vars.push_back(get_array_domain(s, j));
names.push_back(symbol(idx));
args.push_back(m.mk_var(idx++, vars.back()));
}
arg = mk_select(arg, arity, args.c_ptr()+args.size()-arity);
s = get_array_range(s);
}
if (is_pattern) {
pats.push_back(to_app(arg));
}
args.push_back(arg);
}
expr* pat = nullptr;
expr_ref pattern(m);
pattern = m.mk_pattern(pats.size(), pats.c_ptr());
pat = pattern.get();
app_ref result(m);
symbol qid, skid;
result = m.mk_app(new_p, args.size(), args.c_ptr());
result = m.mk_eq(m.mk_forall(vars.size(), vars.c_ptr(), names.c_ptr(), result, 1, qid, skid, 1, &pat), m.mk_true());
return result;
}
expr * mk_quantifier_abstraction::mk_select(expr* arg, unsigned num_args, expr* const* args) {
ptr_vector<expr> args2;
args2.push_back(arg);
args2.append(num_args, args);
return a.mk_select(args2.size(), args2.c_ptr());
}
rule_set * mk_quantifier_abstraction::operator()(rule_set const & source) {
if (!m_ctx.quantify_arrays()) {
return nullptr;
}
unsigned sz = source.get_num_rules();
for (unsigned i = 0; i < sz; ++i) {
rule& r = *source.get_rule(i);
if (r.has_negation()) {
return nullptr;
}
}
m_refs.reset();
m_old2new.reset();
m_new2old.reset();
rule_manager& rm = source.get_rule_manager();
rule_ref new_rule(rm);
expr_ref_vector tail(m);
app_ref head(m);
expr_ref fml(m);
rule_counter& vc = rm.get_counter();
if (m_ctx.get_model_converter()) {
m_mc = alloc(qa_model_converter, m);
}
scoped_ptr<rule_set> result = alloc(rule_set, m_ctx);
for (unsigned i = 0; i < sz; ++i) {
tail.reset();
rule & r = *source.get_rule(i);
TRACE("dl", r.display(m_ctx, tout); );
unsigned cnt = vc.get_max_rule_var(r)+1;
unsigned utsz = r.get_uninterpreted_tail_size();
unsigned tsz = r.get_tail_size();
for (unsigned j = 0; j < utsz; ++j) {
tail.push_back(mk_tail(source, *result, r.get_tail(j)));
}
for (unsigned j = utsz; j < tsz; ++j) {
tail.push_back(r.get_tail(j));
}
head = mk_head(source, *result, r.get_head(), cnt);
fml = m.mk_implies(m.mk_and(tail.size(), tail.c_ptr()), head);
proof_ref pr(m);
rm.mk_rule(fml, pr, *result, r.name());
TRACE("dl", result->last()->display(m_ctx, tout););
}
// proof converter: proofs are not necessarily preserved using this transformation.
if (m_old2new.empty()) {
dealloc(m_mc);
result = nullptr;
}
else {
m_ctx.add_model_converter(m_mc);
}
m_mc = nullptr;
return result.detach();
}
};
| 35.383784
| 129
| 0.498396
|
akreuzer
|