<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD
license as described in the file LICENSE.
 */

#include <float.h>
#include <math.h>
#include <stdio.h>

#include "wap.h"
#include "simple_label.h"
#include "cache.h"
#include "csoaa.h"
#include "oaa.h"
#include "vw.h"

using namespace std;

namespace WAP {
  struct wap{
    uint32_t increment;
    learner base;
    vw* all;
  };

  void mirror_features(vw& all, example* ec, uint32_t offset1, uint32_t offset2)
  {
    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
      {
        size_t original_length = ec->atomics[*i].size();
        //cerr << "original_length = " << original_length << endl;
        for (uint32_t j = 0; j < original_length; j++)
          {
            feature* f = &ec->atomics[*i][j];
            feature temp = {- f->x, f->weight_index + offset2};
            f->weight_index += offset1;
            ec->atomics[*i].push_back(temp);
          }
        ec->sum_feat_sq[*i] *= 2;
        //cerr << "final_length = " << ec->atomics[*i].size() << endl;
      }
    if (all.audit)
      {
        for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
          if (ec->audit_features[*i].begin != ec->audit_features[*i].end)
            {
              size_t original_length = ec->audit_features[*i].size();
              for (uint32_t j = 0; j < original_length; j++)
                {
                  audit_data* f = &ec->audit_features[*i][j];
                  char* new_space = NULL;
                  if (f->space != NULL)
                    {
                      new_space = (char*)calloc(strlen(f->space)+1,sizeof(char));
                      strcpy(new_space, f->space);
                    }
                  char* new_feature = (char*)calloc(strlen(f->feature)+2,sizeof(char));
                  strcpy(new_feature+1, f->feature);
                  *new_feature = '-';
                  audit_data temp = {new_space, new_feature, f->weight_index + offset2, - f->x, true};
                  f->weight_index += offset1;
                  ec->audit_features[*i].push_back(temp);
                }
              //cerr << "final_length = " << ec->audit_features[*i].size() << endl;
            }
      }
    ec->num_features *= 2;
    ec->total_sum_feat_sq *= 2;
    //cerr << "total_sum_feat_sq = " << ec->total_sum_feat_sq << endl;
  }

  void unmirror_features(vw& all, example* ec, uint32_t offset1, uint32_t offset2)
  {
    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
      {
        ec->atomics[*i].end = ec->atomics[*i].begin+ec->atomics[*i].size()/2;
        feature* end = ec->atomics[*i].end;
        for (feature* f = ec->atomics[*i].begin; f!= end; f++)
          f->weight_index -= offset1;
        ec->sum_feat_sq[*i] /= 2;
      }
    if (all.audit)
      {
        for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
          if (ec->audit_features[*i].begin != ec->audit_features[*i].end)
            {
              for (audit_data *f = ec->audit_features[*i].begin + ec->audit_features[*i].size()/2; f != ec->audit_features[*i].end; f++)
                {
                  if (f->space != NULL)
                    free(f->space);
                  free(f->feature);
                  f->alloced = false;
                }
              ec->audit_features[*i].end = ec->audit_features[*i].begin+ec->audit_features[*i].size()/2;
              for (audit_data *f = ec->audit_features[*i].begin; f != ec->audit_features[*i].end; f++)
                f->weight_index -= offset1;
            }
      }
    ec->num_features /= 2;
    ec->total_sum_feat_sq /= 2;
  }

  struct float_wclass
  {
    float v;
    CSOAA::wclass ci;
  };
  int fi_compare(const void *e1, const void* e2)
  {
    float_wclass* fi1 = (float_wclass*)e1;
    float_wclass* fi2 = (float_wclass*)e2;
    if (fi1->ci.x > fi2->ci.x)
      return 1;
    else if (fi1->ci.x < fi2->ci.x)
      return -1;
    else
      return 0;
  }
  int fi_compare_i(const void *e1, const void* e2)
  {
    float_wclass* fi1 = (float_wclass*)e1;
    float_wclass* fi2 = (float_wclass*)e2;
    if (fi1->ci.weight_index > fi2->ci.weight_index)
      return 1;
    else if (fi1->ci.weight_index < fi2->ci.weight_index)
      return -1;
    else
      return 0;
  }
  v_array<float_wclass> vs;

  void train(vw& all, wap& w, example* ec)
  {
    CSOAA::label* ld = (CSOAA::label*)ec->ld;

    CSOAA::wclass* old_end = ld->costs.end;
    CSOAA::wclass* j = ld->costs.begin;
    for (CSOAA::wclass *cl = ld->costs.begin; cl != ld->costs.end; cl ++)
      if (cl->x != FLT_MAX)
        *j++ = *cl;
    ld->costs.end = j;

    float score = FLT_MAX;
    vs.erase();
    for (CSOAA::wclass *cl = ld->costs.begin; cl != ld->costs.end; cl ++)
      {
        float_wclass temp = {0., *cl};
        if (temp.ci.x < score)
          score = temp.ci.x;
        vs.push_back(temp);
      }

    qsort(vs.begin, vs.size(), sizeof(float_wclass), fi_compare);

    for (uint32_t i = 0; i < ld->costs.size(); i++)
      {
        vs[i].ci.x -= score;
        if (i == 0)
          vs[i].v = 0.;
        else
          vs[i].v = vs[i-1].v + (vs[i].ci.x-vs[i-1].ci.x) / (float)i;
      }

    qsort(vs.begin, vs.size(), sizeof(float_wclass), fi_compare_i);

    for (uint32_t i = 0; i < ld->costs.size(); i++)
      for (uint32_t j = i+1; j < ld->costs.size(); j++)
        {
          label_data simple_temp;
          simple_temp.weight = fabsf(vs[i].v - vs[j].v);
          if (simple_temp.weight > 1e-5)
            {
              simple_temp.initial = 0.;

              if (vs[i].v < vs[j].v)
                simple_temp.label = 1;
              else
                simple_temp.label = -1;

              ec->ld = &simple_temp;

              ec->partial_prediction = 0.;
              uint32_t myi = (uint32_t)vs[i].ci.weight_index;
              uint32_t myj = (uint32_t)vs[j].ci.weight_index;

              mirror_features(all, ec,(myi-1)*w.increment, (myj-1)*w.increment);

              w.base.learn(ec);
              unmirror_features(all, ec,(myi-1)*w.increment, (myj-1)*w.increment);
            }
        }

    ld->costs.end = old_end;
    ec->ld = ld;
  }

  size_t test(vw& all, wap& w, example* ec)
  {
    size_t prediction = 1;
    float score = -FLT_MAX;

    CSOAA::label* cost_label = (CSOAA::label*)ec->ld;

    for (uint32_t i = 0; i < cost_label->costs.size(); i++)
      {
        label_data simple_temp;
        simple_temp.initial = 0.;
        simple_temp.weight = 0.;
        simple_temp.label = FLT_MAX;
        uint32_t myi = (uint32_t)cost_label->costs[i].weight_index;
        if (myi!= 1)
          update_example_indicies(all.audit, ec, w.increment*(myi-1));
        ec->partial_prediction = 0.;
        ec->ld = &simple_temp;
        w.base.learn(ec);
        if (myi != 1)
          update_example_indicies(all.audit, ec, -w.increment*(myi-1));
        if (ec->partial_prediction > score)
          {
            score = ec->partial_prediction;
            prediction = myi;
          }
        cost_label->costs[i].partial_prediction = -ec->partial_prediction;
      }
    return prediction;
  }

  void learn(void* d, example* ec)
  {
    CSOAA::label* cost_label = (CSOAA::label*)ec->ld;
    wap* w = (wap*)d;
    vw* all = w->all;

    if (command_example(all, ec))
      {
	w->base.learn(ec);
	return;
      }

    size_t prediction = test(*all, *w, ec);
    ec->ld = cost_label;

    if (cost_label->costs.size() > 0)
      train(*all, *w, ec);
    ec->final_prediction = (float)prediction;
  }

  void finish(void* d)
  {
    wap* w=(wap*)d;
    w->base.finish();
    free(w);
  }

  void drive(vw* all, void* d)
  {
    example* ec = NULL;
    while ( true )
      {
        if ((ec = VW::get_example(all->p)) != NULL)//semiblocking operation.
          {
	    learn(d, ec);
            CSOAA::output_example(*all, ec);
	    VW::finish_example(*all, ec);
          }
        else if (parser_done(all->p))
	  return;
        else
          ;
      }
  }

  learner setup(vw& all, std::vector<std::string>&, po::variables_map& vm, po::variables_map& vm_file)
  {
    wap* w=(wap*)calloc(1,sizeof(wap));
    w->all = &all;
    uint32_t nb_actions = 0;
    if( vm_file.count("wap") ) { //if loaded options from regressor
      nb_actions = (uint32_t)vm_file["wap"].as<size_t>();
      if( vm.count("wap") && (uint32_t)vm["wap"].as<size_t>() != nb_actions )
        std::cerr << "warning: you specified a different number of actions through --wap than the one loaded from regressor. Pursuing with loaded value of: " << nb_actions << endl;
    }
    else {
      nb_actions = (uint32_t)vm["wap"].as<size_t>();

     //append wap with nb_actions to options_from_file so it is saved to regressor later
     std::stringstream ss;
     ss << " --wap " << nb_actions;
     all.options_from_file.append(ss.str());
    }

    *(all.p->lp) = CSOAA::cs_label_parser;

    all.sd->k = (uint32_t)nb_actions;
    all.weights_per_problem *= nb_actions;
    w->increment = (uint32_t)((all.length()/ all.weights_per_problem) * all.reg.stride);

    learner l(w, drive, learn, finish, all.l.sl);
    w->base = all.l;
    return l;
  }
}
<commit_msg>make wap work<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD
license as described in the file LICENSE.
 */

#include <float.h>
#include <math.h>
#include <stdio.h>

#include "wap.h"
#include "simple_label.h"
#include "cache.h"
#include "csoaa.h"
#include "oaa.h"
#include "vw.h"

using namespace std;

namespace WAP {
  struct wap{
    uint32_t increment;
    learner base;
    vw* all;
  };

  void mirror_features(vw& all, example* ec, uint32_t offset1, uint32_t offset2)
  {
    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
      {
        size_t original_length = ec->atomics[*i].size();
        //cerr << "original_length = " << original_length << endl;
        for (uint32_t j = 0; j < original_length; j++)
          {
            feature* f = &ec->atomics[*i][j];
            feature temp = {- f->x, f->weight_index + offset2};
            f->weight_index += offset1;
            ec->atomics[*i].push_back(temp);
          }
        ec->sum_feat_sq[*i] *= 2;
        //cerr << "final_length = " << ec->atomics[*i].size() << endl;
      }
    if (all.audit)
      {
        for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
          if (ec->audit_features[*i].begin != ec->audit_features[*i].end)
            {
              size_t original_length = ec->audit_features[*i].size();
              for (uint32_t j = 0; j < original_length; j++)
                {
                  audit_data* f = &ec->audit_features[*i][j];
                  char* new_space = NULL;
                  if (f->space != NULL)
                    {
                      new_space = (char*)calloc(strlen(f->space)+1,sizeof(char));
                      strcpy(new_space, f->space);
                    }
                  char* new_feature = (char*)calloc(strlen(f->feature)+2,sizeof(char));
                  strcpy(new_feature+1, f->feature);
                  *new_feature = '-';
                  audit_data temp = {new_space, new_feature, f->weight_index + offset2, - f->x, true};
                  f->weight_index += offset1;
                  ec->audit_features[*i].push_back(temp);
                }
              //cerr << "final_length = " << ec->audit_features[*i].size() << endl;
            }
      }
    ec->num_features *= 2;
    ec->total_sum_feat_sq *= 2;
    //cerr << "total_sum_feat_sq = " << ec->total_sum_feat_sq << endl;
  }

  void unmirror_features(vw& all, example* ec, uint32_t offset1, uint32_t offset2)
  {
    for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
      {
        ec->atomics[*i].end = ec->atomics[*i].begin+ec->atomics[*i].size()/2;
        feature* end = ec->atomics[*i].end;
        for (feature* f = ec->atomics[*i].begin; f!= end; f++)
          f->weight_index -= offset1;
        ec->sum_feat_sq[*i] /= 2;
      }
    if (all.audit)
      {
        for (unsigned char* i = ec->indices.begin; i != ec->indices.end; i++)
          if (ec->audit_features[*i].begin != ec->audit_features[*i].end)
            {
              for (audit_data *f = ec->audit_features[*i].begin + ec->audit_features[*i].size()/2; f != ec->audit_features[*i].end; f++)
                {
                  if (f->space != NULL)
                    free(f->space);
                  free(f->feature);
                  f->alloced = false;
                }
              ec->audit_features[*i].end = ec->audit_features[*i].begin+ec->audit_features[*i].size()/2;
              for (audit_data *f = ec->audit_features[*i].begin; f != ec->audit_features[*i].end; f++)
                f->weight_index -= offset1;
            }
      }
    ec->num_features /= 2;
    ec->total_sum_feat_sq /= 2;
  }

  struct float_wclass
  {
    float v;
    CSOAA::wclass ci;
  };
  int fi_compare(const void *e1, const void* e2)
  {
    float_wclass* fi1 = (float_wclass*)e1;
    float_wclass* fi2 = (float_wclass*)e2;
    if (fi1->ci.x > fi2->ci.x)
      return 1;
    else if (fi1->ci.x < fi2->ci.x)
      return -1;
    else
      return 0;
  }
  int fi_compare_i(const void *e1, const void* e2)
  {
    float_wclass* fi1 = (float_wclass*)e1;
    float_wclass* fi2 = (float_wclass*)e2;
    if (fi1->ci.weight_index > fi2->ci.weight_index)
      return 1;
    else if (fi1->ci.weight_index < fi2->ci.weight_index)
      return -1;
    else
      return 0;
  }
  v_array<float_wclass> vs;

  void train(vw& all, wap& w, example* ec)
  {
    CSOAA::label* ld = (CSOAA::label*)ec->ld;

    CSOAA::wclass* old_end = ld->costs.end;
    CSOAA::wclass* j = ld->costs.begin;
    for (CSOAA::wclass *cl = ld->costs.begin; cl != ld->costs.end; cl ++)
      if (cl->x != FLT_MAX)
        *j++ = *cl;
    ld->costs.end = j;

    float score = FLT_MAX;
    vs.erase();
    for (CSOAA::wclass *cl = ld->costs.begin; cl != ld->costs.end; cl ++)
      {
        float_wclass temp = {0., *cl};
        if (temp.ci.x < score)
          score = temp.ci.x;
        vs.push_back(temp);
      }

    qsort(vs.begin, vs.size(), sizeof(float_wclass), fi_compare);

    for (uint32_t i = 0; i < ld->costs.size(); i++)
      {
        vs[i].ci.x -= score;
        if (i == 0)
          vs[i].v = 0.;
        else
          vs[i].v = vs[i-1].v + (vs[i].ci.x-vs[i-1].ci.x) / (float)i;
      }

    qsort(vs.begin, vs.size(), sizeof(float_wclass), fi_compare_i);

    for (uint32_t i = 0; i < ld->costs.size(); i++)
      for (uint32_t j = i+1; j < ld->costs.size(); j++)
        {
          label_data simple_temp;
          simple_temp.weight = fabsf(vs[i].v - vs[j].v);
          if (simple_temp.weight > 1e-5)
            {
              simple_temp.initial = 0.;

              if (vs[i].v < vs[j].v)
                simple_temp.label = 1;
              else
                simple_temp.label = -1;

              ec->ld = &simple_temp;

              ec->partial_prediction = 0.;
              uint32_t myi = (uint32_t)vs[i].ci.weight_index;
              uint32_t myj = (uint32_t)vs[j].ci.weight_index;

              mirror_features(all, ec,(myi-1)*w.increment, (myj-1)*w.increment);

              w.base.learn(ec);
              unmirror_features(all, ec,(myi-1)*w.increment, (myj-1)*w.increment);
            }
        }

    ld->costs.end = old_end;
    ec->ld = ld;
  }

  size_t test(vw& all, wap& w, example* ec)
  {
    size_t prediction = 1;
    float score = -FLT_MAX;

    CSOAA::label* cost_label = (CSOAA::label*)ec->ld;

    for (uint32_t i = 0; i < cost_label->costs.size(); i++)
      {
        label_data simple_temp;
        simple_temp.initial = 0.;
        simple_temp.weight = 0.;
        simple_temp.label = FLT_MAX;
        uint32_t myi = (uint32_t)cost_label->costs[i].weight_index;
        if (myi!= 1)
          update_example_indicies(all.audit, ec, w.increment*(myi-1));
        ec->partial_prediction = 0.;
        ec->ld = &simple_temp;
        w.base.learn(ec);
        if (myi != 1)
          update_example_indicies(all.audit, ec, -w.increment*(myi-1));
        if (ec->partial_prediction > score)
          {
            score = ec->partial_prediction;
            prediction = myi;
          }
        cost_label->costs[i].partial_prediction = -ec->partial_prediction;
      }
    return prediction;
  }

  void learn(void* d, example* ec)
  {
    CSOAA::label* cost_label = (CSOAA::label*)ec->ld;
    wap* w = (wap*)d;
    vw* all = w->all;

    if (command_example(all, ec))
      {
	w->base.learn(ec);
	return;
      }

    size_t prediction = test(*all, *w, ec);
    ec->ld = cost_label;

    if (cost_label->costs.size() > 0)
      train(*all, *w, ec);
    ec->final_prediction = (float)prediction;
  }

  void finish(void* d)
  {
    wap* w=(wap*)d;
    w->base.finish();
    free(w);
  }

  void drive(vw* all, void* d)
  {
    example* ec = NULL;
    while ( true )
      {
        if(all-> early_terminate)
          {
            all->p->done = true;
            all->final_regressor_name = "";//skip finalize_regressor
            all->text_regressor_name = "";
            all->inv_hash_regressor_name = "";
            return;
          }
        if ((ec = VW::get_example(all->p)) != NULL)//semiblocking operation.
          {
	    learn(d, ec);
            if (!command_example(all, ec))
              CSOAA::output_example(*all, ec);
	    VW::finish_example(*all, ec);
          }
        else if (parser_done(all->p))
	  return;
        else
          ;
      }
  }

  learner setup(vw& all, std::vector<std::string>&, po::variables_map& vm, po::variables_map& vm_file)
  {
    wap* w=(wap*)calloc(1,sizeof(wap));
    w->all = &all;
    uint32_t nb_actions = 0;
    if( vm_file.count("wap") ) { //if loaded options from regressor
      nb_actions = (uint32_t)vm_file["wap"].as<size_t>();
      if( vm.count("wap") && (uint32_t)vm["wap"].as<size_t>() != nb_actions )
        std::cerr << "warning: you specified a different number of actions through --wap than the one loaded from regressor. Pursuing with loaded value of: " << nb_actions << endl;
    }
    else {
      nb_actions = (uint32_t)vm["wap"].as<size_t>();

     //append wap with nb_actions to options_from_file so it is saved to regressor later
     std::stringstream ss;
     ss << " --wap " << nb_actions;
     all.options_from_file.append(ss.str());
    }

    *(all.p->lp) = CSOAA::cs_label_parser;

    all.sd->k = (uint32_t)nb_actions;
    all.weights_per_problem *= nb_actions;
    w->increment = (uint32_t)((all.length()/ all.weights_per_problem) * all.reg.stride);

    learner l(w, drive, learn, finish, all.l.sl);
    w->base = all.l;
    return l;
  }
}
<|endoftext|>


<commit_before><commit_msg>MB-38570: Use cb::hex_encode to encode nonce<commit_after><|endoftext|>


<commit_before>
#include <fusekit/daemon.h>
#include <fusekit/default_directory.h>
#include <fusekit/stream_object_file.h>

/// example demonstrates how to create hierarchical structure
/// by creating directories and by by adding files to this
/// newly created directories.
///
/// so directory struture should look like the following
/// (explore with ls and cd from shell)
/// mountpoint/s
/// mountpoint/a/s
/// mountpoint/b/s
/// when started with like
/// $folders mountpoint
int main( int argc, char* argv[] ){
  fusekit::daemon<>& daemon = fusekit::daemon<>::instance();

  std::string s1("i am a child of /");
  daemon.root().add_file("s", fusekit::make_iostream_object_file(s1));

  std::string s2("i am a child of /a");
  daemon.root().add_directory( "a", fusekit::make_default_directory()).
    add_file("s", fusekit::make_iostream_object_file(s2));

  std::string s3("i am a child of /b");
  daemon.root().add_directory( "b", fusekit::make_default_directory()).
    add_file("s", fusekit::make_iostream_object_file(s3));

  return daemon.run(argc,argv);
}
<commit_msg>holding a dir ref<commit_after>
#include <fusekit/daemon.h>
#include <fusekit/default_directory.h>
#include <fusekit/stream_object_file.h>

/// example demonstrates how to create hierarchical structure
/// by creating directories and by by adding files to this
/// newly created directories.
///
/// so directory struture should look like the following
/// (explore with ls and cd from shell)
/// mountpoint/s
/// mountpoint/a/s
/// mountpoint/b/s
/// when started with like
/// $folders mountpoint
int main( int argc, char* argv[] ){
  fusekit::daemon<>& daemon = fusekit::daemon<>::instance();

  std::string s1("i am a child of /");
  daemon.root().add_file("s", fusekit::make_iostream_object_file(s1));

  std::string s2("i am a child of /a");
  // you can hold references to directories (and files) you create
  fusekit::default_directory<>::type& dir_a = daemon.root().add_directory( "a", fusekit::make_default_directory());
  dir_a.add_file("s", fusekit::make_iostream_object_file(s2));

  // or you can using chaining if  you do not need the variable later on
  std::string s3("i am a child of /b");
  daemon.root().add_directory( "b", fusekit::make_default_directory()).
    add_file("s", fusekit::make_iostream_object_file(s3));

  return daemon.run(argc,argv);
}
<|endoftext|>


<commit_before><commit_msg>Revised based on review.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fltoptint.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:01:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_DOCUMENT_FILTEROPTIONSREQUEST_HPP_
#include <com/sun/star/document/FilterOptionsRequest.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XINTERACTIONFILTEROPTIONS_HPP_
#include <com/sun/star/document/XInteractionFilterOptions.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif

#ifndef __FRAMEWORK_DISPATCH_INTERACTION_HXX_
#include <framework/interaction.hxx>
#endif

using namespace ::framework;

class FilterOptionsContinuation : public ContinuationBase< ::com::sun::star::document::XInteractionFilterOptions >
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > rProperties;

public:
    virtual void SAL_CALL setFilterOptions( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rProp ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getFilterOptions(  ) throw (::com::sun::star::uno::RuntimeException);
};

class RequestFilterOptions : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    ::com::sun::star::uno::Any m_aRequest;

    ::com::sun::star::uno::Sequence<
                    ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >
                > m_lContinuations;

    ContinuationAbort*  m_pAbort;

    FilterOptionsContinuation*  m_pOptions;

public:
    RequestFilterOptions( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > rModel,
                              ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > rProperties );

    sal_Bool    isAbort() { return m_pAbort->isSelected(); }

    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > getFilterOptions()
    {
        return m_pOptions->getFilterOptions();
    }

    virtual ::com::sun::star::uno::Any SAL_CALL getRequest()
        throw( ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Sequence<
                ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >
            > SAL_CALL getContinuations()
        throw( ::com::sun::star::uno::RuntimeException );
};

<commit_msg>INTEGRATION: CWS changefileheader (1.3.732); FILE MERGED 2008/04/01 15:39:25 thb 1.3.732.3: #i85898# Stripping all external header guards 2008/04/01 12:40:51 thb 1.3.732.2: #i85898# Stripping all external header guards 2008/03/31 13:38:34 rt 1.3.732.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fltoptint.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <com/sun/star/document/FilterOptionsRequest.hpp>
#include <com/sun/star/document/XInteractionFilterOptions.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <framework/interaction.hxx>

using namespace ::framework;

class FilterOptionsContinuation : public ContinuationBase< ::com::sun::star::document::XInteractionFilterOptions >
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > rProperties;

public:
    virtual void SAL_CALL setFilterOptions( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rProp ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getFilterOptions(  ) throw (::com::sun::star::uno::RuntimeException);
};

class RequestFilterOptions : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    ::com::sun::star::uno::Any m_aRequest;

    ::com::sun::star::uno::Sequence<
                    ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >
                > m_lContinuations;

    ContinuationAbort*  m_pAbort;

    FilterOptionsContinuation*  m_pOptions;

public:
    RequestFilterOptions( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > rModel,
                              ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > rProperties );

    sal_Bool    isAbort() { return m_pAbort->isSelected(); }

    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > getFilterOptions()
    {
        return m_pOptions->getFilterOptions();
    }

    virtual ::com::sun::star::uno::Any SAL_CALL getRequest()
        throw( ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Sequence<
                ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >
            > SAL_CALL getContinuations()
        throw( ::com::sun::star::uno::RuntimeException );
};

<|endoftext|>


<commit_before>// Copyright (C) 2016 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/MaterialPipeline.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <functional>
#include <Nazara/Graphics/Debug.hpp>

namespace Nz
{
	inline MaterialPipeline::MaterialPipeline(const MaterialPipelineInfo& pipelineInfo) :
	m_pipelineInfo(pipelineInfo)
	{
	}

	/*!
	* \brief Enable pipeline states for rendering
	*
	* \param flags Shader flags
	*/
	inline const MaterialPipeline::Instance& MaterialPipeline::Apply(UInt32 flags) const
	{
		const Instance& instance = GetInstance(flags);
		instance.uberInstance->Activate();

		Renderer::SetRenderStates(m_pipelineInfo);

		return instance;
	}

	/*!
	* \brief Retrieve a MaterialPipelineInfo object describing this pipeline
	*
	* \return Pipeline informations
	*/
	const MaterialPipelineInfo& MaterialPipeline::GetInfo() const
	{
		return m_pipelineInfo;
	}

	/*!
	* \brief Retrieve (and generate if required) a pipeline instance using shader flags without applying it
	*
	* \param flags Shader flags
	*
	* \return Pipeline instance
	*/
	inline const MaterialPipeline::Instance& MaterialPipeline::GetInstance(UInt32 flags) const
	{
		const Instance& instance = m_instances[flags];
		if (!instance.uberInstance)
			GenerateRenderPipeline(flags);

		return instance;
	}

	bool operator==(const MaterialPipelineInfo& lhs, const MaterialPipelineInfo& rhs)
	{
		if (!operator==(static_cast<const RenderStates&>(lhs), static_cast<const RenderStates&>(rhs)))
			return false;

		#define NazaraPipelineMember(field) if (lhs.field != rhs.field) return false
		#define NazaraPipelineBoolMember NazaraPipelineMember

		NazaraPipelineBoolMember(alphaTest);
		NazaraPipelineBoolMember(depthSorting);
		NazaraPipelineBoolMember(hasAlphaMap);
		NazaraPipelineBoolMember(hasDiffuseMap);
		NazaraPipelineBoolMember(hasEmissiveMap);
		NazaraPipelineBoolMember(hasHeightMap);
		NazaraPipelineBoolMember(hasNormalMap);
		NazaraPipelineBoolMember(hasSpecularMap);
		NazaraPipelineBoolMember(shadowReceive);

		NazaraPipelineMember(uberShader);

		#undef NazaraPipelineMember
		#undef NazaraPipelineBoolMember

		return true;
	}

	bool operator!=(const MaterialPipelineInfo& lhs, const MaterialPipelineInfo& rhs)
	{
		return !operator==(lhs, rhs);
	}

	/*!
	* \brief Creates a new MaterialPipeline from the arguments
	* \return A reference to the newly created material pipeline
	*
	* \param args Arguments for the material pipeline
	*/
	template<typename... Args>
	MaterialPipelineRef MaterialPipeline::New(Args&&... args)
	{
		std::unique_ptr<MaterialPipeline> object(new MaterialPipeline(std::forward<Args>(args)...));
		return object.release();
	}
}

namespace std
{
	template<>
	struct hash<Nz::MaterialPipelineInfo>
	{
		size_t operator()(const Nz::MaterialPipelineInfo& pipelineInfo) const
		{
			hash<Nz::RenderStates> parentHash;

			std::size_t seed = parentHash(pipelineInfo);

			Nz::UInt16 parameterHash = 0;
			Nz::UInt16 parameterIndex = 0;

			#define NazaraPipelineMember(member) Nz::HashCombine(seed, pipelineInfo.member)
			#define NazaraPipelineBoolMember(member) parameterHash |= ((pipelineInfo.member) ? 1U : 0U) << (parameterIndex++)

			NazaraPipelineBoolMember(alphaTest);
			NazaraPipelineBoolMember(depthSorting);
			NazaraPipelineBoolMember(hasAlphaMap);
			NazaraPipelineBoolMember(hasDiffuseMap);
			NazaraPipelineBoolMember(hasEmissiveMap);
			NazaraPipelineBoolMember(hasHeightMap);
			NazaraPipelineBoolMember(hasNormalMap);
			NazaraPipelineBoolMember(hasSpecularMap);
			NazaraPipelineBoolMember(shadowReceive);

			NazaraPipelineMember(uberShader);

			#undef NazaraPipelineMember
			#undef NazaraPipelineBoolMember

			Nz::HashCombine(seed, parameterHash);

			return seed;
		}
	};
}

#include <Nazara/Graphics/DebugOff.hpp>
<commit_msg>Fix memory leak<commit_after>// Copyright (C) 2016 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Graphics/MaterialPipeline.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <functional>
#include <Nazara/Graphics/Debug.hpp>

namespace Nz
{
	inline MaterialPipeline::MaterialPipeline(const MaterialPipelineInfo& pipelineInfo) :
	m_pipelineInfo(pipelineInfo)
	{
	}

	/*!
	* \brief Enable pipeline states for rendering
	*
	* \param flags Shader flags
	*/
	inline const MaterialPipeline::Instance& MaterialPipeline::Apply(UInt32 flags) const
	{
		const Instance& instance = GetInstance(flags);
		instance.uberInstance->Activate();

		Renderer::SetRenderStates(m_pipelineInfo);

		return instance;
	}

	/*!
	* \brief Retrieve a MaterialPipelineInfo object describing this pipeline
	*
	* \return Pipeline informations
	*/
	const MaterialPipelineInfo& MaterialPipeline::GetInfo() const
	{
		return m_pipelineInfo;
	}

	/*!
	* \brief Retrieve (and generate if required) a pipeline instance using shader flags without applying it
	*
	* \param flags Shader flags
	*
	* \return Pipeline instance
	*/
	inline const MaterialPipeline::Instance& MaterialPipeline::GetInstance(UInt32 flags) const
	{
		const Instance& instance = m_instances[flags];
		if (!instance.uberInstance)
			GenerateRenderPipeline(flags);

		return instance;
	}

	bool operator==(const MaterialPipelineInfo& lhs, const MaterialPipelineInfo& rhs)
	{
		if (!operator==(static_cast<const RenderStates&>(lhs), static_cast<const RenderStates&>(rhs)))
			return false;

		#define NazaraPipelineMember(field) if (lhs.field != rhs.field) return false
		#define NazaraPipelineBoolMember NazaraPipelineMember

		NazaraPipelineBoolMember(alphaTest);
		NazaraPipelineBoolMember(depthSorting);
		NazaraPipelineBoolMember(hasAlphaMap);
		NazaraPipelineBoolMember(hasDiffuseMap);
		NazaraPipelineBoolMember(hasEmissiveMap);
		NazaraPipelineBoolMember(hasHeightMap);
		NazaraPipelineBoolMember(hasNormalMap);
		NazaraPipelineBoolMember(hasSpecularMap);
		NazaraPipelineBoolMember(shadowReceive);

		NazaraPipelineMember(uberShader);

		#undef NazaraPipelineMember
		#undef NazaraPipelineBoolMember

		return true;
	}

	bool operator!=(const MaterialPipelineInfo& lhs, const MaterialPipelineInfo& rhs)
	{
		return !operator==(lhs, rhs);
	}

	/*!
	* \brief Creates a new MaterialPipeline from the arguments
	* \return A reference to the newly created material pipeline
	*
	* \param args Arguments for the material pipeline
	*/
	template<typename... Args>
	MaterialPipelineRef MaterialPipeline::New(Args&&... args)
	{
		std::unique_ptr<MaterialPipeline> object(new MaterialPipeline(std::forward<Args>(args)...));
		object->SetPersistent(false);
		return object.release();
	}
}

namespace std
{
	template<>
	struct hash<Nz::MaterialPipelineInfo>
	{
		size_t operator()(const Nz::MaterialPipelineInfo& pipelineInfo) const
		{
			hash<Nz::RenderStates> parentHash;

			std::size_t seed = parentHash(pipelineInfo);

			Nz::UInt16 parameterHash = 0;
			Nz::UInt16 parameterIndex = 0;

			#define NazaraPipelineMember(member) Nz::HashCombine(seed, pipelineInfo.member)
			#define NazaraPipelineBoolMember(member) parameterHash |= ((pipelineInfo.member) ? 1U : 0U) << (parameterIndex++)

			NazaraPipelineBoolMember(alphaTest);
			NazaraPipelineBoolMember(depthSorting);
			NazaraPipelineBoolMember(hasAlphaMap);
			NazaraPipelineBoolMember(hasDiffuseMap);
			NazaraPipelineBoolMember(hasEmissiveMap);
			NazaraPipelineBoolMember(hasHeightMap);
			NazaraPipelineBoolMember(hasNormalMap);
			NazaraPipelineBoolMember(hasSpecularMap);
			NazaraPipelineBoolMember(shadowReceive);

			NazaraPipelineMember(uberShader);

			#undef NazaraPipelineMember
			#undef NazaraPipelineBoolMember

			Nz::HashCombine(seed, parameterHash);

			return seed;
		}
	};
}

#include <Nazara/Graphics/DebugOff.hpp>
<|endoftext|>


<commit_before><commit_msg>coverity#735851 Dereference after null check<commit_after><|endoftext|>


<commit_before>#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>
#include <vector>

AndroidClientCache::AndroidClientCache(JNIEnv * _env) : myEnv(_env) {
  myEnv->GetJavaVM(&javaVM);
  cookieManagerClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/webkit/CookieManager"));
  httpClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/HttpURLConnection"));
  urlClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URL"));
  urlConnectionClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URLConnection"));
  inputStreamClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/InputStream"));
  frameworkClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("com/sometrik/framework/FrameWork"));

  getHeaderMethod = myEnv->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;");
  getHeaderMethodInt = myEnv->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;");
  getHeaderKeyMethod = myEnv->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;");
  readMethod = myEnv->GetMethodID(inputStreamClass, "read", "([B)I");
  urlConstructor = myEnv->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
  openConnectionMethod = myEnv->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
  setUseCachesMethod = myEnv->GetMethodID(urlConnectionClass, "setUseCaches", "(Z)V");
  disconnectConnectionMethod = myEnv->GetMethodID(httpClass, "disconnect", "()V");
  setRequestProperty = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
  setRequestMethod = myEnv->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
  setFollowMethod = myEnv->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
  setDoInputMethod = myEnv->GetMethodID(httpClass, "setDoInput", "(Z)V");
  setDoOutputMethod = myEnv->GetMethodID(httpClass, "setDoOutput", "(Z)V");
  getResponseCodeMethod = myEnv->GetMethodID(httpClass, "getResponseCode", "()I");
  getResponseMessageMethod = myEnv->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
  setRequestPropertyMethod = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
  clearCookiesMethod = myEnv->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
  getInputStreamMethod = myEnv->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");
  getErrorStreamMethod = myEnv->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;");
  handleThrowableMethod = myEnv->GetStaticMethodID(frameworkClass, "handleNativeException", "(Ljava/lang/Throwable;)V");
}

AndroidClientCache::~AndroidClientCache() {
  __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClien", "destructor on clientCache");
  myEnv->DeleteGlobalRef(cookieManagerClass);
  myEnv->DeleteGlobalRef(httpClass);
  myEnv->DeleteGlobalRef(urlClass);
  myEnv->DeleteGlobalRef(inputStreamClass);
  myEnv->DeleteGlobalRef(frameworkClass);
}

class AndroidClient : public HTTPClient {
public:
  AndroidClient(const std::shared_ptr<AndroidClientCache> & _cache, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
    : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), cache(_cache) {
  }

  ~AndroidClient(){
   if (stored_env) {
       cache->getJavaVM()->DetachCurrentThread();
   }
  }

  JNIEnv * getEnv() {
    if (stored_env) return stored_env;
    else {
      stored_env = cache->createJNIEnv();
      // cache->checkEnvAttachment(&env);
      return stored_env;
    }
  }

  void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) {
    JNIEnv * env = getEnv();

    __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Host = %s, ua = %s", req.getURI().c_str(), user_agent.c_str());
    jstring juri = env->NewStringUTF(req.getURI().c_str());
    jobject url = env->NewObject(cache->urlClass, cache->urlConstructor, juri);
    env->DeleteLocalRef(juri);

    jobject connection = env->CallObjectMethod(url, cache->openConnectionMethod);
    env->CallVoidMethod(connection, cache->setUseCachesMethod, JNI_FALSE);
    env->DeleteLocalRef(url);

    //Authorization example
//    env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));
    std::string auth_header = auth.createHeader();
   env->CallVoidMethod(connection, cache->setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);

    // Setting headers for request
    std::map<std::string, std::string> combined_headers;
    for (auto & hd : default_headers) {
      combined_headers[hd.first] = hd.second;
    }
    combined_headers["User-Agent"] = user_agent;
    for (auto & hd : req.getHeaders()) {
      combined_headers[hd.first] = hd.second;
    }
    if (!auth_header.empty()) {
      __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Auth: %s = %s", auth.getHeaderName(), auth_header.c_str());
      combined_headers[auth.getHeaderName()] = auth_header;
    }
    for (auto & hd : combined_headers) {
      jstring firstHeader = env->NewStringUTF(hd.first.c_str());
      jstring secondHeader = env->NewStringUTF(hd.second.c_str());
      env->CallVoidMethod(connection, cache->setRequestPropertyMethod, firstHeader, secondHeader);
      env->DeleteLocalRef(firstHeader);
      env->DeleteLocalRef(secondHeader);
    }

    if (req.getType() == HTTPRequest::POST) {
      env->CallVoidMethod(connection, cache->setDoOutputMetod, true);
    } else {
      env->CallVoidMethod(connection, cache->setDoOutputMethod, false);
      if (req.getType() != HTTPRequest::GET) {
	jstring jTypeString = env->NewStringUTF(req.getTypeString());
	env->CallVoidMethod(connection, cache->setRequestMethod, jTypeString);
	env->DeleteLocalRef(jTypeString);
      }
    }

    int responseCode = env->CallIntMethod(connection, cache->getResponseCodeMethod);

    jobject input = 0;

    if (env->ExceptionCheck()) {
      env->ExceptionClear();
      __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "EXCEPTION http request failed");
      callback.handleResultCode(500);

    } else {
      __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);

      input = env->CallObjectMethod(connection, cache->getInputStreamMethod);
      callback.handleResultCode(responseCode);

      if (env->ExceptionCheck()) {
        env->ExceptionClear();
        __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "Exception while getting stream");
        input = env->CallObjectMethod(connection, cache->getErrorStreamMethod);
      }
    }
    if (input != 0) {
      // Gather headers and values
      for (int i = 0;; i++) {
        jstring jheaderKey = (jstring) env->CallObjectMethod(connection, cache->getHeaderKeyMethod, i);
        if (jheaderKey == NULL) {
          break;
        }
        const char * headerKey = env->GetStringUTFChars(jheaderKey, 0);

        jstring jheader = (jstring) env->CallObjectMethod(connection, cache->getHeaderMethodInt, i);
        const char * header = env->GetStringUTFChars(jheader, 0);
        __android_log_print(ANDROID_LOG_INFO, "content", "header: %s = %s", headerKey, header);

        callback.handleHeader(headerKey, header);

        if (strcasecmp(headerKey, "Location") == 0) {
          callback.handleRedirectUrl(header);
        }

        env->DeleteLocalRef(jheaderKey);
        env->DeleteLocalRef(jheader);
      }

      // Gather content
      jbyteArray array = env->NewByteArray(4096);
      int g = 0;
      while ((g = env->CallIntMethod(input, cache->readMethod, array)) != -1) {

        if (env->ExceptionCheck()) {
          __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "Exception while reading content");
          env->ExceptionClear();
          break;
        }
        jbyte* content_array = env->GetByteArrayElements(array, NULL);
        bool r = callback.handleChunk(g, (char*) content_array);
        env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);
	if (!r) {
	  break;
	}
      }
      env->DeleteLocalRef(array);

      callback.handleDisconnect();

      env->CallVoidMethod(connection, cache->disconnectConnectionMethod);
      env->DeleteLocalRef(input);
    }
    env->DeleteLocalRef(connection);
    cache->getJavaVM()->DetachCurrentThread();
    stored_env = 0;
}

  void clearCookies() {
//    JNIEnv * env = cache->getJNIEnv();
//    env->CallVoidMethod(cache->cookieManagerClass, cache->clearCookiesMethod);
  }

private:
  std::shared_ptr<AndroidClientCache> cache;
  JNIEnv * stored_env = 0;
};

std::unique_ptr<HTTPClient>
AndroidClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
  return std::unique_ptr<AndroidClient>(new AndroidClient(cache, _user_agent, _enable_cookies, _enable_keepalive));
}
<commit_msg>fix typo<commit_after>#include <AndroidClient.h>
#include <jni.h>
#include <android/log.h>
#include <vector>

AndroidClientCache::AndroidClientCache(JNIEnv * _env) : myEnv(_env) {
  myEnv->GetJavaVM(&javaVM);
  cookieManagerClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("android/webkit/CookieManager"));
  httpClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/HttpURLConnection"));
  urlClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URL"));
  urlConnectionClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/net/URLConnection"));
  inputStreamClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("java/io/InputStream"));
  frameworkClass = (jclass) myEnv->NewGlobalRef(myEnv->FindClass("com/sometrik/framework/FrameWork"));

  getHeaderMethod = myEnv->GetMethodID(httpClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;");
  getHeaderMethodInt = myEnv->GetMethodID(httpClass, "getHeaderField", "(I)Ljava/lang/String;");
  getHeaderKeyMethod = myEnv->GetMethodID(httpClass, "getHeaderFieldKey", "(I)Ljava/lang/String;");
  readMethod = myEnv->GetMethodID(inputStreamClass, "read", "([B)I");
  urlConstructor = myEnv->GetMethodID(urlClass, "<init>", "(Ljava/lang/String;)V");
  openConnectionMethod = myEnv->GetMethodID(urlClass, "openConnection", "()Ljava/net/URLConnection;");
  setUseCachesMethod = myEnv->GetMethodID(urlConnectionClass, "setUseCaches", "(Z)V");
  disconnectConnectionMethod = myEnv->GetMethodID(httpClass, "disconnect", "()V");
  setRequestProperty = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
  setRequestMethod = myEnv->GetMethodID(httpClass, "setRequestMethod", "(Ljava/lang/String;)V");
  setFollowMethod = myEnv->GetMethodID(httpClass, "setInstanceFollowRedirects", "(Z)V");
  setDoInputMethod = myEnv->GetMethodID(httpClass, "setDoInput", "(Z)V");
  setDoOutputMethod = myEnv->GetMethodID(httpClass, "setDoOutput", "(Z)V");
  getResponseCodeMethod = myEnv->GetMethodID(httpClass, "getResponseCode", "()I");
  getResponseMessageMethod = myEnv->GetMethodID(httpClass, "getResponseMessage", "()Ljava/lang/String;");
  setRequestPropertyMethod = myEnv->GetMethodID(httpClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
  clearCookiesMethod = myEnv->GetMethodID(cookieManagerClass, "removeAllCookie", "()V");
  getInputStreamMethod = myEnv->GetMethodID(httpClass, "getInputStream", "()Ljava/io/InputStream;");
  getErrorStreamMethod = myEnv->GetMethodID(httpClass, "getErrorStream", "()Ljava/io/InputStream;");
  handleThrowableMethod = myEnv->GetStaticMethodID(frameworkClass, "handleNativeException", "(Ljava/lang/Throwable;)V");
}

AndroidClientCache::~AndroidClientCache() {
  __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClien", "destructor on clientCache");
  myEnv->DeleteGlobalRef(cookieManagerClass);
  myEnv->DeleteGlobalRef(httpClass);
  myEnv->DeleteGlobalRef(urlClass);
  myEnv->DeleteGlobalRef(inputStreamClass);
  myEnv->DeleteGlobalRef(frameworkClass);
}

class AndroidClient : public HTTPClient {
public:
  AndroidClient(const std::shared_ptr<AndroidClientCache> & _cache, const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive)
    : HTTPClient(_user_agent, _enable_cookies, _enable_keepalive), cache(_cache) {
  }

  ~AndroidClient(){
   if (stored_env) {
       cache->getJavaVM()->DetachCurrentThread();
   }
  }

  JNIEnv * getEnv() {
    if (stored_env) return stored_env;
    else {
      stored_env = cache->createJNIEnv();
      // cache->checkEnvAttachment(&env);
      return stored_env;
    }
  }

  void request(const HTTPRequest & req, const Authorization & auth, HTTPClientInterface & callback) {
    JNIEnv * env = getEnv();

    __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Host = %s, ua = %s", req.getURI().c_str(), user_agent.c_str());
    jstring juri = env->NewStringUTF(req.getURI().c_str());
    jobject url = env->NewObject(cache->urlClass, cache->urlConstructor, juri);
    env->DeleteLocalRef(juri);

    jobject connection = env->CallObjectMethod(url, cache->openConnectionMethod);
    env->CallVoidMethod(connection, cache->setUseCachesMethod, JNI_FALSE);
    env->DeleteLocalRef(url);

    //Authorization example
//    env->CallVoidMethod(connection, setRequestPropertyMethod, env->NewStringUTF("Authorization"), env->NewStringUTF("myUsername"));
    std::string auth_header = auth.createHeader();
   env->CallVoidMethod(connection, cache->setFollowMethod, req.getFollowLocation() ? JNI_TRUE : JNI_FALSE);

    // Setting headers for request
    std::map<std::string, std::string> combined_headers;
    for (auto & hd : default_headers) {
      combined_headers[hd.first] = hd.second;
    }
    combined_headers["User-Agent"] = user_agent;
    for (auto & hd : req.getHeaders()) {
      combined_headers[hd.first] = hd.second;
    }
    if (!auth_header.empty()) {
      __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "Auth: %s = %s", auth.getHeaderName(), auth_header.c_str());
      combined_headers[auth.getHeaderName()] = auth_header;
    }
    for (auto & hd : combined_headers) {
      jstring firstHeader = env->NewStringUTF(hd.first.c_str());
      jstring secondHeader = env->NewStringUTF(hd.second.c_str());
      env->CallVoidMethod(connection, cache->setRequestPropertyMethod, firstHeader, secondHeader);
      env->DeleteLocalRef(firstHeader);
      env->DeleteLocalRef(secondHeader);
    }

    if (req.getType() == HTTPRequest::POST) {
      env->CallVoidMethod(connection, cache->setDoOutputMethod, true);
    } else {
      env->CallVoidMethod(connection, cache->setDoOutputMethod, false);
      if (req.getType() != HTTPRequest::GET) {
	jstring jTypeString = env->NewStringUTF(req.getTypeString());
	env->CallVoidMethod(connection, cache->setRequestMethod, jTypeString);
	env->DeleteLocalRef(jTypeString);
      }
    }

    int responseCode = env->CallIntMethod(connection, cache->getResponseCodeMethod);

    jobject input = 0;

    if (env->ExceptionCheck()) {
      env->ExceptionClear();
      __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "EXCEPTION http request failed");
      callback.handleResultCode(500);

    } else {
      __android_log_print(ANDROID_LOG_INFO, "AndroidClient", "http request responsecode = %i", responseCode);

      input = env->CallObjectMethod(connection, cache->getInputStreamMethod);
      callback.handleResultCode(responseCode);

      if (env->ExceptionCheck()) {
        env->ExceptionClear();
        __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "Exception while getting stream");
        input = env->CallObjectMethod(connection, cache->getErrorStreamMethod);
      }
    }
    if (input != 0) {
      // Gather headers and values
      for (int i = 0;; i++) {
        jstring jheaderKey = (jstring) env->CallObjectMethod(connection, cache->getHeaderKeyMethod, i);
        if (jheaderKey == NULL) {
          break;
        }
        const char * headerKey = env->GetStringUTFChars(jheaderKey, 0);

        jstring jheader = (jstring) env->CallObjectMethod(connection, cache->getHeaderMethodInt, i);
        const char * header = env->GetStringUTFChars(jheader, 0);
        __android_log_print(ANDROID_LOG_INFO, "content", "header: %s = %s", headerKey, header);

        callback.handleHeader(headerKey, header);

        if (strcasecmp(headerKey, "Location") == 0) {
          callback.handleRedirectUrl(header);
        }

        env->DeleteLocalRef(jheaderKey);
        env->DeleteLocalRef(jheader);
      }

      // Gather content
      jbyteArray array = env->NewByteArray(4096);
      int g = 0;
      while ((g = env->CallIntMethod(input, cache->readMethod, array)) != -1) {

        if (env->ExceptionCheck()) {
          __android_log_print(ANDROID_LOG_VERBOSE, "AndroidClient", "Exception while reading content");
          env->ExceptionClear();
          break;
        }
        jbyte* content_array = env->GetByteArrayElements(array, NULL);
        bool r = callback.handleChunk(g, (char*) content_array);
        env->ReleaseByteArrayElements(array, content_array, JNI_ABORT);
	if (!r) {
	  break;
	}
      }
      env->DeleteLocalRef(array);

      callback.handleDisconnect();

      env->CallVoidMethod(connection, cache->disconnectConnectionMethod);
      env->DeleteLocalRef(input);
    }
    env->DeleteLocalRef(connection);
    cache->getJavaVM()->DetachCurrentThread();
    stored_env = 0;
}

  void clearCookies() {
//    JNIEnv * env = cache->getJNIEnv();
//    env->CallVoidMethod(cache->cookieManagerClass, cache->clearCookiesMethod);
  }

private:
  std::shared_ptr<AndroidClientCache> cache;
  JNIEnv * stored_env = 0;
};

std::unique_ptr<HTTPClient>
AndroidClientFactory::createClient2(const std::string & _user_agent, bool _enable_cookies, bool _enable_keepalive) {
  return std::unique_ptr<AndroidClient>(new AndroidClient(cache, _user_agent, _enable_cookies, _enable_keepalive));
}
<|endoftext|>


<commit_before>// Copyright 2010-2015 RethinkDB, all rights reserved.
#include "clustering/table_contract/executor.hpp"

#include "clustering/table_contract/exec_erase.hpp"
#include "clustering/table_contract/exec_primary.hpp"
#include "clustering/table_contract/exec_secondary.hpp"
#include "store_subview.hpp"

contract_executor_t::contract_executor_t(
        const server_id_t &_server_id,
        mailbox_manager_t *_mailbox_manager,
        const clone_ptr_t<watchable_t<table_raft_state_t> > &_raft_state,
        watchable_map_t<std::pair<server_id_t, branch_id_t>, contract_execution_bcard_t>
            *_remote_contract_execution_bcards,
        multistore_ptr_t *_multistore,
        const base_path_t &_base_path,
        io_backender_t *_io_backender,
        backfill_throttler_t *_backfill_throttler,
        perfmon_collection_t *_perfmons) :
    server_id(_server_id),
    raft_state(_raft_state),
    multistore(_multistore),
    perfmons(_perfmons),
    perfmon_counter(0),
    update_pumper(new pump_coro_t(
        std::bind(&contract_executor_t::update_blocking, this, ph::_1))),
    raft_state_subs([this]() { update_pumper->notify(); })
{
    execution_context.server_id = _server_id;
    execution_context.mailbox_manager = _mailbox_manager;
    execution_context.branch_history_manager = multistore->get_branch_history_manager();
    execution_context.base_path = _base_path;
    execution_context.io_backender = _io_backender;
    execution_context.backfill_throttler = _backfill_throttler;
    execution_context.remote_contract_execution_bcards
        = _remote_contract_execution_bcards;
    execution_context.local_contract_execution_bcards
        = &local_contract_execution_bcards;
    execution_context.local_table_query_bcards = &local_table_query_bcards;

    multistore->assert_thread();

    watchable_t<table_raft_state_t>::freeze_t freeze(raft_state);
    raft_state_subs.reset(raft_state, &freeze);
    update_pumper->notify();
}

contract_executor_t::~contract_executor_t() {
    /* Run destructors manually so that we can control how `executions` is destroyed. We
    want to first destroy every individual execution without modifying the `std::map`,
    then we want to destroy the `std::map`. This is because the `execution_t`s can
    access the `std::map` via `send_ack()` until they are all destroyed. */

    raft_state_subs.reset();

    /* Call `drain()` before setting `update_pumper` itself to null because
    `update_blocking()` will sometimes try to dereference `update_pumper`. */
    update_pumper->drain();
    update_pumper.reset();

    for (auto &&pair : executions) {
        pair.second->execution.reset();
    }
}

contract_executor_t::execution_key_t contract_executor_t::get_contract_key(
        const std::pair<region_t, contract_t> &pair,
        const branch_id_t &branch) {
    execution_key_t key;
    key.region = pair.first;
    if (static_cast<bool>(pair.second.primary) &&
            pair.second.primary->server == server_id) {
        key.role = execution_key_t::role_t::primary;
        key.primary = nil_uuid();
        key.branch = nil_uuid();
    } else if (pair.second.replicas.count(server_id) == 1) {
        key.role = execution_key_t::role_t::secondary;
        if (static_cast<bool>(pair.second.primary)) {
            key.primary = pair.second.primary->server;
        } else {
            key.primary = nil_uuid();
        }
        key.branch = branch;
    } else {
        key.role = execution_key_t::role_t::erase;
        key.primary = nil_uuid();
        key.branch = nil_uuid();
    }
    return key;
}

void contract_executor_t::update_blocking(UNUSED signal_t *interruptor) {
    std::set<execution_key_t> to_delete;
    {
        ASSERT_NO_CORO_WAITING;
        raft_state->apply_read([&](const table_raft_state_t *state) {
            update(*state, &to_delete); });
    }
    if (!to_delete.empty()) {
        for (const execution_key_t &key : to_delete) {
            auto it = executions.find(key);
            guarantee(it != executions.end());
            /* Resetting `execution` is the part that can block. */
            it->second->execution.reset();
            /* Remove the entry from the ack map, only once we are sure that the
            execution won't recreate it. */
            ack_map.delete_key(std::make_pair(server_id, it->second->contract_id));
            /* Note that we do a two-step process: first we reset `execution`, then we
            erase the entry from `executions`. This is because until we finish resetting
            `execution`, it may still be calling `send_ack()`, and it's important that
            `send_ack()` be able to see the entry in `executions`. */
            executions.erase(it);
        }
        /* Now that we've deleted the executions, `update()` is likely to have new
        instructions for us, so we should run again. */
        update_pumper->notify();
    }
}

void contract_executor_t::update(const table_raft_state_t &new_state,
                                 std::set<execution_key_t> *to_delete_out) {
    assert_thread();
    /* Go through the new contracts and try to match them to existing executions */
    std::set<execution_key_t> dont_delete;
    for (const auto &new_pair : new_state.contracts) {
        /* Extract the current branch ID for the region covered by this contract.
        If there are multiple branches for different subregions, we consider
        the branch as incoherent and don't set a branch ID. */
        branch_id_t branch = nil_uuid();
        region_map_t<branch_id_t> branch_intersection =
            new_state.current_branches.mask(new_pair.second.first);
        bool branch_mismatch = false;
        branch_intersection.visit(new_pair.second.first,
        [&](const region_t &, const branch_id_t &b) {
            if (branch.is_nil()) {
                branch = b;
            } else if (branch != b) {
                branch_mismatch = true;
            }
        });
        if (branch_mismatch) {
            branch = nil_uuid();
        }

        execution_key_t key = get_contract_key(new_pair.second, branch);
        dont_delete.insert(key);
        auto it = executions.find(key);
        if (it != executions.end()) {
            /* Update the existing execution */
            contract_id_t old_contract_id = it->second->contract_id;
            it->second->contract_id = new_pair.first;
            /* Note that `update_contract_or_raft_state()` will never block.
            Also note that we call it even if the contract ID has not actually changed,
            because it might care about the changes to the parts of the Raft state
            other than the contract. */
            it->second->execution->update_contract_or_raft_state(
                new_pair.first, new_state);
            if (old_contract_id != new_pair.first) {
                /* Delete the old contract ack, if there was one */
                ack_map.delete_key(std::make_pair(server_id, old_contract_id));
            }
        } else {
            /* Create a new execution, unless there's already an execution whose region
            overlaps ours. In the latter case, the execution will be deleted soon. */
            bool ok_to_create = true;
            for (const auto &old_pair : executions) {
                if (region_overlaps(old_pair.first.region, new_pair.second.first)) {
                    ok_to_create = false;
                    break;
                }
            }
            if (ok_to_create) {
                executions[key] = make_scoped<execution_data_t>();
                execution_data_t *data = executions[key].get();
                data->contract_id = new_pair.first;

                data->store_subview = make_scoped<store_subview_t>(
                    multistore->get_cpu_sharded_store(get_cpu_shard_number(key.region)),
                    key.region);

                /* We generate perfmon keys of the form "primary-3", "secondary-8", etc.
                The numbers are arbitrary but unique. */
                data->perfmon_membership = make_scoped<perfmon_membership_t>(
                    perfmons, &data->perfmon_collection,
                    strprintf("%s-%d", key.role_name().c_str(), ++perfmon_counter));

                std::function<void(const contract_id_t &, const contract_ack_t &)>
                    acker = std::bind(&contract_executor_t::send_ack, this,
                        key, ph::_1, ph::_2);
                /* Note that these constructors will never block. */
                switch (key.role) {
                case execution_key_t::role_t::primary:
                    data->execution.init(new primary_execution_t(
                        &execution_context, data->store_subview.get(),
                        &data->perfmon_collection, acker,
                        new_pair.first, new_state));
                    break;
                case execution_key_t::role_t::secondary:
                    data->execution.init(new secondary_execution_t(
                        &execution_context, data->store_subview.get(),
                        &data->perfmon_collection, acker,
                        new_pair.first, new_state, branch));
                    break;
                case execution_key_t::role_t::erase:
                    data->execution.init(new erase_execution_t(
                        &execution_context, data->store_subview.get(),
                        &data->perfmon_collection, acker,
                        new_pair.first, new_state));
                    break;
                default: unreachable();
                }
            }
        }
    }
    /* Go through our existing executions and delete the ones that don't correspond to
    any of the new contracts */
    for (const auto &old_pair : executions) {
        if (dont_delete.count(old_pair.first) == 0) {
            to_delete_out->insert(old_pair.first);
        }
    }
}

void contract_executor_t::send_ack(const execution_key_t &key, const contract_id_t &cid,
        const contract_ack_t &ack) {
    assert_thread();
    /* If the contract is out of date, don't send the ack */
    if (executions.at(key)->contract_id == cid) {
        ack_map.set_key_no_equals(std::make_pair(server_id, cid), ack);
    }
}

<commit_msg>Removed redundant code<commit_after>// Copyright 2010-2015 RethinkDB, all rights reserved.
#include "clustering/table_contract/executor.hpp"

#include "clustering/table_contract/exec_erase.hpp"
#include "clustering/table_contract/exec_primary.hpp"
#include "clustering/table_contract/exec_secondary.hpp"
#include "store_subview.hpp"

contract_executor_t::contract_executor_t(
        const server_id_t &_server_id,
        mailbox_manager_t *_mailbox_manager,
        const clone_ptr_t<watchable_t<table_raft_state_t> > &_raft_state,
        watchable_map_t<std::pair<server_id_t, branch_id_t>, contract_execution_bcard_t>
            *_remote_contract_execution_bcards,
        multistore_ptr_t *_multistore,
        const base_path_t &_base_path,
        io_backender_t *_io_backender,
        backfill_throttler_t *_backfill_throttler,
        perfmon_collection_t *_perfmons) :
    server_id(_server_id),
    raft_state(_raft_state),
    multistore(_multistore),
    perfmons(_perfmons),
    perfmon_counter(0),
    update_pumper(new pump_coro_t(
        std::bind(&contract_executor_t::update_blocking, this, ph::_1))),
    raft_state_subs([this]() { update_pumper->notify(); })
{
    execution_context.server_id = _server_id;
    execution_context.mailbox_manager = _mailbox_manager;
    execution_context.branch_history_manager = multistore->get_branch_history_manager();
    execution_context.base_path = _base_path;
    execution_context.io_backender = _io_backender;
    execution_context.backfill_throttler = _backfill_throttler;
    execution_context.remote_contract_execution_bcards
        = _remote_contract_execution_bcards;
    execution_context.local_contract_execution_bcards
        = &local_contract_execution_bcards;
    execution_context.local_table_query_bcards = &local_table_query_bcards;

    multistore->assert_thread();

    watchable_t<table_raft_state_t>::freeze_t freeze(raft_state);
    raft_state_subs.reset(raft_state, &freeze);
    update_pumper->notify();
}

contract_executor_t::~contract_executor_t() {
    /* Run destructors manually so that we can control how `executions` is destroyed. We
    want to first destroy every individual execution without modifying the `std::map`,
    then we want to destroy the `std::map`. This is because the `execution_t`s can
    access the `std::map` via `send_ack()` until they are all destroyed. */

    raft_state_subs.reset();

    /* Call `drain()` before setting `update_pumper` itself to null because
    `update_blocking()` will sometimes try to dereference `update_pumper`. */
    update_pumper->drain();
    update_pumper.reset();

    for (auto &&pair : executions) {
        pair.second->execution.reset();
    }
}

contract_executor_t::execution_key_t contract_executor_t::get_contract_key(
        const std::pair<region_t, contract_t> &pair,
        const branch_id_t &branch) {
    execution_key_t key;
    key.region = pair.first;
    if (static_cast<bool>(pair.second.primary) &&
            pair.second.primary->server == server_id) {
        key.role = execution_key_t::role_t::primary;
        key.primary = nil_uuid();
        key.branch = nil_uuid();
    } else if (pair.second.replicas.count(server_id) == 1) {
        key.role = execution_key_t::role_t::secondary;
        if (static_cast<bool>(pair.second.primary)) {
            key.primary = pair.second.primary->server;
        } else {
            key.primary = nil_uuid();
        }
        key.branch = branch;
    } else {
        key.role = execution_key_t::role_t::erase;
        key.primary = nil_uuid();
        key.branch = nil_uuid();
    }
    return key;
}

void contract_executor_t::update_blocking(UNUSED signal_t *interruptor) {
    std::set<execution_key_t> to_delete;
    {
        ASSERT_NO_CORO_WAITING;
        raft_state->apply_read([&](const table_raft_state_t *state) {
            update(*state, &to_delete); });
    }
    if (!to_delete.empty()) {
        for (const execution_key_t &key : to_delete) {
            auto it = executions.find(key);
            guarantee(it != executions.end());
            /* Resetting `execution` is the part that can block. */
            it->second->execution.reset();
            /* Remove the entry from the ack map, only once we are sure that the
            execution won't recreate it. */
            ack_map.delete_key(std::make_pair(server_id, it->second->contract_id));
            /* Note that we do a two-step process: first we reset `execution`, then we
            erase the entry from `executions`. This is because until we finish resetting
            `execution`, it may still be calling `send_ack()`, and it's important that
            `send_ack()` be able to see the entry in `executions`. */
            executions.erase(it);
        }
        /* Now that we've deleted the executions, `update()` is likely to have new
        instructions for us, so we should run again. */
        update_pumper->notify();
    }
}

void contract_executor_t::update(const table_raft_state_t &new_state,
                                 std::set<execution_key_t> *to_delete_out) {
    assert_thread();
    /* Go through the new contracts and try to match them to existing executions */
    std::set<execution_key_t> dont_delete;
    for (const auto &new_pair : new_state.contracts) {
        /* Extract the current branch ID for the region covered by this contract.
        If there are multiple branches for different subregions, we consider
        the branch as incoherent and don't set a branch ID. */
        branch_id_t branch = nil_uuid();
        bool branch_mismatch = false;
        new_state.current_branches.visit(new_pair.second.first,
        [&](const region_t &, const branch_id_t &b) {
            if (branch.is_nil()) {
                branch = b;
            } else if (branch != b) {
                branch_mismatch = true;
            }
        });
        if (branch_mismatch) {
            branch = nil_uuid();
        }

        execution_key_t key = get_contract_key(new_pair.second, branch);
        dont_delete.insert(key);
        auto it = executions.find(key);
        if (it != executions.end()) {
            /* Update the existing execution */
            contract_id_t old_contract_id = it->second->contract_id;
            it->second->contract_id = new_pair.first;
            /* Note that `update_contract_or_raft_state()` will never block.
            Also note that we call it even if the contract ID has not actually changed,
            because it might care about the changes to the parts of the Raft state
            other than the contract. */
            it->second->execution->update_contract_or_raft_state(
                new_pair.first, new_state);
            if (old_contract_id != new_pair.first) {
                /* Delete the old contract ack, if there was one */
                ack_map.delete_key(std::make_pair(server_id, old_contract_id));
            }
        } else {
            /* Create a new execution, unless there's already an execution whose region
            overlaps ours. In the latter case, the execution will be deleted soon. */
            bool ok_to_create = true;
            for (const auto &old_pair : executions) {
                if (region_overlaps(old_pair.first.region, new_pair.second.first)) {
                    ok_to_create = false;
                    break;
                }
            }
            if (ok_to_create) {
                executions[key] = make_scoped<execution_data_t>();
                execution_data_t *data = executions[key].get();
                data->contract_id = new_pair.first;

                data->store_subview = make_scoped<store_subview_t>(
                    multistore->get_cpu_sharded_store(get_cpu_shard_number(key.region)),
                    key.region);

                /* We generate perfmon keys of the form "primary-3", "secondary-8", etc.
                The numbers are arbitrary but unique. */
                data->perfmon_membership = make_scoped<perfmon_membership_t>(
                    perfmons, &data->perfmon_collection,
                    strprintf("%s-%d", key.role_name().c_str(), ++perfmon_counter));

                std::function<void(const contract_id_t &, const contract_ack_t &)>
                    acker = std::bind(&contract_executor_t::send_ack, this,
                        key, ph::_1, ph::_2);
                /* Note that these constructors will never block. */
                switch (key.role) {
                case execution_key_t::role_t::primary:
                    data->execution.init(new primary_execution_t(
                        &execution_context, data->store_subview.get(),
                        &data->perfmon_collection, acker,
                        new_pair.first, new_state));
                    break;
                case execution_key_t::role_t::secondary:
                    data->execution.init(new secondary_execution_t(
                        &execution_context, data->store_subview.get(),
                        &data->perfmon_collection, acker,
                        new_pair.first, new_state, branch));
                    break;
                case execution_key_t::role_t::erase:
                    data->execution.init(new erase_execution_t(
                        &execution_context, data->store_subview.get(),
                        &data->perfmon_collection, acker,
                        new_pair.first, new_state));
                    break;
                default: unreachable();
                }
            }
        }
    }
    /* Go through our existing executions and delete the ones that don't correspond to
    any of the new contracts */
    for (const auto &old_pair : executions) {
        if (dont_delete.count(old_pair.first) == 0) {
            to_delete_out->insert(old_pair.first);
        }
    }
}

void contract_executor_t::send_ack(const execution_key_t &key, const contract_id_t &cid,
        const contract_ack_t &ack) {
    assert_thread();
    /* If the contract is out of date, don't send the ack */
    if (executions.at(key)->contract_id == cid) {
        ack_map.set_key_no_equals(std::make_pair(server_id, cid), ack);
    }
}

<|endoftext|>


<commit_before>#pragma once

// std
#include <cstdint>

// libraries
#include "nlohmann/json.hpp"

namespace dai {

struct EEPROMData {
    // int64_t sec, nsec;
    bool SwapLeftRightCam;
    double MonoFovRad, RGBFovRad; // Can we change this to radians? most of the standard api's prefer radian. would make things easier to integrate
    double LeftRightDistanceMtrs, LeftRGBDistanceMtrs; // since gen2 is more flexible can we move these to setting during pipeline creation or can be used from calibration
    std::string name, revision; // board name. do we need this ? it might help in debugging which device the user is using.
    /**
     * While helping OPAL I realized this can also be produced rectification from the other information we get during calibration.
     * we might need to add that function on the host side if the users want to use rgb camera like OPAL did
    **/
    std::vector<std::vector<double>> RectifiedRotationLeft, RectifiedRotationRight;
    // Intriniscs of the cameras
    std::vector<std::vector<double>> IntrinsicMatrixLeft, IntrinsicMatrixRight, IntrinsicMatrixRGB;
    // Relative rotation between cameras
    std::vector<std::vector<double>> RotationMatrixLeftRight, RotationMatrixRightRGB; // need to add IMU extrinsics later
    // Relative translation between cameras
    std::vector<double> TranslationLeftRight, TranslationRightRGB;
    // Distortion Coefficients
    std::vector<double> DistortionCoeffLeft, DistortionCoeffRight, DistortionCoeffRGB;

    NLOHMANN_DEFINE_TYPE_INTRUSIVE(EEPROMData, SwapLeftRightCam, MonoFovRad, RGBFovRad, LeftRightDistanceMtrs, \
                                    LeftRGBDistanceMtrs, name, revision, RectifiedRotationLeft, RectifiedRotationRight,\
                                    IntrinsicMatrixLeft, IntrinsicMatrixRight, IntrinsicMatrixRGB, \
                                    RotationMatrixLeftRight, RotationMatrixRightRGB, TranslationLeftRight,\
                                    TranslationRightRGB, DistortionCoeffLeft, DistortionCoeffRight, DistortionCoeffRGB);
};

} // namespace dai
<commit_msg>modified eeprom structure<commit_after>#pragma once

// std
#include <cstdint>

// libraries
#include "nlohmann/json.hpp"

namespace dai {

struct EepromData {
    // int64_t sec, nsec;
    bool swapLeftRightCam;
    // Can we change this to radians? most of the standard api's prefer radian. would make things easier to integrate
    double monoFovRad, rgbFovRad;
    // since gen2 is more flexible can we move distance vars to setting during pipeline creation or can be used from calibration
    double leftRightDistanceMtrs, leftRGBDistanceMtrs;
    // board name. do we need this ? it might help in debugging which device the user is using.
    std::string name, revision;
    /**
     * While helping OPAL I realized this can also be produced rectification from the other information we get during calibration.
     * we might need to add that function on the host side if the users want to use rgb camera like OPAL did
     **/
    std::vector<std::vector<double>> rectifiedRotationLeft, rectifiedRotationRight;
    // Intriniscs of the cameras
    std::vector<std::vector<double>> intrinsicMatrixLeft, intrinsicMatrixRight, intrinsicMatrixRGB;
    // Relative rotation between cameras
    std::vector<std::vector<double>> rotationMatrixLeftRight, rotationMatrixRightRGB;  // need to add IMU extrinsics later
    // Relative translation between cameras
    std::vector<double> translationLeftRight, translationRightRGB;
    // Distortion Coefficients
    std::vector<double> distortionCoeffLeft, distortionCoeffRight, distortionCoeffRGB;

    NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData,
                                   swapLeftRightCam,
                                   monoFovRad,
                                   rgbFovRad,
                                   leftRightDistanceMtrs,
                                   leftRGBDistanceMtrs,
                                   name,
                                   revision,
                                   rectifiedRotationLeft,
                                   rectifiedRotationRight,
                                   intrinsicMatrixLeft,
                                   intrinsicMatrixRight,
                                   intrinsicMatrixRGB,
                                   rotationMatrixLeftRight,
                                   rotationMatrixRightRGB,
                                   translationLeftRight,
                                   translationRightRGB,
                                   distortionCoeffLeft,
                                   distortionCoeffRight,
                                   distortionCoeffRGB);
};

}  // namespace dai
<|endoftext|>


<commit_before>#pragma once

#include "pajlada/settings/setting.hpp"
#include "pajlada/settings/settingdata.hpp"

#include <pajlada/signals/connection.hpp>

namespace pajlada {
namespace Settings {

class SettingListener
{
public:
    using Callback = std::function<void(const SignalArgs &)>;

    SettingListener() = default;

    SettingListener(Callback _cb)
        : cb(_cb)
    {
    }

    SettingListener(SettingListener &&other)
        : cb(std::move(other.cb))
        , settings(std::move(other.settings))
    {
        other.managedConnections.clear();

        for (auto &setting : this->settings) {
            if (auto s = setting.lock()) {
                this->addRawSetting(s);
            }
        }
    }

    SettingListener &
    operator=(SettingListener &&other)
    {
        other.managedConnections.clear();

        this->cb = std::move(other.cb);
        this->settings = std::move(other.settings);

        for (auto &setting : this->settings) {
            if (auto s = setting.lock()) {
                this->addRawSetting(s);
            }
        }
    }

    SettingListener(const SettingListener &) = delete;
    SettingListener &operator=(const SettingListener &) = delete;

    void
    addRawSetting(std::shared_ptr<ISettingData> setting)
    {
        auto connection = setting->simpleValueChanged.connect([this](const SignalArgs &args) {
            if (this->cb) {
                this->cb(args);
            }
        });

        this->managedConnections.emplace_back(std::move(connection));
    }

    template <typename AnySetting>
    void
    addSetting(AnySetting &setting)
    {
        this->settings.emplace_back(setting.getData());

        auto connection = setting.getSimpleSignal().connect([this](const SignalArgs &args) {
            if (this->cb) {
                this->cb(args);
            }
        });

        this->managedConnections.emplace_back(std::move(connection));
    }

    Callback cb;

private:
    std::vector<std::weak_ptr<pajlada::Settings::ISettingData>> settings;

    std::vector<pajlada::Signals::ScopedConnection> managedConnections;
};

}  // namespace Settings
}  // namespace pajlada
<commit_msg>fix compilation issue on gcc (thanks @Fourtf)<commit_after>#pragma once

#include "pajlada/settings/setting.hpp"
#include "pajlada/settings/settingdata.hpp"

#include <pajlada/signals/connection.hpp>

namespace pajlada {
namespace Settings {

class SettingListener
{
public:
    using Callback = std::function<void(const SignalArgs &)>;

    SettingListener() = default;

    SettingListener(Callback _cb)
        : cb(_cb)
    {
    }

    SettingListener(SettingListener &&other)
        : cb(std::move(other.cb))
        , settings(std::move(other.settings))
    {
        other.managedConnections.clear();

        for (auto &setting : this->settings) {
            if (auto s = setting.lock()) {
                this->addRawSetting(s);
            }
        }
    }

    SettingListener &
    operator=(SettingListener &&other)
    {
        other.managedConnections.clear();

        this->cb = std::move(other.cb);
        this->settings = std::move(other.settings);

        for (auto &setting : this->settings) {
            if (auto s = setting.lock()) {
                this->addRawSetting(s);
            }
        }

        return *this;
    }

    SettingListener(const SettingListener &) = delete;
    SettingListener &operator=(const SettingListener &) = delete;

    void
    addRawSetting(std::shared_ptr<ISettingData> setting)
    {
        auto connection = setting->simpleValueChanged.connect([this](const SignalArgs &args) {
            if (this->cb) {
                this->cb(args);
            }
        });

        this->managedConnections.emplace_back(std::move(connection));
    }

    template <typename AnySetting>
    void
    addSetting(AnySetting &setting)
    {
        this->settings.emplace_back(setting.getData());

        auto connection = setting.getSimpleSignal().connect([this](const SignalArgs &args) {
            if (this->cb) {
                this->cb(args);
            }
        });

        this->managedConnections.emplace_back(std::move(connection));
    }

    Callback cb;

private:
    std::vector<std::weak_ptr<pajlada::Settings::ISettingData>> settings;

    std::vector<pajlada::Signals::ScopedConnection> managedConnections;
};

}  // namespace Settings
}  // namespace pajlada
<|endoftext|>


<commit_before>#include "capabilities.hpp"

#include <stdio.h>

namespace fcwt {

#if 0
const uint32_t iso_flag_auto = 1 << 31;
const uint32_t iso_flag_emulated = 1 << 30;
const uint32_t iso_value_mask = 0x00ffffff;
const uint32_t iso_max_levels = 32;

struct iso_caps
{
    uint32_t levels[iso_max_levels] = {};
    uint32_t numLevels = 0;
};

enum shutter_speed_mode
{
    shutter_speed_auto,
    shutter_speed_manual
};

struct shutter_speed_caps
{
    shutter_speed_mode mode = shutter_speed_auto;
    uint32_t value = 0;
    int32_t exposure = 0;
};

struct aperture_caps
{
    uint32_t value = 0;
};

struct auto_focus_caps
{
    // TODO
};

struct camera_capabilities
{
    iso_caps iso;
    shutter_speed_caps shutterSpeed;
    auto_focus_caps autoFocus;
    aperture_caps apterture;
};
#endif

void print(camera_capabilities const& caps)
{
    printf("camera capabilities:\n");

    printf("\tiso levels (%d):\n", caps.iso.numLevels);
    for (uint32_t i = 0; i < caps.iso.numLevels; ++i)
    {
        auto const lvl = caps.iso.levels[i];
        char const* flag = "";
        if (lvl & iso_flag_auto)
            flag = " (auto)";
        else if (lvl & iso_flag_emulated)
            flag = " (emulated)";

        printf("\t\t%12d%s\n", lvl & iso_value_mask, flag);
    }

    printf("\tshutter speed:\n");
    printf("\t\tmode: %s\n", caps.shutter_speed.mode == shutter_speed_auto ? "auto" : "manual");
    if (caps.shutter_speed.mode == shutter_speed_manual)
        printf("\t\ttime: 1/%ds\n", caps.shutter_speed.value);
    else
        printf("\t\texposure: %d\n", static_cast<int>(caps.shutter_speed.exposure));
    printf("\taperture:\n");
    if (caps.aperture.value)
        printf("\t\tvalue: %.1f\n", static_cast<float>(caps.aperture.value) / 100.f);
    else
        printf("\t\tauto\n");
}

} // namespace fcwt<commit_msg>Remove disabled code<commit_after>#include "capabilities.hpp"

#include <stdio.h>

namespace fcwt {

void print(camera_capabilities const& caps)
{
    printf("camera capabilities:\n");

    printf("\tiso levels (%d):\n", caps.iso.numLevels);
    for (uint32_t i = 0; i < caps.iso.numLevels; ++i)
    {
        auto const lvl = caps.iso.levels[i];
        char const* flag = "";
        if (lvl & iso_flag_auto)
            flag = " (auto)";
        else if (lvl & iso_flag_emulated)
            flag = " (emulated)";

        printf("\t\t%12d%s\n", lvl & iso_value_mask, flag);
    }

    printf("\tshutter speed:\n");
    printf("\t\tmode: %s\n", caps.shutter_speed.mode == shutter_speed_auto ? "auto" : "manual");
    if (caps.shutter_speed.mode == shutter_speed_manual)
        printf("\t\ttime: 1/%ds\n", caps.shutter_speed.value);
    else
        printf("\t\texposure: %d\n", static_cast<int>(caps.shutter_speed.exposure));
    printf("\taperture:\n");
    if (caps.aperture.value)
        printf("\t\tvalue: %.1f\n", static_cast<float>(caps.aperture.value) / 100.f);
    else
        printf("\t\tauto\n");
}

} // namespace fcwt<|endoftext|>