text:
#include "reductions.h"
#include "cb_adf.h"
#include "rand48.h"
#include "bs.h"
#include "gen_cs_example.h"
#include "cb_explore.h"

using namespace LEARNER;
using namespace ACTION_SCORE;
using namespace std;
using namespace CB_ALGS;
//All exploration algorithms return a vector of id, probability tuples, sorted in order of scores. The probabilities are the probability with which each action should be replaced to the top of the list.

//tau first
#define EXPLORE_FIRST 0
//epsilon greedy
#define EPS_GREEDY 1
// bagging explorer
#define BAG_EXPLORE 2
//softmax
#define SOFTMAX 3
//cover
#define COVER 4

namespace CB_EXPLORE_ADF
{

struct cb_explore_adf
{ v_array<example*> ec_seq;
  v_array<action_score> action_probs;

  size_t explore_type;

  size_t tau;
  float epsilon;
  size_t bag_size;
  size_t cover_size;
  float lambda;
  uint64_t offset;

  bool need_to_clear;
  vw* all;
  LEARNER::base_learner* cs_ldf_learner;

  GEN_CS::cb_to_cs_adf gen_cs;
  COST_SENSITIVE::label cs_labels;
  v_array<CB::label> cb_labels;

  CB::label action_label;
  CB::label empty_label;

  COST_SENSITIVE::label cs_labels_2;

  v_array<COST_SENSITIVE::label> prepped_cs_labels;
};

template<class T> void swap(T& ele1, T& ele2)
{ T temp = ele2;
  ele2 = ele1;
  ele1 = temp;
}
template<bool is_learn>
void multiline_learn_or_predict(base_learner& base, v_array<example*>& examples, uint64_t offset, uint32_t id = 0)
{ for (example* ec : examples)
  { uint64_t old_offset = ec->ft_offset;
    ec->ft_offset = offset;
    if (is_learn)
      base.learn(*ec, id);
    else
      base.predict(*ec, id);
    ec->ft_offset = old_offset;
  }
}

example* test_adf_sequence(v_array<example*>& ec_seq)
{ uint32_t count = 0;
  example* ret = nullptr;
  for (size_t k = 0; k < ec_seq.size(); k++)
  { example *ec = ec_seq[k];

    if (ec->l.cb.costs.size() > 1)
      THROW("cb_adf: badly formatted example, only one cost can be known.");

    if (ec->l.cb.costs.size() == 1 && ec->l.cb.costs[0].cost != FLT_MAX)
    { ret = ec;
      count += 1;
    }

    if (CB::ec_is_example_header(*ec))
      if (k != 0)
        THROW("warning: example headers at position " << k << ": can only have in initial position!");
  }
  if (count == 0 || count == 1)
    return ret;
  else
    THROW("cb_adf: badly formatted example, only one line can have a cost");
}

template <bool is_learn>
void predict_or_learn_first(cb_explore_adf& data, base_learner& base, v_array<example*>& examples)
{ //Explore tau times, then act according to optimal.
  if (is_learn && data.gen_cs.known_cost.probability < 1 && test_adf_sequence(data.ec_seq) != nullptr)
    multiline_learn_or_predict<true>(base, examples, data.offset);
  else
    multiline_learn_or_predict<false>(base, examples, data.offset);

  v_array<action_score>& preds = examples[0]->pred.a_s;
  uint32_t num_actions = (uint32_t)preds.size();

  if (data.tau)
  { float prob = 1.f / (float)num_actions;
    for (size_t i = 0; i < num_actions; i++)
      preds[i].score = prob;
    data.tau--;
  }
  else
  { for (size_t i = 1; i < num_actions; i++)
      preds[i].score = 0.;
    preds[0].score = 1.0;
  }
  CB_EXPLORE::safety(preds, data.epsilon, true);
}

  template <bool is_learn>
  void predict_or_learn_greedy(cb_explore_adf& data, base_learner& base, v_array<example*>& examples)
  { //Explore uniform random an epsilon fraction of the time.
    if (is_learn && test_adf_sequence(data.ec_seq) != nullptr)
      multiline_learn_or_predict<true>(base, examples, data.offset);
    else
      multiline_learn_or_predict<false>(base, examples, data.offset);

    v_array<action_score>& preds = examples[0]->pred.a_s;
    uint32_t num_actions = (uint32_t)preds.size();
    float prob = data.epsilon/(float)num_actions;
    for (size_t i = 0; i < num_actions; i++)
      preds[i].score = prob;
    preds[0].score += 1.f - data.epsilon;
  }

  template <bool is_learn>
  void predict_or_learn_bag(cb_explore_adf& data, base_learner& base, v_array<example*>& examples)
  { //Randomize over predictions from a base set of predictors
    v_array<action_score>& preds = examples[0]->pred.a_s;
    uint32_t num_actions = (uint32_t)(examples.size() - 1);
    if (CB::ec_is_example_header(*examples[0]))
      num_actions--;
    if (num_actions == 0)
      {
	preds.erase();
	return;
      }

    data.action_probs.resize(num_actions);
    data.action_probs.erase();
    for (uint32_t i = 0; i < num_actions; i++)
      data.action_probs.push_back({ i,0. });
    float prob = 1.f / (float)data.bag_size;
    bool test_sequence = test_adf_sequence(data.ec_seq) == nullptr;
    for (uint32_t i = 0; i < data.bag_size; i++)
      {
		// avoid updates to the random num generator
	uint32_t count = is_learn ? BS::weight_gen(*data.all) : 0;
	if (is_learn && count > 0 && !test_sequence)
	  multiline_learn_or_predict<true>(base, examples, data.offset, i);
	else
	  multiline_learn_or_predict<false>(base, examples, data.offset, i);
	assert(preds.size() == num_actions);
	data.action_probs[preds[0].action].score += prob;
	if (is_learn && !test_sequence)
	  for (uint32_t j = 1; j < count; j++)
	    multiline_learn_or_predict<true>(base, examples, data.offset, i);
      }

    CB_EXPLORE::safety(data.action_probs, data.epsilon, true);
    qsort((void*) data.action_probs.begin(), data.action_probs.size(), sizeof(action_score), reverse_order);

    for (size_t i = 0; i < num_actions; i++)
      preds[i] = data.action_probs[i];
  }

template <bool is_learn>
void predict_or_learn_cover(cb_explore_adf& data, base_learner& base, v_array<example*>& examples)
{ //Randomize over predictions from a base set of predictors
  //Use cost sensitive oracle to cover actions to form distribution.
  if (is_learn)
  { GEN_CS::gen_cs_example<false>(data.gen_cs, examples, data.cs_labels);
    multiline_learn_or_predict<true>(base, examples, data.offset);
  }
  else
  { GEN_CS::gen_cs_example_ips(examples, data.cs_labels);
    multiline_learn_or_predict<false>(base, examples, data.offset);
  }

  v_array<action_score>& preds = examples[0]->pred.a_s;
  uint32_t num_actions = (uint32_t)preds.size();

  float additive_probability = 1.f / (float)data.cover_size;
  float min_prob = data.epsilon / num_actions;
  v_array<action_score>& probs = data.action_probs;
  probs.erase();
  for(uint32_t i = 0; i < num_actions; i++)
    probs.push_back({i,0.});

  probs[preds[0].action].score += additive_probability;

  uint32_t shared = CB::ec_is_example_header(*examples[0]) ? 1 : 0;

  float norm = min_prob * num_actions + (additive_probability - min_prob);
  for (size_t i = 1; i < data.cover_size; i++)
  { //Create costs of each action based on online cover
    if (is_learn)
    { data.cs_labels_2.costs.erase();
      if (shared > 0)
        data.cs_labels_2.costs.push_back(data.cs_labels.costs[0]);
      for (uint32_t j = 0; j < num_actions; j++)
      { float pseudo_cost = data.cs_labels.costs[j+shared].x - data.epsilon * min_prob / (max(probs[j].score, min_prob) / norm);
        data.cs_labels_2.costs.push_back({pseudo_cost,j,0.,0.});
      }
      GEN_CS::call_cs_ldf<true>(*(data.cs_ldf_learner), examples, data.cb_labels, data.cs_labels_2, data.prepped_cs_labels, data.offset, i+1);
    }
    else
      GEN_CS::call_cs_ldf<false>(*(data.cs_ldf_learner), examples, data.cb_labels, data.cs_labels, data.prepped_cs_labels, data.offset, i+1);

    uint32_t action = preds[0].action;
    if (probs[action].score < min_prob)
      norm += max(0, additive_probability - (min_prob - probs[action].score));
    else
      norm += additive_probability;
    probs[action].score += additive_probability;
  }

  CB_EXPLORE::safety(data.action_probs, data.epsilon, true);

  qsort((void*) probs.begin(), probs.size(), sizeof(action_score), reverse_order);
  for (size_t i = 0; i < num_actions; i++)
    preds[i] = probs[i];
}

template <bool is_learn>
void predict_or_learn_softmax(cb_explore_adf& data, base_learner& base, v_array<example*>& examples)
{ if (is_learn && test_adf_sequence(data.ec_seq) != nullptr)
    multiline_learn_or_predict<true>(base, examples, data.offset);
  else
    multiline_learn_or_predict<false>(base, examples, data.offset);

  v_array<action_score>& preds = examples[0]->pred.a_s;
  uint32_t num_actions = (uint32_t)preds.size();
  float norm = 0.;
  float max_score = preds[0].score;
  for (size_t i = 1; i < num_actions; i++)
    if (max_score < preds[i].score)
      max_score = preds[i].score;

  for (size_t i = 0; i < num_actions; i++)
  { float prob = exp(data.lambda*(preds[i].score - max_score));
    preds[i].score = prob;
     norm += prob;
  }
  for (size_t i = 0; i < num_actions; i++)
    preds[i].score /= norm;
  CB_EXPLORE::safety(preds, data.epsilon, true);
}

void end_examples(cb_explore_adf& data)
{ if (data.need_to_clear)
    data.ec_seq.erase();
}

void finish(cb_explore_adf& data)
{ data.ec_seq.delete_v();
  data.action_probs.delete_v();
  data.cs_labels.costs.delete_v();
  data.cs_labels_2.costs.delete_v();
  data.cb_labels.delete_v();
  for(size_t i = 0; i < data.prepped_cs_labels.size(); i++)
    data.prepped_cs_labels[i].costs.delete_v();
  data.prepped_cs_labels.delete_v();
  data.gen_cs.pred_scores.costs.delete_v();
}

//Semantics: Currently we compute the IPS loss no matter what flags
//are specified. We print the first action and probability, based on
//ordering by scores in the final output.

void output_example(vw& all, cb_explore_adf& c, example& ec, v_array<example*>* ec_seq)
{ if (CB_ALGS::example_is_newline_not_header(ec)) return;

  size_t num_features = 0;

  float loss = 0.;
  ACTION_SCORE::action_scores preds = (*ec_seq)[0]->pred.a_s;

  for (size_t i = 0; i < (*ec_seq).size(); i++)
    if (!CB::ec_is_example_header(*(*ec_seq)[i]))
      num_features += (*ec_seq)[i]->num_features;

  bool is_test = false;
  if (c.gen_cs.known_cost.probability > 0)
  { for (uint32_t i = 0; i < preds.size(); i++)
    { float l = get_unbiased_cost(&c.gen_cs.known_cost, preds[i].action);
      loss += l*preds[i].score;
    }
  }
  else
    is_test = true;
  all.sd->update(ec.test_only, c.gen_cs.known_cost.probability > 0, loss, ec.weight, num_features);

  for (int sink : all.final_prediction_sink)
    print_action_score(sink, ec.pred.a_s, ec.tag);

  if (all.raw_prediction > 0)
  { string outputString;
    stringstream outputStringStream(outputString);
    v_array<CB::cb_class> costs = ec.l.cb.costs;

    for (size_t i = 0; i < costs.size(); i++)
    { if (i > 0) outputStringStream << ' ';
      outputStringStream << costs[i].action << ':' << costs[i].partial_prediction;
    }
    all.print_text(all.raw_prediction, outputStringStream.str(), ec.tag);
  }

  CB::print_update(all, is_test, ec, ec_seq, true);
}

void output_example_seq(vw& all, cb_explore_adf& data)
{ if (data.ec_seq.size() > 0)
  { output_example(all, data, **(data.ec_seq.begin()), &(data.ec_seq));
    if (all.raw_prediction > 0)
      all.print_text(all.raw_prediction, "", data.ec_seq[0]->tag);
  }
}

void clear_seq_and_finish_examples(vw& all, cb_explore_adf& data)
{ if (data.ec_seq.size() > 0)
    for (example* ecc : data.ec_seq)
      if (ecc->in_use)
        VW::finish_example(all, ecc);
  data.ec_seq.erase();
}

void finish_multiline_example(vw& all, cb_explore_adf& data, example& ec)
{ if (data.need_to_clear)
  { if (data.ec_seq.size() > 0)
    { output_example_seq(all, data);
      CB_ADF::global_print_newline(all);
    }
    clear_seq_and_finish_examples(all, data);
    data.need_to_clear = false;
  }
}

template <bool is_learn>
void do_actual_learning(cb_explore_adf& data, base_learner& base)
{ example* label_example=test_adf_sequence(data.ec_seq);
  data.gen_cs.known_cost = CB_ADF::get_observed_cost(data.ec_seq);

  if (label_example == nullptr || !is_learn)
  { if (label_example != nullptr)//extract label
    { data.action_label = label_example->l.cb;
      label_example->l.cb = data.empty_label;
    }
    switch (data.explore_type)
    { case EXPLORE_FIRST:
        predict_or_learn_first<false>(data, base, data.ec_seq);
        break;
      case EPS_GREEDY:
        predict_or_learn_greedy<false>(data, base, data.ec_seq);
        break;
      case SOFTMAX:
        predict_or_learn_softmax<false>(data, base, data.ec_seq);
        break;
      case BAG_EXPLORE:
        predict_or_learn_bag<false>(data, base, data.ec_seq);
        break;
      case COVER:
        predict_or_learn_cover<false>(data, base, data.ec_seq);
        break;
      default:
        THROW("Unknown explorer type specified for contextual bandit learning: " << data.explore_type);
    }
    if (label_example != nullptr)	//restore label
      label_example->l.cb = data.action_label;
  }
  else
  { /*	v_array<float> temp_probs;
    temp_probs = v_init<float>();
    do_actual_learning<false>(data,base);
    for (size_t i = 0; i < data.ec_seq[0]->pred.a_s.size(); i++)
    temp_probs.push_back(data.ec_seq[0]->pred.a_s[i].score);*/

    switch (data.explore_type)
    { case EXPLORE_FIRST:
        predict_or_learn_first<is_learn>(data, base, data.ec_seq);
        break;
      case EPS_GREEDY:
        predict_or_learn_greedy<is_learn>(data, base, data.ec_seq);
        break;
      case SOFTMAX:
        predict_or_learn_softmax<is_learn>(data, base, data.ec_seq);
        break;
      case BAG_EXPLORE:
        predict_or_learn_bag<is_learn>(data, base, data.ec_seq);
        break;
      case COVER:
        predict_or_learn_cover<is_learn>(data, base, data.ec_seq);
        break;
      default:
        THROW("Unknown explorer type specified for contextual bandit learning: " << data.explore_type);
    }

    /*	for (size_t i = 0; i < temp_probs.size(); i++)
      if (temp_probs[i] != data.ec_seq[0]->pred.a_s[i].score)
        cout << "problem! " << temp_probs[i] << " != " << data.ec_seq[0]->pred.a_s[i].score << " for " << data.ec_seq[0]->pred.a_s[i].action << endl;
        temp_probs.delete_v();*/
  }
}

template <bool is_learn>
void predict_or_learn(cb_explore_adf& data, base_learner& base, example &ec)
{ vw* all = data.all;
  //data.base = &base;
  data.offset = ec.ft_offset;
  bool is_test_ec = CB::example_is_test(ec);
  bool need_to_break = VW::is_ring_example(*all, &ec) && (data.ec_seq.size() >= all->p->ring_size - 2);

  if ((CB_ALGS::example_is_newline_not_header(ec) && is_test_ec) || need_to_break)
  { data.ec_seq.push_back(&ec);
    if (data.ec_seq.size() == 1)
      cout << "Something is wrong---an example with no choice.  Do you have all 0 features? Or multiple empty lines?" << endl;
    else
      do_actual_learning<is_learn>(data, base);
    // using flag to clear, because ec_seq is used in finish_example
    data.need_to_clear = true;
  }
  else
  { if (data.need_to_clear)    // should only happen if we're NOT driving
    { data.ec_seq.erase();
      data.need_to_clear = false;
    }
    data.ec_seq.push_back(&ec);
  }
}

}

using namespace CB_EXPLORE_ADF;

base_learner* cb_explore_adf_setup(vw& all)
{ //parse and set arguments
  if (missing_option(all, true, "cb_explore_adf", "Online explore-exploit for a contextual bandit problem with multiline action dependent features"))
    return nullptr;
  new_options(all, "CB_EXPLORE_ADF options")
  ("first", po::value<size_t>(), "tau-first exploration")
  ("epsilon", po::value<float>(), "epsilon-greedy exploration")
  ("bag", po::value<size_t>(), "bagging-based exploration")
  ("cover",po::value<size_t>() ,"Online cover based exploration")
  ("softmax", "softmax exploration")
  ("lambda", po::value<float>(), "parameter for softmax");
  add_options(all);

  po::variables_map& vm = all.vm;
  cb_explore_adf& data = calloc_or_throw<cb_explore_adf>();

  data.all = &all;
  if (count(all.args.begin(), all.args.end(), "--cb_adf") == 0)
    all.args.push_back("--cb_adf");

  all.delete_prediction = delete_action_scores;

  size_t problem_multiplier = 1;
  char type_string[10];

  if (vm.count("epsilon"))
  { data.epsilon = vm["epsilon"].as<float>();
    sprintf(type_string, "%f", data.epsilon);
    *all.file_options << " --epsilon "<<type_string;
  }
  if (vm.count("cover"))
  { data.cover_size = (uint32_t)vm["cover"].as<size_t>();
    data.explore_type = COVER;
    problem_multiplier = data.cover_size+1;
    sprintf(type_string, "%lu", data.cover_size);
    *all.file_options << " --cover " << type_string;

    if (!vm.count("epsilon"))
      data.epsilon = 0.05f;
  }
  else if (vm.count("bag"))
  { data.bag_size = (uint32_t)vm["bag"].as<size_t>();
    data.explore_type = BAG_EXPLORE;
    problem_multiplier = data.bag_size;
    sprintf(type_string, "%lu", data.bag_size);
    *all.file_options << " --bag "<<type_string;
  }
  else if (vm.count("first"))
  { data.tau = (uint32_t)vm["first"].as<size_t>();
    data.explore_type = EXPLORE_FIRST;
    sprintf(type_string, "%lu", data.tau);
    *all.file_options << " --first "<<type_string;
  }
  else if (vm.count("softmax"))
  { data.lambda = 1.0;
    if (vm.count("lambda"))
      data.lambda = (float)vm["lambda"].as<float>();
    data.explore_type = SOFTMAX;
    sprintf(type_string, "%f", data.lambda);
    *all.file_options << " --softmax --lambda "<<type_string;
  }
  else if (vm.count("epsilon"))
    data.explore_type = EPS_GREEDY;
  else //epsilon
  { data.epsilon = 0.05f;
    data.explore_type = EPS_GREEDY;
  }

  base_learner* base = setup_base(all);
  all.p->lp = CB::cb_label;
  all.label_type = label_type::cb;

  learner<cb_explore_adf>& l = init_learner(&data, base, CB_EXPLORE_ADF::predict_or_learn<true>, CB_EXPLORE_ADF::predict_or_learn<false>, problem_multiplier, prediction_type::action_probs);

  //Extract from lower level reductions.
  data.gen_cs.scorer = all.scorer;
  data.cs_ldf_learner = all.cost_sensitive;
  data.gen_cs.cb_type = CB_TYPE_IPS;
  if (all.vm.count("cb_type"))
  { std::string type_string;
    type_string = all.vm["cb_type"].as<std::string>();

    if (type_string.compare("dr") == 0)
      data.gen_cs.cb_type = CB_TYPE_DR;
    else if (type_string.compare("ips") == 0)
      data.gen_cs.cb_type = CB_TYPE_IPS;
    else if (type_string.compare("mtr") == 0)
      if (vm.count("cover"))
      { all.trace_message << "warning: cover and mtr are not simultaneously supported yet, defaulting to ips" << endl;
        data.gen_cs.cb_type = CB_TYPE_IPS;
      }
      else
        data.gen_cs.cb_type = CB_TYPE_MTR;
    else
      all.trace_message << "warning: cb_type must be in {'ips','dr'}; resetting to ips." << std::endl;
  }

  l.set_finish_example(CB_EXPLORE_ADF::finish_multiline_example);
  l.set_finish(CB_EXPLORE_ADF::finish);
  l.set_end_examples(CB_EXPLORE_ADF::end_examples);
  return make_base(l);
}


text:
#include "b04_ETCTextureTest.h"

#include "DebugLog.h"
#include "GLWrapper.h"

/*
 * Constructor and destructor are dummy ones. Only descriptions are set, and other activities are
 * done when calling the virtual benchmark API
 */

b04_ETCTextureTest::b04_ETCTextureTest()
{
    setName("ETC1 texture mapping test");
    setDescription("This test tests texture compression parts of GLES2 and executes a case using ETC texture format");
}

b04_ETCTextureTest::~b04_ETCTextureTest()
{
}

/*
 * initBenchmark() shall initialize all required resources for this test case. If initialization fails,
 * false must be returned to indicate core benchmark not to continue execution. Parent class DebugLog::Instance()->MESSAGE()
 * method can be used to output information about the initialization
 */
bool b04_ETCTextureTest::initBenchmark(void)
{
    const char *texturefilename = "./resources/etctexture.pkm";
    const char vertex_src[] =
       "attribute vec4 a_Position;   \n"
       "attribute vec2 a_Texcoord;   \n"
       "varying vec2 v_Texcoord;     \n"
       "void main()                  \n"
       "{                            \n"
       "   gl_Position = a_Position; \n"
       "   v_Texcoord = a_Texcoord;  \n"
       "}                            \n";
    const char fragment_src[] =
       "precision mediump float;                     \n"
       "varying vec2 v_Texcoord;                     \n"
       "uniform sampler2D s_texture;                 \n"
       "void main()                                  \n"
       "{                                            \n"
       "  gl_FragColor = texture2D(s_texture, v_Texcoord);\n"
       "}                                            \n";

    // Check for support of compressed ETC1 texture format
    if (false == queryCompressedTextureformats())
    {
        DebugLog::Instance()->MESSAGE(1, "Error: ETC1 texture format not supported by the driver\n");
        return false;
    }

    /*
     * Shader program init:
     */
    ss = new SimpleShader();
    if (false == ss->fromFiles(vertex_src, fragment_src))
    {
        DebugLog::Instance()->MESSAGE(2, "Shader program object creation failed\n");
        return false;
    }

    GLWrapper::Instance()->GLBINDATTRIBLOCATION(ss->getProgramObject(), 0, "a_Position");
    GLWrapper::Instance()->GLBINDATTRIBLOCATION(ss->getProgramObject(), 1, "a_Texcoord");
    ss->linkProgram();

    texturesampler = GLWrapper::Instance()->GLGETUNIFORMLOCATION(ss->getProgramObject(), "s_texture");

    /*
     * Texture loading for the test case:
     */
    st = new SimpleTexture();
    if (false == st->fromFile(texturefilename))
    {
        DebugLog::Instance()->MESSAGE(1, "Error: Loading of texturefile '%s' failed.\n", texturefilename);
        return false;
    }

    GLWrapper::Instance()->GLCLEARCOLOR(0.0f, 0.0f, 0.0f, 0.0f);

    // If we have errors in GL pipe, then abort.
    if (GLWrapper::Instance()->getGLErrors() > 0) return false;

    return true;
}

/*
 * destroyBenchmark() shall free all resources allocated by the initBenchmark() method. The core shall
 * call this method once the benchmark case has been run.
 */
bool b04_ETCTextureTest::destroyBenchmark(void)
{
    return true;
}

// Constant vectors for the render test
static GLfloat vVertices[] = {  -0.5f, -0.5f, 0.0f,
                                -0.5f,  0.5f, 0.0f,
                                 0.5f,  0.5f, 0.0f,
                                -0.5f, -0.5f, 0.0f,
                                 0.5f,  0.5f, 0.0f,
                                 0.5f, -0.5f, 0.0f };
static GLfloat vTexcoord[] = { 0.0f, 0.0f,
                               0.0f, 1.0f,
                               1.0f, 1.0f,
                               0.0f, 0.0f,
                               1.0f, 1.0f,
                               1.0f, 0.0f };

void b04_ETCTextureTest::Render(void)
{
    GLWrapper::Instance()->GLVIEWPORT(0, 0, display->getDisplayWidth(), display->getDisplayHeight());
    GLWrapper::Instance()->GLCLEAR(GL_COLOR_BUFFER_BIT);
    GLWrapper::Instance()->GLVERTEXATTRIBPOINTER(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices);
    GLWrapper::Instance()->GLENABLEVERTEXATTRIBARRAY(0);
    GLWrapper::Instance()->GLVERTEXATTRIBPOINTER(1, 2, GL_FLOAT, GL_FALSE, 0, vTexcoord);
    GLWrapper::Instance()->GLENABLEVERTEXATTRIBARRAY(1);

    GLWrapper::Instance()->GLACTIVETEXTURE(GL_TEXTURE0);
    st->bind();
    GLWrapper::Instance()->GLUNIFORM1I(texturesampler, 0);

    GLWrapper::Instance()->GLDRAWARRAYS(GL_TRIANGLES, 0, 6);

    // get the rendered buffer to the screen
    GLWrapper::Instance()->EGLSWAPBUFFERS(display->getEGLDisplay(), display->getEGLSurface());
}

/*
 * renderSingleFrame()
 */
bool b04_ETCTextureTest::renderSingleFrame(float deltatime)
{
    Render();
    return true;
}

/*
 * getRenderStatistics()
 */
bool b04_ETCTextureTest::getRenderStatistics(RENDER_STATISTICS *rs)
{
    return true;
}

bool b04_ETCTextureTest::queryCompressedTextureformats(void)
{
    GLint *v;
    GLint t;
    bool etc1_supported = false;

    // First we query the list of supported compressed texture formats
    glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &t);
    GLWrapper::Instance()->flushGLErrors();
    DebugLog::Instance()->MESSAGE(1, "Number of compressed texture formats supported by the driver: %d\n", t);
    if (t == 0)
    {
        DebugLog::Instance()->MESSAGE(1, "Error: The driver does not support texture compression.\n");
        return false;
    }

    v = new GLint [t];

    glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, v);
    GLWrapper::Instance()->flushGLErrors();

    DebugLog::Instance()->MESSAGE(2, "Supported compressed texture formats:\n");
    for (int i=0; i<t; i++)
    {
        DebugLog::Instance()->MESSAGE(2, "format %d: 0x%x ", i, v[i]);
        switch(v[i])
        {
#if defined(GL_COMPRESSED_RGB_S3TC_DXT1_EXT)
        case GL_COMPRESSED_RGB_S3TC_DXT1_EXT: /* 0x83f0 */
            DebugLog::Instance()->MESSAGE(2, "(GL_COMPRESSED_RGB_S3TC_DXT1_EXT)\n");
            break;
#endif
#if defined(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT)
        case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: /* 0x83f1 */
            DebugLog::Instance()->MESSAGE(2, "(GL_COMPRESSED_RGBA_S3TC_DXT1_EXT)\n");
            break;
#endif
#if defined(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT)
        case GL_COMPRESSED_RGB_S3TC_DXT3_EXT: /* 0x83f2 */
            DebugLog::Instance()->MESSAGE(2, "(GL_COMPRESSED_RGBA_S3TC_DXT3_EXT)\n");
            break;
#endif
#if defined(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)
        case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: /* 0x83f3 */
            DebugLog::Instance()->MESSAGE(2, "(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)\n");
            break;
#endif
#if defined(GL_LUMINANCE_LATC1_EXT)
        case GL_LUMINANCE_LATC1_EXT: /* 0x8c70 */
            DebugLog::Instance()->MESSAGE(2, "(GL_LUMINANCE_LATC1_EXT)\n");
            break;
#endif
#if defined(GL_SIGNED_LUMINANCE_LATC1_EXT)
        case GL_SIGNED_LUMINANCE_LATC1_EXT: /* 0x8c71 */
            DebugLog::Instance()->MESSAGE(2, "(GL_SIGNED_LUMINANCE_LATC1_EXT)\n");
            break;
#endif
#if defined(GL_LUMINANCE_ALPHA_LATC2_EXT)
        case GL_LUMINANCE_ALPHA_LATC2_EXT: /* 0x8c72 */
            DebugLog::Instance()->MESSAGE(2, "(GL_LUMINANCE_ALPHA_LATC2_EXT)\n");
            break;
#endif
#if defined(GL_SIGNED_LUMINANCE_ALPHA_LATC2_EXT)
        case GL_SIGNED_LUMINANCE_ALPHA_LATC2_EXT: /* 0x8c73 */
            DebugLog::Instance()->MESSAGE(2, "(GL_SIGNED_LUMINANCE_ALPHA_LATC1_EXT)\n");
            break;
#endif
#if defined(COMPRESSED_SRGB_S3TC_DXT1_EXT)
        case COMPRESSED_SRGB_S3TC_DXT1_EXT: /* 0x8c4c */
            DebugLog::Instance()->MESSAGE(2, "(COMPRESSED_SRGB_S3TC_DXT1_EXT\n");
            break;
#endif
#if defined(COMPRESSED_SRGB_S3TC_DXT1_EXT)
        case COMPRESSED_SRGB_S3TC_DXT1_EXT: /* 0x8c4d */
            DebugLog::Instance()->MESSAGE(2, "(COMPRESSED_SRGB_S3TC_DXT1_EXT)\n");
            break;
#endif
#if defined(COMPRESSED_SRGB_S3TC_DXT1_EXT)
        case COMPRESSED_SRGB_S3TC_DXT1_EXT: /* 0x8c4e */
            DebugLog::Instance()->MESSAGE(2, "(COMPRESSED_SRGB_S3TC_DXT1_EXT)\n");
            break;
#endif
#if defined(COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT)
        case COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: /* 0x8c4f */
            DebugLog::Instance()->MESSAGE(2, "(COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT)\n");
            break;
#endif
#if defined(GL_ETC1_RGB8_OES)
        case GL_ETC1_RGB8_OES: /* 0x8d64 */
            etc1_supported = true;
            DebugLog::Instance()->MESSAGE(2, "(GL_ETC1_RGB8_OES)\n");
            break;
#endif
        default:
            DebugLog::Instance()->MESSAGE(2, "(UNKNOWN FORMAT)\n");
            break;
        }
    }
    delete v;
    return etc1_supported;
}

redpajama_set_name: RedPajamaGithub


text:
package com.example.vortexjumper;

import java.util.Random;

import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

public class EnemyX
{
	AnimatedSprite EnemyXAnimatedSprite;
	Body EnemyXbody;
	FixtureDef EnemyXobjectFixtureDef;
	int EnemyXrandomIntX;
	int EnemyXrandomIntY;

	public EnemyX(final int i, final int j, Scene mScene, final FixedStepPhysicsWorld mPhysicsWorld, TiledTextureRegion targetTextureRegion2, VertexBufferObjectManager vbom)
	{
		Random randomGenerator = new Random();
		for (int idx = 1; idx <= 10; ++idx)
		{
			EnemyXrandomIntX = randomGenerator.nextInt(500);
		}

		for (int idx = 1; idx <= 10; ++idx)
		{
			EnemyXrandomIntY = randomGenerator.nextInt(500);
		}

		EnemyXobjectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
		EnemyXAnimatedSprite = new AnimatedSprite(EnemyXrandomIntX + i, EnemyXrandomIntY + j, targetTextureRegion2, vbom)
		{
			protected void onManagedUpdate(float pSecondsElapsed)
			{
				super.onManagedUpdate(pSecondsElapsed);
				EnemyXbody.applyAngularImpulse(500f);
			};
		};

		EnemyXbody = PhysicsFactory.createCircleBody(mPhysicsWorld, EnemyXAnimatedSprite, BodyType.DynamicBody, EnemyXobjectFixtureDef);
		mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(EnemyXAnimatedSprite, EnemyXbody, true, true));

		EnemyXAnimatedSprite.animate(200, true);
		mScene.attachChild(EnemyXAnimatedSprite);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.funnic.mvc.examples</groupId>
        <artifactId>examples-reactor</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.funnic.mvc.examples</groupId>
    <artifactId>example5-reactor</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>example5-controller</module>
    </modules>

</project>


text:
<?php

echo pht('Backfilling commit summaries...')."\n";

$table = new PhabricatorRepositoryCommit();
$conn_w = $table->establishConnection('w');
$commits = new LiskMigrationIterator($table);
foreach ($commits as $commit) {
  echo pht('Filling Commit #%d', $commit->getID())."\n";

  if (strlen($commit->getSummary())) {
    continue;
  }

  $data = $commit->loadOneRelative(
    new PhabricatorRepositoryCommitData(),
    'commitID');

  if (!$data) {
    continue;
  }

  queryfx(
    $conn_w,
    'UPDATE %T SET summary = %s WHERE id = %d',
    $commit->getTableName(),
    $data->getSummary(),
    $commit->getID());
}

echo pht('Done.')."\n";


text:
WINRT_EXPORT namespace winrt {

namespace Windows::Media::Protection {

template <typename L> ComponentLoadFailedEventHandler::ComponentLoadFailedEventHandler(L lambda) :
    ComponentLoadFailedEventHandler(impl::make_delegate<impl_ComponentLoadFailedEventHandler<L>, ComponentLoadFailedEventHandler>(std::forward<L>(lambda)))
{}

template <typename F> ComponentLoadFailedEventHandler::ComponentLoadFailedEventHandler(F * function) :
    ComponentLoadFailedEventHandler([=](auto && ... args) { function(args ...); })
{}

template <typename O, typename M> ComponentLoadFailedEventHandler::ComponentLoadFailedEventHandler(O * object, M method) :
    ComponentLoadFailedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}

inline void ComponentLoadFailedEventHandler::operator()(const Windows::Media::Protection::MediaProtectionManager & sender, const Windows::Media::Protection::ComponentLoadFailedEventArgs & e) const
{
    check_hresult((*this)->abi_Invoke(get(sender), get(e)));
}

template <typename L> RebootNeededEventHandler::RebootNeededEventHandler(L lambda) :
    RebootNeededEventHandler(impl::make_delegate<impl_RebootNeededEventHandler<L>, RebootNeededEventHandler>(std::forward<L>(lambda)))
{}

template <typename F> RebootNeededEventHandler::RebootNeededEventHandler(F * function) :
    RebootNeededEventHandler([=](auto && ... args) { function(args ...); })
{}

template <typename O, typename M> RebootNeededEventHandler::RebootNeededEventHandler(O * object, M method) :
    RebootNeededEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}

inline void RebootNeededEventHandler::operator()(const Windows::Media::Protection::MediaProtectionManager & sender) const
{
    check_hresult((*this)->abi_Invoke(get(sender)));
}

template <typename L> ServiceRequestedEventHandler::ServiceRequestedEventHandler(L lambda) :
    ServiceRequestedEventHandler(impl::make_delegate<impl_ServiceRequestedEventHandler<L>, ServiceRequestedEventHandler>(std::forward<L>(lambda)))
{}

template <typename F> ServiceRequestedEventHandler::ServiceRequestedEventHandler(F * function) :
    ServiceRequestedEventHandler([=](auto && ... args) { function(args ...); })
{}

template <typename O, typename M> ServiceRequestedEventHandler::ServiceRequestedEventHandler(O * object, M method) :
    ServiceRequestedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); })
{}

inline void ServiceRequestedEventHandler::operator()(const Windows::Media::Protection::MediaProtectionManager & sender, const Windows::Media::Protection::ServiceRequestedEventArgs & e) const
{
    check_hresult((*this)->abi_Invoke(get(sender), get(e)));
}

}

namespace impl {

template <typename D>
struct produce<D, Windows::Media::Protection::IComponentLoadFailedEventArgs> : produce_base<D, Windows::Media::Protection::IComponentLoadFailedEventArgs>
{
    HRESULT __stdcall get_Information(abi_arg_out<Windows::Media::Protection::IRevocationAndRenewalInformation> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Information());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Completion(abi_arg_out<Windows::Media::Protection::IMediaProtectionServiceCompletion> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Completion());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IComponentRenewalStatics> : produce_base<D, Windows::Media::Protection::IComponentRenewalStatics>
{
    HRESULT __stdcall abi_RenewSystemComponentsAsync(abi_arg_in<Windows::Media::Protection::IRevocationAndRenewalInformation> information, abi_arg_out<Windows::Foundation::IAsyncOperationWithProgress<winrt::Windows::Media::Protection::RenewalStatus, uint32_t>> operation) noexcept override
    {
        try
        {
            *operation = detach(this->shim().RenewSystemComponentsAsync(*reinterpret_cast<const Windows::Media::Protection::RevocationAndRenewalInformation *>(&information)));
            return S_OK;
        }
        catch (...)
        {
            *operation = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IHdcpSession> : produce_base<D, Windows::Media::Protection::IHdcpSession>
{
    HRESULT __stdcall abi_IsEffectiveProtectionAtLeast(Windows::Media::Protection::HdcpProtection protection, bool * value) noexcept override
    {
        try
        {
            *value = detach(this->shim().IsEffectiveProtectionAtLeast(protection));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_GetEffectiveProtection(abi_arg_out<Windows::Foundation::IReference<winrt::Windows::Media::Protection::HdcpProtection>> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().GetEffectiveProtection());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall abi_SetDesiredMinProtectionAsync(Windows::Media::Protection::HdcpProtection protection, abi_arg_out<Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Protection::HdcpSetProtectionResult>> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().SetDesiredMinProtectionAsync(protection));
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall add_ProtectionChanged(abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Media::Protection::HdcpSession, Windows::IInspectable>> handler, event_token * token) noexcept override
    {
        try
        {
            *token = detach(this->shim().ProtectionChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Media::Protection::HdcpSession, Windows::IInspectable> *>(&handler)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall remove_ProtectionChanged(event_token token) noexcept override
    {
        try
        {
            this->shim().ProtectionChanged(token);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IMediaProtectionManager> : produce_base<D, Windows::Media::Protection::IMediaProtectionManager>
{
    HRESULT __stdcall add_ServiceRequested(abi_arg_in<Windows::Media::Protection::ServiceRequestedEventHandler> handler, event_token * cookie) noexcept override
    {
        try
        {
            *cookie = detach(this->shim().ServiceRequested(*reinterpret_cast<const Windows::Media::Protection::ServiceRequestedEventHandler *>(&handler)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall remove_ServiceRequested(event_token cookie) noexcept override
    {
        try
        {
            this->shim().ServiceRequested(cookie);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall add_RebootNeeded(abi_arg_in<Windows::Media::Protection::RebootNeededEventHandler> handler, event_token * cookie) noexcept override
    {
        try
        {
            *cookie = detach(this->shim().RebootNeeded(*reinterpret_cast<const Windows::Media::Protection::RebootNeededEventHandler *>(&handler)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall remove_RebootNeeded(event_token cookie) noexcept override
    {
        try
        {
            this->shim().RebootNeeded(cookie);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall add_ComponentLoadFailed(abi_arg_in<Windows::Media::Protection::ComponentLoadFailedEventHandler> handler, event_token * cookie) noexcept override
    {
        try
        {
            *cookie = detach(this->shim().ComponentLoadFailed(*reinterpret_cast<const Windows::Media::Protection::ComponentLoadFailedEventHandler *>(&handler)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall remove_ComponentLoadFailed(event_token cookie) noexcept override
    {
        try
        {
            this->shim().ComponentLoadFailed(cookie);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Properties(abi_arg_out<Windows::Foundation::Collections::IPropertySet> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Properties());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IMediaProtectionPMPServer> : produce_base<D, Windows::Media::Protection::IMediaProtectionPMPServer>
{
    HRESULT __stdcall get_Properties(abi_arg_out<Windows::Foundation::Collections::IPropertySet> ppProperties) noexcept override
    {
        try
        {
            *ppProperties = detach(this->shim().Properties());
            return S_OK;
        }
        catch (...)
        {
            *ppProperties = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IMediaProtectionPMPServerFactory> : produce_base<D, Windows::Media::Protection::IMediaProtectionPMPServerFactory>
{
    HRESULT __stdcall abi_CreatePMPServer(abi_arg_in<Windows::Foundation::Collections::IPropertySet> pProperties, abi_arg_out<Windows::Media::Protection::IMediaProtectionPMPServer> ppObject) noexcept override
    {
        try
        {
            *ppObject = detach(this->shim().CreatePMPServer(*reinterpret_cast<const Windows::Foundation::Collections::IPropertySet *>(&pProperties)));
            return S_OK;
        }
        catch (...)
        {
            *ppObject = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IMediaProtectionServiceCompletion> : produce_base<D, Windows::Media::Protection::IMediaProtectionServiceCompletion>
{
    HRESULT __stdcall abi_Complete(bool success) noexcept override
    {
        try
        {
            this->shim().Complete(success);
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IMediaProtectionServiceRequest> : produce_base<D, Windows::Media::Protection::IMediaProtectionServiceRequest>
{
    HRESULT __stdcall get_ProtectionSystem(GUID * system) noexcept override
    {
        try
        {
            *system = detach(this->shim().ProtectionSystem());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Type(GUID * type) noexcept override
    {
        try
        {
            *type = detach(this->shim().Type());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IProtectionCapabilities> : produce_base<D, Windows::Media::Protection::IProtectionCapabilities>
{
    HRESULT __stdcall abi_IsTypeSupported(abi_arg_in<hstring> type, abi_arg_in<hstring> keySystem, Windows::Media::Protection::ProtectionCapabilityResult * value) noexcept override
    {
        try
        {
            *value = detach(this->shim().IsTypeSupported(*reinterpret_cast<const hstring *>(&type), *reinterpret_cast<const hstring *>(&keySystem)));
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IRevocationAndRenewalInformation> : produce_base<D, Windows::Media::Protection::IRevocationAndRenewalInformation>
{
    HRESULT __stdcall get_Items(abi_arg_out<Windows::Foundation::Collections::IVector<Windows::Media::Protection::RevocationAndRenewalItem>> items) noexcept override
    {
        try
        {
            *items = detach(this->shim().Items());
            return S_OK;
        }
        catch (...)
        {
            *items = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IRevocationAndRenewalItem> : produce_base<D, Windows::Media::Protection::IRevocationAndRenewalItem>
{
    HRESULT __stdcall get_Reasons(Windows::Media::Protection::RevocationAndRenewalReasons * reasons) noexcept override
    {
        try
        {
            *reasons = detach(this->shim().Reasons());
            return S_OK;
        }
        catch (...)
        {
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_HeaderHash(abi_arg_out<hstring> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().HeaderHash());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_PublicKeyHash(abi_arg_out<hstring> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().PublicKeyHash());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Name(abi_arg_out<hstring> name) noexcept override
    {
        try
        {
            *name = detach(this->shim().Name());
            return S_OK;
        }
        catch (...)
        {
            *name = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_RenewalId(abi_arg_out<hstring> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().RenewalId());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IServiceRequestedEventArgs> : produce_base<D, Windows::Media::Protection::IServiceRequestedEventArgs>
{
    HRESULT __stdcall get_Request(abi_arg_out<Windows::Media::Protection::IMediaProtectionServiceRequest> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Request());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }

    HRESULT __stdcall get_Completion(abi_arg_out<Windows::Media::Protection::IMediaProtectionServiceCompletion> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().Completion());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }
};

template <typename D>
struct produce<D, Windows::Media::Protection::IServiceRequestedEventArgs2> : produce_base<D, Windows::Media::Protection::IServiceRequestedEventArgs2>
{
    HRESULT __stdcall get_MediaPlaybackItem(abi_arg_out<Windows::Media::Playback::IMediaPlaybackItem> value) noexcept override
    {
        try
        {
            *value = detach(this->shim().MediaPlaybackItem());
            return S_OK;
        }
        catch (...)
        {
            *value = nullptr;
            return impl::to_hresult();
        }
    }
};

}

namespace Windows::Media::Protection {

template <typename D> event_token impl_IMediaProtectionManager<D>::ServiceRequested(const Windows::Media::Protection::ServiceRequestedEventHandler & handler) const
{
    event_token cookie {};
    check_hresult(static_cast<const IMediaProtectionManager &>(static_cast<const D &>(*this))->add_ServiceRequested(get(handler), &cookie));
    return cookie;
}

template <typename D> event_revoker<IMediaProtectionManager> impl_IMediaProtectionManager<D>::ServiceRequested(auto_revoke_t, const Windows::Media::Protection::ServiceRequestedEventHandler & handler) const
{
    return impl::make_event_revoker<D, IMediaProtectionManager>(this, &ABI::Windows::Media::Protection::IMediaProtectionManager::remove_ServiceRequested, ServiceRequested(handler));
}

template <typename D> void impl_IMediaProtectionManager<D>::ServiceRequested(event_token cookie) const
{
    check_hresult(static_cast<const IMediaProtectionManager &>(static_cast<const D &>(*this))->remove_ServiceRequested(cookie));
}

template <typename D> event_token impl_IMediaProtectionManager<D>::RebootNeeded(const Windows::Media::Protection::RebootNeededEventHandler & handler) const
{
    event_token cookie {};
    check_hresult(static_cast<const IMediaProtectionManager &>(static_cast<const D &>(*this))->add_RebootNeeded(get(handler), &cookie));
    return cookie;
}

template <typename D> event_revoker<IMediaProtectionManager> impl_IMediaProtectionManager<D>::RebootNeeded(auto_revoke_t, const Windows::Media::Protection::RebootNeededEventHandler & handler) const
{
    return impl::make_event_revoker<D, IMediaProtectionManager>(this, &ABI::Windows::Media::Protection::IMediaProtectionManager::remove_RebootNeeded, RebootNeeded(handler));
}

template <typename D> void impl_IMediaProtectionManager<D>::RebootNeeded(event_token cookie) const
{
    check_hresult(static_cast<const IMediaProtectionManager &>(static_cast<const D &>(*this))->remove_RebootNeeded(cookie));
}

template <typename D> event_token impl_IMediaProtectionManager<D>::ComponentLoadFailed(const Windows::Media::Protection::ComponentLoadFailedEventHandler & handler) const
{
    event_token cookie {};
    check_hresult(static_cast<const IMediaProtectionManager &>(static_cast<const D &>(*this))->add_ComponentLoadFailed(get(handler), &cookie));
    return cookie;
}

template <typename D> event_revoker<IMediaProtectionManager> impl_IMediaProtectionManager<D>::ComponentLoadFailed(auto_revoke_t, const Windows::Media::Protection::ComponentLoadFailedEventHandler & handler) const
{
    return impl::make_event_revoker<D, IMediaProtectionManager>(this, &ABI::Windows::Media::Protection::IMediaProtectionManager::remove_ComponentLoadFailed, ComponentLoadFailed(handler));
}

template <typename D> void impl_IMediaProtectionManager<D>::ComponentLoadFailed(event_token cookie) const
{
    check_hresult(static_cast<const IMediaProtectionManager &>(static_cast<const D &>(*this))->remove_ComponentLoadFailed(cookie));
}

template <typename D> Windows::Foundation::Collections::IPropertySet impl_IMediaProtectionManager<D>::Properties() const
{
    Windows::Foundation::Collections::IPropertySet value;
    check_hresult(static_cast<const IMediaProtectionManager &>(static_cast<const D &>(*this))->get_Properties(put(value)));
    return value;
}

template <typename D> void impl_IMediaProtectionServiceCompletion<D>::Complete(bool success) const
{
    check_hresult(static_cast<const IMediaProtectionServiceCompletion &>(static_cast<const D &>(*this))->abi_Complete(success));
}

template <typename D> Windows::Media::Protection::IMediaProtectionServiceRequest impl_IServiceRequestedEventArgs<D>::Request() const
{
    Windows::Media::Protection::IMediaProtectionServiceRequest value;
    check_hresult(static_cast<const IServiceRequestedEventArgs &>(static_cast<const D &>(*this))->get_Request(put(value)));
    return value;
}

template <typename D> Windows::Media::Protection::MediaProtectionServiceCompletion impl_IServiceRequestedEventArgs<D>::Completion() const
{
    Windows::Media::Protection::MediaProtectionServiceCompletion value { nullptr };
    check_hresult(static_cast<const IServiceRequestedEventArgs &>(static_cast<const D &>(*this))->get_Completion(put(value)));
    return value;
}

template <typename D> GUID impl_IMediaProtectionServiceRequest<D>::ProtectionSystem() const
{
    GUID system {};
    check_hresult(static_cast<const IMediaProtectionServiceRequest &>(static_cast<const D &>(*this))->get_ProtectionSystem(&system));
    return system;
}

template <typename D> GUID impl_IMediaProtectionServiceRequest<D>::Type() const
{
    GUID type {};
    check_hresult(static_cast<const IMediaProtectionServiceRequest &>(static_cast<const D &>(*this))->get_Type(&type));
    return type;
}

template <typename D> Windows::Media::Playback::MediaPlaybackItem impl_IServiceRequestedEventArgs2<D>::MediaPlaybackItem() const
{
    Windows::Media::Playback::MediaPlaybackItem value { nullptr };
    check_hresult(static_cast<const IServiceRequestedEventArgs2 &>(static_cast<const D &>(*this))->get_MediaPlaybackItem(put(value)));
    return value;
}

template <typename D> Windows::Media::Protection::RevocationAndRenewalInformation impl_IComponentLoadFailedEventArgs<D>::Information() const
{
    Windows::Media::Protection::RevocationAndRenewalInformation value { nullptr };
    check_hresult(static_cast<const IComponentLoadFailedEventArgs &>(static_cast<const D &>(*this))->get_Information(put(value)));
    return value;
}

template <typename D> Windows::Media::Protection::MediaProtectionServiceCompletion impl_IComponentLoadFailedEventArgs<D>::Completion() const
{
    Windows::Media::Protection::MediaProtectionServiceCompletion value { nullptr };
    check_hresult(static_cast<const IComponentLoadFailedEventArgs &>(static_cast<const D &>(*this))->get_Completion(put(value)));
    return value;
}

template <typename D> Windows::Foundation::Collections::IVector<Windows::Media::Protection::RevocationAndRenewalItem> impl_IRevocationAndRenewalInformation<D>::Items() const
{
    Windows::Foundation::Collections::IVector<Windows::Media::Protection::RevocationAndRenewalItem> items;
    check_hresult(static_cast<const IRevocationAndRenewalInformation &>(static_cast<const D &>(*this))->get_Items(put(items)));
    return items;
}

template <typename D> Windows::Media::Protection::RevocationAndRenewalReasons impl_IRevocationAndRenewalItem<D>::Reasons() const
{
    Windows::Media::Protection::RevocationAndRenewalReasons reasons {};
    check_hresult(static_cast<const IRevocationAndRenewalItem &>(static_cast<const D &>(*this))->get_Reasons(&reasons));
    return reasons;
}

template <typename D> hstring impl_IRevocationAndRenewalItem<D>::HeaderHash() const
{
    hstring value;
    check_hresult(static_cast<const IRevocationAndRenewalItem &>(static_cast<const D &>(*this))->get_HeaderHash(put(value)));
    return value;
}

template <typename D> hstring impl_IRevocationAndRenewalItem<D>::PublicKeyHash() const
{
    hstring value;
    check_hresult(static_cast<const IRevocationAndRenewalItem &>(static_cast<const D &>(*this))->get_PublicKeyHash(put(value)));
    return value;
}

template <typename D> hstring impl_IRevocationAndRenewalItem<D>::Name() const
{
    hstring name;
    check_hresult(static_cast<const IRevocationAndRenewalItem &>(static_cast<const D &>(*this))->get_Name(put(name)));
    return name;
}

template <typename D> hstring impl_IRevocationAndRenewalItem<D>::RenewalId() const
{
    hstring value;
    check_hresult(static_cast<const IRevocationAndRenewalItem &>(static_cast<const D &>(*this))->get_RenewalId(put(value)));
    return value;
}

template <typename D> Windows::Media::Protection::MediaProtectionPMPServer impl_IMediaProtectionPMPServerFactory<D>::CreatePMPServer(const Windows::Foundation::Collections::IPropertySet & pProperties) const
{
    Windows::Media::Protection::MediaProtectionPMPServer ppObject { nullptr };
    check_hresult(static_cast<const IMediaProtectionPMPServerFactory &>(static_cast<const D &>(*this))->abi_CreatePMPServer(get(pProperties), put(ppObject)));
    return ppObject;
}

template <typename D> Windows::Foundation::Collections::IPropertySet impl_IMediaProtectionPMPServer<D>::Properties() const
{
    Windows::Foundation::Collections::IPropertySet ppProperties;
    check_hresult(static_cast<const IMediaProtectionPMPServer &>(static_cast<const D &>(*this))->get_Properties(put(ppProperties)));
    return ppProperties;
}

template <typename D> Windows::Media::Protection::ProtectionCapabilityResult impl_IProtectionCapabilities<D>::IsTypeSupported(hstring_ref type, hstring_ref keySystem) const
{
    Windows::Media::Protection::ProtectionCapabilityResult value {};
    check_hresult(static_cast<const IProtectionCapabilities &>(static_cast<const D &>(*this))->abi_IsTypeSupported(get(type), get(keySystem), &value));
    return value;
}

template <typename D> bool impl_IHdcpSession<D>::IsEffectiveProtectionAtLeast(Windows::Media::Protection::HdcpProtection protection) const
{
    bool value {};
    check_hresult(static_cast<const IHdcpSession &>(static_cast<const D &>(*this))->abi_IsEffectiveProtectionAtLeast(protection, &value));
    return value;
}

template <typename D> Windows::Foundation::IReference<winrt::Windows::Media::Protection::HdcpProtection> impl_IHdcpSession<D>::GetEffectiveProtection() const
{
    Windows::Foundation::IReference<winrt::Windows::Media::Protection::HdcpProtection> value;
    check_hresult(static_cast<const IHdcpSession &>(static_cast<const D &>(*this))->abi_GetEffectiveProtection(put(value)));
    return value;
}

template <typename D> Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Protection::HdcpSetProtectionResult> impl_IHdcpSession<D>::SetDesiredMinProtectionAsync(Windows::Media::Protection::HdcpProtection protection) const
{
    Windows::Foundation::IAsyncOperation<winrt::Windows::Media::Protection::HdcpSetProtectionResult> value;
    check_hresult(static_cast<const IHdcpSession &>(static_cast<const D &>(*this))->abi_SetDesiredMinProtectionAsync(protection, put(value)));
    return value;
}

template <typename D> event_token impl_IHdcpSession<D>::ProtectionChanged(const Windows::Foundation::TypedEventHandler<Windows::Media::Protection::HdcpSession, Windows::IInspectable> & handler) const
{
    event_token token {};
    check_hresult(static_cast<const IHdcpSession &>(static_cast<const D &>(*this))->add_ProtectionChanged(get(handler), &token));
    return token;
}

template <typename D> event_revoker<IHdcpSession> impl_IHdcpSession<D>::ProtectionChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Media::Protection::HdcpSession, Windows::IInspectable> & handler) const
{
    return impl::make_event_revoker<D, IHdcpSession>(this, &ABI::Windows::Media::Protection::IHdcpSession::remove_ProtectionChanged, ProtectionChanged(handler));
}

template <typename D> void impl_IHdcpSession<D>::ProtectionChanged(event_token token) const
{
    check_hresult(static_cast<const IHdcpSession &>(static_cast<const D &>(*this))->remove_ProtectionChanged(token));
}

template <typename D> Windows::Foundation::IAsyncOperationWithProgress<winrt::Windows::Media::Protection::RenewalStatus, uint32_t> impl_IComponentRenewalStatics<D>::RenewSystemComponentsAsync(const Windows::Media::Protection::RevocationAndRenewalInformation & information) const
{
    Windows::Foundation::IAsyncOperationWithProgress<winrt::Windows::Media::Protection::RenewalStatus, uint32_t> operation;
    check_hresult(static_cast<const IComponentRenewalStatics &>(static_cast<const D &>(*this))->abi_RenewSystemComponentsAsync(get(information), put(operation)));
    return operation;
}

inline Windows::Foundation::IAsyncOperationWithProgress<winrt::Windows::Media::Protection::RenewalStatus, uint32_t> ComponentRenewal::RenewSystemComponentsAsync(const Windows::Media::Protection::RevocationAndRenewalInformation & information)
{
    return get_activation_factory<ComponentRenewal, IComponentRenewalStatics>().RenewSystemComponentsAsync(information);
}

inline HdcpSession::HdcpSession() :
    HdcpSession(activate_instance<HdcpSession>())
{}

inline MediaProtectionManager::MediaProtectionManager() :
    MediaProtectionManager(activate_instance<MediaProtectionManager>())
{}

inline MediaProtectionPMPServer::MediaProtectionPMPServer(const Windows::Foundation::Collections::IPropertySet & pProperties) :
    MediaProtectionPMPServer(get_activation_factory<MediaProtectionPMPServer, IMediaProtectionPMPServerFactory>().CreatePMPServer(pProperties))
{}

inline ProtectionCapabilities::ProtectionCapabilities() :
    ProtectionCapabilities(activate_instance<ProtectionCapabilities>())
{}

}

}


text:
'use strict'
let Model = require("../model")
, path = require("path")
,	fs = require("fs")
require("../lib/date")

Promise.all([
	Model.getBlogs()
	, Model.getComments()
	, Model.getAbouts()
]).then(data => {
	fs.writeFileSync(path.join(__dirname, "../local/data.json"), JSON.stringify({blogs: data[0], comments: data[1], abouts: data[2]}))
	console.log(`write to file data.json`)
	process.exit(0)
}).catch(err => {
	console.error(err)
	process.exit(1)
})


text:
/**
 * Reference:
 * https://developer.linkedin.com/docs/share-on-linkedin
 */

const hrefFactory = require('./core/href-factory.js');
const shareFactory = require('./core/share-factory.js');

const href = hrefFactory('https://www.linkedin.com/sharing/share-offsite/', {
  url: 'url',
});

module.exports = shareFactory(href, 500, 400);


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/listpage_more_speak_pressed" />
    <item android:drawable="@drawable/listpage_more_speak_normal" />
</selector>


text:
// va contenir (un jour) toutes les fonctions concernant les blocs droites/gauches
var bloc = {};

var gHttpsUrl = "https://my.nabaztag.com/vl/action/";

var gHColor = "rgb(222, 235, 103)";	// couleur highlite générique
var gErrorColor = "rgb(230, 139, 147)";// couleur highlite erreur
var gSrvErrorFlag = false;		// mis a true, au cas ou la mise a jour du service c'est mal passé.
var gGlobal = new Object;

// dans ce tableau sont conserv?'?t de tout les div qui charge du contenu dynamiquement (true = en train de charger)
var loadingTable = new Array;
var loadingTimerTable = new Array;

// pour chaque groupe d'onglet (pour l'instant il n'y en a qu'un par page, mais sait on jamais !)
// on conserve quel onglet est selectionné
var currentTab = ""; 		//= new Array;
var currentSousTab = ""; 	//= new Array;

var loadingContent 			= "";
var loadingContentError 	= "
Loading error
";
var processingContent 		= "

";
var backgroundSubmitContent = "

please wait

";

var blocOrder = new Array;

/* Home page */

var blockExtendable				= "|friends:open|";

// nabaztag.constantes.ISLOG est setté en amont dans les pages JSP
if(nabaztag.constantes.ISLOG){

	// blocOrder['onglet du site'] = colonnegauche_type_de_bloc1@param1^param2, colonnegauche_type_de_bloc2@param1^param2 : colonnedroite_type_de_bloc1@param1^param2

	// home
	blocOrder['CreerCompte']		= "generic@register";

	// nablife
	if ( !nabaztag.constantes.BAD_CONNECTED_OBJECT && nabaztag.constantes.OBJECTID == 0 ) {
		blocOrder['AllServices'] 		= "DernierAnnuaire : nablives";
	} else {
		blocOrder['AllServices'] 		= "MyServices, MyNabcast, DernierAnnuaire : nablives";
	}

	blocOrder['Nabaztaland'] 		= "MyServices, MyNabcast";
	blocOrder['Publier'] 			= "MyServices, MyNabcast";

	// message
	blocOrder['Envoyer']			= "friends:DernierAnnuaire";
	blocOrder['Envoyes'] = blocOrder['Recu'] = blocOrder['Archives'] = blocOrder['Envoyer'];

	// terrier
	blocOrder['Profil'] 			= (nabaztag.constantes.OBJECTID == 0) 	? "updateMac@true"
																			: "";
	blocOrder['MaMusique']			= ":friends";
	blocOrder['MesAmis']			= ":DernierAnnuaire";

} else {

	//home
	blocOrder['SeConnecter'] 	= "DecouvrirNabaztag:DernierAnnuaire";
	blocOrder['CreerCompte']	= "generic@register";

	// nablife
	blocOrder['AllServices'] 	= "DernierAnnuaire : nablives"; //generic@homeBloc:
	blocOrder['Nabaztaland']	= blocOrder['AllServices'];

	// message
	blocOrder['Envoyer']		= "DernierAnnuaire:";

}


text:
package org.elasticsearch.examples.nativescript.script;

import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;

import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.search.sort.SortBuilders;
import org.junit.Test;

/**
 */
public class RandomSortScriptTests extends AbstractSearchScriptTests {
    @Test
    public void testPseudoRandomScript() throws Exception {

        // Create a new index
        String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
                .startObject("properties")
                .startObject("name").field("type", "string").endObject()
                .endObject().endObject().endObject()
                .string();

        assertAcked(prepareCreate("test")
                .addMapping("type", mapping));

        List<IndexRequestBuilder> indexBuilders = new ArrayList<IndexRequestBuilder>();

        // Index 100 records (0..99)
        for (int i = 0; i < 100; i++) {
            indexBuilders.add(
                    client().prepareIndex("test", "type", Integer.toString(i))
                    .setSource(XContentFactory.jsonBuilder().startObject()
                            .field("name", "rec " + i)
                            .endObject()));
        }

        indexRandom(true, indexBuilders);

        // Retrieve first 10 records
        SearchResponse searchResponse = client().prepareSearch("test")
                .setQuery(matchAllQuery())
                .addField("name")
                .setSize(10)
                .addSort(SortBuilders.scriptSort("random", "number").lang("native").setParams(MapBuilder.<String, Object>newMapBuilder().put("salt", "1234").map()))
                .execute().actionGet();

        assertNoFailures(searchResponse);

        // Check that random order was applied
        assertThat(searchResponse.getHits().getAt(0).field("name").getValue().toString(), not(equalTo("rec0")));

        String[] records = new String[10];

        // Store sort order
        for (int i = 0; i < 10; i++) {
            records[i] = searchResponse.getHits().getAt(i).field("name").getValue().toString();
        }

        // Retrieve first 10 records again
        searchResponse = client().prepareSearch("test")
                .setQuery(matchAllQuery())
                .addField("name")
                .setSize(10)
                .addSort(SortBuilders.scriptSort("random", "number").lang("native").setParams(MapBuilder.<String, Object>newMapBuilder().put("salt", "1234").map()))
                .execute().actionGet();

        assertNoFailures(searchResponse);

        // Verify the same sort order
        for (int i = 0; i < 10; i++) {
            assertThat(searchResponse.getHits().getAt(i).field("name").getValue().toString(), equalTo(records[i]));
        }

        // Retrieve first 10 records without salt
        searchResponse = client().prepareSearch("test")
                .setQuery(matchAllQuery())
                .addField("name")
                .setSize(10)
                .addSort(SortBuilders.scriptSort("random", "number").lang("native"))
                .execute().actionGet();

        assertNoFailures(searchResponse);

        // Verify different sort order
        boolean different = false;
        for (int i = 0; i < 10; i++) {
            if (!records[i].equals(searchResponse.getHits().getAt(i).field("name").getValue().toString())) {
                different = true;
                break;
            }
        }
        assertThat(different, equalTo(true));

    }
}


text:
"""Test that the toolchain can build executables.

Multiple build tools and languages are supported. If an emulator is available,
its ability to run the generated executables is also tested.
"""

import argparse
import glob
import os
import shutil
import subprocess
import sys
import tempfile

def test_none_build_system(build_dir, language, source, linker_flags, exe_suffix):
    build_cmd = list()
    if language == 'C':
        compiler = os.getenv('CC', 'cc')
    elif language == 'C++':
        compiler = os.getenv('CXX', 'c++')
    else:
        print('Unknown language: ' + language)
        return 1
    build_cmd.append(compiler)
    if linker_flags:
        build_cmd.extend(linker_flags)
    build_cmd.append(source)

    build_cmd.append('-o')
    build_cmd.append('a.out' + exe_suffix)

    print('Building ' + source + ' by calling ' + compiler + '...')
    print(' '.join(build_cmd))
    sys.stdout.flush()

    return subprocess.call(build_cmd)

def test_cmake_build_system(build_dir, language, source, emulator, linker_flags,
        exe_suffix):
    shutil.copy(source, build_dir)
    print('Building ' + source + ' with CMake...')

    with open('CMakeLists.txt', 'w') as fp:
        fp.write('cmake_minimum_required(VERSION 3.0)\n')
        fp.write('project(test-compiler)\n')
        fp.write('add_executable(a.out ' + os.path.basename(source) + ')\n')
        if emulator:
            fp.write('enable_testing()\n')
            fp.write('add_test(NAME emulator-in-cmake COMMAND a.out)\n')

    os.mkdir('build')
    os.chdir('build')

    cmake_configuration_cmd = ['cmake', '..']
    if linker_flags:
        cmake_configuration_cmd.insert(1,
                '-DCMAKE_EXE_LINKER_FLAGS="{0}"'.format(' '.join(linker_flags)))
    print(' '.join(cmake_configuration_cmd))
    sys.stdout.flush()
    if subprocess.call(cmake_configuration_cmd):
        return 1
    if subprocess.call(['make', 'VERBOSE=1']):
        return 1
    if emulator:
        if subprocess.call(['ctest']):
            return 1
    shutil.copy('a.out' + exe_suffix, build_dir)
    return 0

def test_source(source, language, build_system, emulator, linker_flags,
        exe_suffix, debug):
    result = 0
    cwd = os.getcwd()
    build_dir = tempfile.mkdtemp()
    os.chdir(build_dir)

    if build_system == 'None':
        result += test_none_build_system(build_dir, language, source,
                linker_flags, exe_suffix)
    elif build_system == 'CMake':
        result += test_cmake_build_system(build_dir, language, source, emulator,
                linker_flags, exe_suffix)
    else:
        print('Unknown build system: ' + build_system)
        result += 1

    if emulator:
        cmd = emulator
        cmd += ' ' + os.path.join(build_dir, 'a.out' + exe_suffix)
        print('Running ' + cmd + '...')
        sys.stdout.flush()
        result += subprocess.call(cmd, shell=True)

    os.chdir(cwd)
    if not debug:
        print('Deleting temporary build directory ' + build_dir)
        shutil.rmtree(build_dir)
    else:
        print('Keeping temporary build directory ' + build_dir)

    sys.stdout.flush()
    return result

def test_build_system(test_dir, language, build_system, emulator, linker_flags,
        exe_suffix, debug):
    print('\n\n--------------------------------------------------------')
    print('Testing ' + build_system + ' build system with the ' +
          language + ' language\n')
    sys.stdout.flush()
    result = 0
    for source in glob.glob(os.path.join(test_dir, language, '*')):
        result += test_source(source, language, build_system, emulator,
                linker_flags, exe_suffix, debug)
    return result

def test_language(test_dir, language, build_systems, emulator, linker_flags,
        exe_suffix, debug):
    result = 0
    for build_system in build_systems:
        result += test_build_system(test_dir,
                language,
                build_system,
                emulator,
                linker_flags,
                exe_suffix,
                debug)
    return result

def run_tests(test_dir, languages=('C', 'C++'), build_systems=('None', 'CMake'),
        emulator=None, linker_flags=None, exe_suffix='', debug=False):
    """Run the tests found in test_dir where each directory corresponds to an
    entry in languages. Every source within a language directory is built. The
    output executable is also run with the emulator if provided."""
    result = 0
    for language in languages:
        result += test_language(test_dir,
                language,
                build_systems,
                emulator,
                linker_flags,
                exe_suffix,
                debug)
    return result

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
            description='Test the cross-compiler toolchain.')
    parser.add_argument('--languages', '-l', nargs='+', default=['C', 'C++'],
            help='Languages to test. Options: C C++')
    parser.add_argument('--build-systems', '-b', nargs='+', default=['None', 'CMake'],
            help='Build systems to test. Options: None CMake')
    parser.add_argument('--emulator', '-e',
            help='Emulator used to test generated executables')
    parser.add_argument('--linker-flags', '-w', nargs='+',
            help='Extra compilation linker flags')
    parser.add_argument('--exe-suffix', '-s', default='',
            help='Suffix for generated executables')
    parser.add_argument('--debug', '-d', action='store_true',
            help='Do not remove temporary build directory')
    args = parser.parse_args()

    test_dir = os.path.dirname(os.path.abspath(__file__))

    sys.exit(run_tests(test_dir,
        languages=args.languages,
        build_systems=args.build_systems,
        emulator=args.emulator,
        linker_flags=args.linker_flags,
        exe_suffix=args.exe_suffix,
        debug=args.debug) != 0)


text:
using System;

namespace Lextm.SharpSnmpLib.Mib.Elements.Types
{
    public sealed class TextualConvention : ITypeAssignment, ITypeReferrer
    {
        private IModule _module;
        private string _name;
        private DisplayHint _displayHint;
        private Status _status;
        private string _description;
        private string _reference;
        private ITypeAssignment _syntax;

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "module")]
        public TextualConvention(IModule module, string name, ISymbolEnumerator symbols)
        {
            _module = module;
            _name = name;

            _displayHint = ParseDisplayHint(symbols);
            _status      = ParseStatus(symbols);
            _description = ParseDescription(symbols);
            _reference   = ParseReference(symbols);
            _syntax      = ParseSyntax(module, symbols);
        }

        private static DisplayHint ParseDisplayHint(ISymbolEnumerator symbols)
        {
            Symbol current = symbols.NextNonEOLSymbol();

            if (current == Symbol.DisplayHint)
            {
                return new DisplayHint(symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' }));
            }

            symbols.PutBack(current);
            return null;
        }

        private static Status ParseStatus(ISymbolEnumerator symbols)
        {
            Symbol current = symbols.NextNonEOLSymbol();
            current.Expect(Symbol.Status);

            try
            {
                return (Status)Enum.Parse(typeof(Status), symbols.NextNonEOLSymbol().ToString());
            }
            catch (ArgumentException)
            {
                current.Assert(false, "Invalid/Unknown status");
            }

            return Status.current;
        }

        private static string ParseDescription(ISymbolEnumerator symbols)
        {
            Symbol current = symbols.NextNonEOLSymbol();
            current.Expect(Symbol.Description);

            return symbols.NextNonEOLSymbol().ToString().Trim(new char[] { '"' });
        }

        private static string ParseReference(ISymbolEnumerator symbols)
        {
            Symbol current = symbols.NextNonEOLSymbol();

            if (current == Symbol.Reference)
            {
                string reference = symbols.NextNonEOLSymbol().ToString();
                if ((reference.Length >= 2) && reference.StartsWith("\"") && reference.EndsWith("\""))
                {
                    return reference.Substring(1, reference.Length-2);
                }

                return reference;
            }

            symbols.PutBack(current);
            return null;
        }

        private static ITypeAssignment ParseSyntax(IModule module, ISymbolEnumerator symbols)
        {
            Symbol current = symbols.NextNonEOLSymbol();
            current.Expect(Symbol.Syntax);

            /*
             * RFC2579 definition:
             *       Syntax ::=   -- Must be one of the following:
             *                    -- a base type (or its refinement), or
             *                    -- a BITS pseudo-type
             *               type
             *             | "BITS" "{" NamedBits "}"
             *
             * From section 3.5:
             *      The data structure must be one of the alternatives defined
             *      in the ObjectSyntax CHOICE or the BITS construct.  Note
             *      that this means that the SYNTAX clause of a Textual
             *      Convention can not refer to a previously defined Textual
             *      Convention.
             *
             *      The SYNTAX clause of a TEXTUAL CONVENTION macro may be
             *      sub-typed in the same way as the SYNTAX clause of an
             *      OBJECT-TYPE macro.
             *
             * Therefore the possible values are (grouped by underlying type):
             *      INTEGER, Integer32
             *      OCTET STRING, Opaque
             *      OBJECT IDENTIFIER
             *      IpAddress
             *      Counter64
             *      Unsigned32, Counter32, Gauge32, TimeTicks
             *      BITS
             * With appropriate sub-typing.
             */

            return Lexer.ParseBasicTypeDef(module, String.Empty, symbols, isMacroSyntax: true);
        }

        public IModule Module
        {
            get { return _module; }
        }

        public string Name
        {
            get { return _name; }
        }

        public string DisplayHint
        {
            get { return _displayHint == null ? null : _displayHint.ToString(); }
        }

        public Status Status
        {
            get { return _status; }
        }

        public string Description
        {
            get { return _description; }
        }

        public string Reference
        {
            get { return _reference; }
        }

        public ITypeAssignment Syntax
        {
            get { return _syntax; }
        }

        //internal object Decode(Variable v)
        //{
        //    if (_syntax is IntegerType)
        //    {
        //        Integer32 i = v.Data as Integer32;
        //        if (i == null || (_syntax as IntegerType).IsEnumeration)
        //        {
        //            return null;
        //        }
        //        else if (_displayHint != null)
        //        {
        //            return _displayHint.Decode(i.ToInt32());
        //        }
        //        else
        //        {
        //            return i.ToInt32();
        //        }
        //    }
        //    else if (_syntax is UnsignedType)
        //    {
        //        Integer32 i = v.Data as Integer32;
        //        if (i == null)
        //        {
        //            return null;
        //        }
        //        else if (_displayHint != null)
        //        {
        //            return _displayHint.Decode(i.ToInt32());
        //        }
        //        else
        //        {
        //            return i.ToInt32();
        //        }
        //    }
        //    else if (_syntax is OctetStringType)
        //    {
        //        OctetString o = v.Data as OctetString;
        //        if (o == null)
        //        {
        //            return null;
        //        }
        //        else
        //        {
        //            // TODO: Follow the format specifier for octet strings.
        //            return null;
        //        }
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}

        #region ITypeReferrer Member

        public ITypeAssignment ReferredType
        {
            get { return _syntax; }
            set { _syntax = value; }
        }

        public ITypeAssignment BaseType
        {
            get
            {
                ITypeReferrer   tr     = this;
                ITypeAssignment result = this;

                while ((tr != null) && (tr.ReferredType != null))
                {
                    result = tr.ReferredType;
                    tr = tr.ReferredType as ITypeReferrer;
                }

                return result;
            }
        }

        #endregion
    }
}


text:
<component name="libraryTable">
  <library name="androidautowire">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/libs/androidautowire.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
using System;
using SFA.DAS.EmployerAccounts.ReadStore.Mediator;

namespace SFA.DAS.EmployerAccounts.ReadStore.Application.Queries
{
    internal class IsUserInAnyRoleQuery : IReadStoreRequest<bool>
    {
        public Guid UserRef { get; }
        public long AccountId { get; }

        public IsUserInAnyRoleQuery(Guid userRef, long accountId)
        {
            UserRef = userRef;
            AccountId = accountId;
        }
    }
}


text:
package org.apache.phoenix.schema;

import java.sql.SQLException;

import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.exception.SQLExceptionInfo;

/**
 * Exception thrown when we try to convert one type into a different incompatible type.
 *
 *
 * @since 1.0
 */
public class TypeMismatchException extends SQLException {
    private static final long serialVersionUID = 1L;
    private static SQLExceptionCode code = SQLExceptionCode.TYPE_MISMATCH;

    public TypeMismatchException(String msg) {
        super(new SQLExceptionInfo.Builder(code).setMessage(msg).build().toString(), code.getSQLState(), code.getErrorCode());
    }

    public static TypeMismatchException newException(PDataType lhs)  {
        return new TypeMismatchException(getMessage(lhs,null,null));
    }

    public static TypeMismatchException newException(PDataType lhs, String location)  {
        return new TypeMismatchException(getMessage(lhs,null,location));
    }

    public static TypeMismatchException newException(PDataType lhs, PDataType rhs)  {
        return new TypeMismatchException(getMessage(lhs,rhs,null));
    }

    public static TypeMismatchException newException(PDataType lhs, PDataType rhs, String location)  {
        return new TypeMismatchException(getMessage(lhs,rhs,location));
    }

    public static String getMessage(PDataType lhs, PDataType rhs, String location) {
        return lhs + (rhs == null ? "" : " and " + rhs) + (location == null ? "" : " for " + location);
    }
}


text:
package net.ontrack.dao;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Locale;

public final class SQLUtils {

	private SQLUtils() {
	}

	public static String dateToDB (LocalDate date) {
		return date.toString();
	}

	public static LocalDate dateFromDB(String str) {
		return LocalDate.parse(str);
	}

	public static String timeToDB (LocalTime time) {
		return time.toString("HH:mm");
	}

	public static LocalTime timeFromDB(String str) {
		return LocalTime.parse(str);
	}

	public static DateTime now() {
		return DateTime.now(DateTimeZone.UTC);
	}

	public static Timestamp toTimestamp(DateTime dateTime) {
		return new Timestamp(dateTime.getMillis());
	}

	public static DateTime getDateTime(ResultSet rs, String columnName) throws SQLException {
		Timestamp timestamp = rs.getTimestamp(columnName);
		return getDateTime(timestamp);
	}

	public static DateTime getDateTime(Timestamp timestamp) {
		return timestamp != null ? new DateTime(timestamp.getTime(), DateTimeZone.UTC) : null;
	}

	public static <E extends Enum<E>> E getEnum(Class<E> enumClass, ResultSet rs, String columnName) throws SQLException {
		String value = rs.getString(columnName);
		if (value == null) {
			return null;
		} else {
			return Enum.valueOf(enumClass, value);
		}
	}

    public static Locale toLocale(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (StringUtils.isBlank(value)) {
            return Locale.ENGLISH;
        } else {
            return Locale.forLanguageTag(value);
        }
    }
}


text:
package main

import (
	"os"
	"github.com/pascalw/go-alfred"
	"net/http"
	"io/ioutil"
	"encoding/json"
)

func main() {
	queryTerms := os.Args[1:]

	// optimize query terms for fuzzy matching
	alfred.InitTerms(queryTerms)

	// create a new alfred workflow response
	response := alfred.NewResponse()
	repos := getRepos()

	for _, repo := range repos {
		// check if the repo name fuzzy matches the query terms
		if ! alfred.MatchesTerms(queryTerms, repo.Name) { continue }

		// it matched so add a new response item
		response.AddItem(&alfred.AlfredResponseItem{
			Valid: true,
			Uid: repo.URL,
			Title: repo.Name,
			Arg: repo.URL,
		})
	}

	// finally print the resulting Alfred Workflow XML
	response.Print()
}

type Repo struct {
	Name string
	URL string
}

func getRepos() []Repo {
	resp, err := http.Get("https://api.github.com/users/pascalw/repos")
	if err != nil { panic(err) }

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	var repos []Repo
	json.Unmarshal(body, &repos)

	return repos
}


text:
<?php
Class Report_model extends CI_Model{

    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->model("Tools_model");
        $this->load->model("Branch_model");
        $this->load->model("Log_model");
    }

    public function getGBWeight($filter=array()){

        if(isset($filter["yearNum"])){
            $yearNum=$filter["yearNum"];
        }else{
            $yearNum=date("Y");
        }

        $whereArr[]="
            year(`collectDate`)='".$yearNum."'
        ";

        if(isset($filter["monNum"])){
            $whereArr[]="
                month(`collectDate`)='".$filter["monNum"]."'
            ";
        }

        if(isset($filter["branchID"])){
            $whereArr[]="
                `truckID` in (
                    select  `truckID`
                    from    truck
                    where   `branchID`='".$filter["branchID"]."'
                )
            ";
        }

        $whereSQL=$this->Tools_model->whereSQL($whereArr);

        $query="
            select  *
            from    gabage_collection
            $whereSQL
        ";
        $result=$this->db->query($query);
        if($result->num_rows()){
            return $result->result_array();
        }else{
            return FALSE;
        }
    }

    public function getGBPrice($filter=array()){

        if(isset($filter["yearNum"])){
            $yearNum=$filter["yearNum"];
        }else{
            $yearNum=date("Y");
        }

        $whereArr[]="
            year(`collectDate`)='".$yearNum."'
        ";

        if(isset($filter["monNum"])){
            $whereArr[]="
                month(`collectDate`)='".$_POST["monNum"]."'
            ";
        }

        if(isset($filter["branchID"])){
            $whereArr[]="
                `GBCollectionID` in (
                    select  `GBCollectionID`
                    from    gabage_collection
                    where   `truckID` in (
                                select  `truckID`
                                from    truck
                                where   `branchID`='".$filter["branchID"]."'
                            )
                )
            ";
        }

        $whereSQL=$this->Tools_model->whereSQL($whereArr);

        $query="
            select  *
            from    collection_staff
            $whereSQL
        ";
        $result=$this->db->query($query);
        if($result->num_rows()){
            return $result->result_array();
        }else{
            return FALSE;
        }
    }

    public function getFuelUsageJSON($filter){

        if(isset($filter["yearNum"])){
            $yearNum=$filter["yearNum"];
        }else{
            $yearNum=date("Y");
        }

        $whereArr[]="
            year(`fuelDate`)='".$yearNum."'
        ";

        if(isset($filter["monNum"])){
            $whereArr[]="
                month(`fuelDate`)='".$_POST["monNum"]."'
            ";
        }

        if(isset($filter["branchID"])){
            $whereArr[]="
                `truckID` in (
                    select  `truckID`
                    from    truck
                    where   `branchID`='".$filter["branchID"]."'
                )
            ";
        }

        $whereSQL=$this->Tools_model->whereSQL($whereArr);

        $query="
            select  *
            from    fuel_usage
            $whereSQL
        ";
        $result=$this->db->query($query);
        if($result->num_rows()){
            return $result->result_array();
        }else{
            return FALSE;
        }
    }

    public function getFuelUsageStandard(){

        if(isset($filter["yearNum"])){
            $yearNum=$filter["yearNum"];
        }else{
            $yearNum=date("Y");
        }

        $whereArr[]="
            year(`fuelDate`)='".$yearNum."'
        ";

        if(isset($filter["monNum"])){
            $whereArr[]="
                month(`fuelDate`)='".$_POST["monNum"]."'
            ";
        }

        if(isset($filter["branchID"])){
            $whereArr[]="
                `truckID` in (
                    select  `truckID`
                    from    truck
                    where   `branchID`='".$filter["branchID"]."'
                )
            ";
        }

        $whereSQL=$this->Tools_model->whereSQL($whereArr);

        return array(
            1=>2.9,
            2=>2.9,
            3=>2.9,
            4=>2.9,
            5=>2.9,
            6=>2.9,
            7=>2.9,
            8=>2.9,
            9=>2.9,
            10=>2.9,
            11=>2.9,
            12=>2.9
        );
    }

    public function getTruck($truckID){
        $query="
            select  *
            from    truck
            where   `truckID`='".$truckID."'
        ";
        $result=$this->db->query($query);
        if($result->num_rows()){
            return $result->row_array();
        }else{
            return FALSE;
        }
    }

    public function getBranchIncome($filter=array()){
        $branchName=$this->Tools_model->branchName();

        $whereArr=array();
        if(isset($filter["yearNum"])){
            $yearNum=$filter["yearNum"];
        }else{
            $yearNum=date("Y");
        }

        $whereArr[]="
            year(`collectDate`)='".$yearNum."'
        ";

        if(isset($filter["monNum"])){
            $whereArr[]="
                month(`collectDate`)='".$_POST["monNum"]."'
            ";
        }

        if(isset($filter["branchID"])){
            $whereArr[]="
                `truckID` in (
                    select  `truckID`
                    from    truck
                    where   `branchID`='".$filter["branchID"]."'
                )
            ";
        }

        $whereSQL=$this->Tools_model->whereSQL($whereArr);

        $query="
            select      truckID, sum(income) as 'sumIncome', sum(weight) as 'sumWeight'
            from        gabage_collection
            $whereSQL
            group by    truckID
        ";
        $result=$this->db->query($query);
        if($result->num_rows()){
            // $this->Tools_model->printR($result->result_array());
            foreach ($result->result_array() as $key => $value) {
                $truckInfo[$value["truckID"]]=$this->getTruck($value["truckID"]);
                $branchIncomeArray[$truckInfo[$value["truckID"]]["branchID"]]=$value["sumIncome"];
                $branchWeightArray[$truckInfo[$value["truckID"]]["branchID"]]=$value["sumWeight"];
            }
            foreach ($result->result_array() as $key => $value) {
                $branchArray[$truckInfo[$value["truckID"]]["branchID"]]=$branchName[$truckInfo[$value["truckID"]]["branchID"]];
            }

            // $this->Tools_model->printR($branchArray);
            foreach ($branchArray as $key => $value) {
                $branchList[]=$value;
            }

            // $this->Tools_model->printR($branchIncomeArray);
            foreach ($branchIncomeArray as $key => $value) {
                $branchIncome[]=(double)$value;
            }

            foreach ($branchWeightArray as $key => $value) {
                $branchWeight[]=(double)$value;
            }

            // $this->Tools_model->printR($branchList);
            // $this->Tools_model->printR($branchIncome);

            return array(
                "branchList"=>$branchList,
                "branchIncome"=>$branchIncome,
                "branchWeight"=>$branchWeight
            );
        }else{
            return FALSE;
        }
    }

    public function getBranchOutcome($filter=array(),$getBranchID=FALSE){
        $branchName=$this->Tools_model->branchName();

        $whereArr=array();
        if(isset($filter["yearNum"])){
            $yearNum=$filter["yearNum"];
        }else{
            $yearNum=date("Y");
        }

        $whereArr[]="
            year(`collectDate`)='".$yearNum."'
        ";

        if(isset($filter["monNum"])){
            $whereArr[]="
                month(`collectDate`)='".$_POST["monNum"]."'
            ";
        }

        if(isset($filter["branchID"])){
            $whereArr[]="
                `truckID` in (
                    select  `truckID`
                    from    truck
                    where   `branchID`='".$filter["branchID"]."'
                )
            ";
        }

        $whereSQL=$this->Tools_model->whereSQL($whereArr);

        $query="
            select      *
            from        gabage_collection
            $whereSQL
        ";
        $result=$this->db->query($query);
        if($result->num_rows()){
            // $this->Tools_model->printR($result->result_array());
            foreach ($result->result_array() as $key => $value) {
                $truckInfo[$value["truckID"]]=$this->getTruck($value["truckID"]);
                $queryCS="
                    select  sum(salary) as 'sumOutcome'
                    from    collection_staff
                    where   `GBCollectionID`='".$value["GBCollectionID"]."'
                ";
                $resultCS=$this->db->query($queryCS);
                if($resultCS->num_rows()){
                    $rowCS=$resultCS->row_array();
                    $sumOutcome=$rowCS["sumOutcome"];
                }else{
                    $sumOutcome=0;
                }
                $branchOutcomeArray[$truckInfo[$value["truckID"]]["branchID"]]=$sumOutcome;
            }
            if($getBranchID){
                $branchOutcome=$branchOutcomeArray;
            }else{
                foreach ($branchOutcomeArray as $key => $value) {
                    $branchOutcome[]=$value;
                }
            }

            // $this->Tools_model->printR($branchList);
            // $this->Tools_model->printR($branchIncome);

            return array(
                "branchOutcome"=>$branchOutcome
            );
        }else{
            return FALSE;
        }
    }

    public function getBranchOutcomePerWeightJSON($filter){
        $branchName=$this->Tools_model->branchName();

        $fuelUsageList=$this->getFuelUsageJSON($filter);
        if(is_array($fuelUsageList)){
            foreach ($fuelUsageList as $key => $value) {
                $truckList[$value["truckID"]]=TRUE;
            }
            foreach ($truckList as $truckID => $tIDValue) {
                $truckInfo=$this->getTruck($truckID);
                $branchID=$truckInfo["branchID"];
                foreach ($fuelUsageList as $fuKey => $fuValue) {
                    if(isset($branchFuelPrice[$branchID])){
                        $branchFuelPrice[$branchID]+=$fuValue["price"];
                    }else{
                        $branchFuelPrice[$branchID]=0;
                    }
                }
            }

            foreach ($branchFuelPrice as $key => $value) {
                $branchIDList[]=$key;
                $branchList[]=$branchName[$key];
                $branchFuelPriceJSON[]=$value;
            }

            return array(
                "branchIDList"=>$branchIDList,
                "branchList"=>$branchList,
                "branchFuelPriceJSON"=>$branchFuelPriceJSON
            );
        }
    }

    public function getBranchMaintainCost($filter){
        $branchName=$this->Tools_model->branchName();

        $whereArr=array();
        if(isset($filter["yearNum"])){
            $yearNum=$filter["yearNum"];
        }else{
            $yearNum=date("Y");
        }

        $whereArr[]="
            year(`informDate`)='".$yearNum."'
        ";

        if(isset($filter["monNum"])){
            $whereArr[]="
                month(`informDate`)='".$_POST["monNum"]."'
            ";
        }

        $whereSQL=$this->Tools_model->whereSQL($whereArr);
        $query="
            select  *
            from    truck_maintain
            $whereSQL
        ";
        $result=$this->db->query($query);
        if($result->num_rows()){
            foreach ($result->result_array() as $key => $value) {
                $truckInfo=array();
                if(!isset($truckInfo[$value["truckID"]])){
                    $truckInfo[$value["truckID"]]=$this->getTruck($value["truckID"]);
                }

                $querySUM="
                    select  sum(amount*price) as 'total'
                    from    truck_maintain_item
                    where   `truckMaintainID`='".$value["truckMaintainID"]."'
                ";
                $resultSUM=$this->db->query($querySUM);
                if($resultSUM->num_rows()){
                    $row=$resultSUM->row_array();
                    $total=$row['total'];
                }else{
                    $total=0;
                }

                if(!isset($branchMaintainCost[$truckInfo[$value["truckID"]]["branchID"]])){
                    $branchMaintainCost[$truckInfo[$value["truckID"]]["branchID"]]=0;
                }

                $branchMaintainCost[$truckInfo[$value["truckID"]]["branchID"]]+=$total;

                return $branchMaintainCost;
            }
        }else{
            return FALSE;
        }
    }

}


text:
server.log
===============

The **psiTurk** web server process will not print to the Terminal.
Instead, error messages and warning will be printed to the server log
file.  This will be created the first time you run the server.

.. seealso::

   `Interacting with server log <../command_line/server.html#server-log>`__
   	  The command for viewing the log file.

   `Logfile configuration options <../config/server_parameters.html#logfile-string>`__
   	  Configuration options controlling the log file.