Exemple #1
0
void drawJes(TTree * Events)
{
  aliases(Events);
  TProfile * hJes = new TProfile("hJes","jes",20,0,150);
  TCanvas * cJes = new TCanvas("cJes","cJes",500,500);
  Events->Draw("jet.p4().pt()/gjet.p4().pt():gjet.p4().pt()>>hJes");
}
static void dump_string(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_debug *self = (grib_dumper_debug*)d;
  char value[1024]; size_t size = sizeof(value);
  int err = grib_unpack_string(a,value,&size);
  int i;
  char *p = value;

  if(err) strcpy(value,"<error>");


  if( a->length == 0  &&
      (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
    return;

  set_begin_end(d,a);

  while(*p) { if(!isprint(*p)) *p = '.'; p++; }

  for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
  fprintf(self->dumper.out,"%ld-%ld %s %s = %s",self->begin,self->end,a->creator->op, a->name,value);

  if(comment) fprintf(self->dumper.out," [%s]",comment);
  if(err)
    fprintf(self->dumper.out," *** ERR=%d (%s)",err,grib_get_error_message(err));
  aliases(d,a);
  fprintf(self->dumper.out,"\n");
}
static void dump_bits(grib_dumper* d,grib_accessor* a,const char* comment)
{
    grib_dumper_debug *self = (grib_dumper_debug*)d;
    long value; size_t size = 1;
    int err = grib_unpack_long(a,&value,&size);
    int i;

    if( a->length == 0  &&
            (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
        return;

    set_begin_end(d,a);

    for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
    fprintf(self->dumper.out,"%ld-%ld %s %s = %ld [",self->begin,self->theEnd, a->creator->op,a->name,value);

    for(i=0;i<(a->length*8);i++) {
        if(test_bit(value,a->length*8-i-1))
            fprintf(self->dumper.out,"1");
        else
            fprintf(self->dumper.out,"0");
    }

    if(comment)
        fprintf(self->dumper.out,":%s]",comment);
    else
        fprintf(self->dumper.out,"]");

    if(err)
        fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_debug::dump_bits]",err,grib_get_error_message(err));

    aliases(d,a);
    fprintf(self->dumper.out,"\n");
}
static void dump_name_only(grib_dumper* d,grib_accessor* a,const char* comment) {
  grib_dumper_keys *self = (grib_dumper_keys*)d;

  print_offset(self->dumper.out,d,a);


  if (a->flags & GRIB_ACCESSOR_FLAG_HIDDEN) {
    return;
  }

  if( a->length == 0  &&
      (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
    return;

  if( (a->flags & GRIB_ACCESSOR_FLAG_DUMP) == 0 &&
      (d->option_flags & GRIB_DUMP_FLAG_DUMP_OK) != 0)
    return;

  fprintf(self->dumper.out,"%s",a->name);

  if (a->flags & GRIB_ACCESSOR_FLAG_READ_ONLY) {
    fprintf(self->dumper.out," (read only)");
  }
  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0){
    fprintf(self->dumper.out," (type %s) ",a->creator->op);
  }

  aliases(d,a);

  fprintf(self->dumper.out,"\n");
}
static void dump_double(grib_dumper* d,grib_accessor* a,const char* comment)
{
    grib_dumper_debug *self = (grib_dumper_debug*)d;
    double value; size_t size = 1;
    int err = grib_unpack_double(a,&value,&size);
    int i;

    if( a->length == 0  &&
            (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
        return;

    set_begin_end(d,a);

    for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");

    if( ((a->flags & GRIB_ACCESSOR_FLAG_CAN_BE_MISSING) != 0) && grib_is_missing_internal(a))
        fprintf(self->dumper.out,"%ld-%ld %s %s = MISSING",self->begin,self->theEnd,a->creator->op, a->name);
    else
        fprintf(self->dumper.out,"%ld-%ld %s %s = %g",self->begin,self->theEnd,a->creator->op, a->name,value);
    if(comment) fprintf(self->dumper.out," [%s]",comment);
    if(err)
        fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_debug::dump_double]",err,grib_get_error_message(err));
    aliases(d,a);
    fprintf(self->dumper.out,"\n");
}
static void dump_string(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_default *self = (grib_dumper_default*)d;
  char *value=NULL;
  char *p = NULL;
  size_t size = 0;
  grib_context* c=NULL;
  int err = grib_get_string_length(a->parent->h,a->name,&size);

  c=a->parent->h->context;
  if (size==0) return;

  value=(char*)grib_context_malloc_clear(c,size);
  if (!value) {
  	grib_context_log(c,GRIB_LOG_FATAL,"unable to allocate %d bytes",(int)size);
	return;
  }

  err = grib_unpack_string(a,value,&size);
  p=value;

  if ( (a->flags & GRIB_ACCESSOR_FLAG_DUMP) == 0)
    return;

  while(*p) { if(!isprint(*p)) *p = '.'; p++; }

  print_offset(self->dumper.out,d,a);

  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# type %s \n",a->creator->op);
  }

  aliases(d,a);
  if(comment) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# %s \n",comment);
  }

  if (a->flags & GRIB_ACCESSOR_FLAG_READ_ONLY) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"#-READ ONLY- ");
  } else
    fprintf(self->dumper.out,"  ");

  if( ((a->flags & GRIB_ACCESSOR_FLAG_CAN_BE_MISSING) != 0) && grib_is_missing_internal(a) )
    fprintf(self->dumper.out,"%s = MISSING;",a->name);
  else
    fprintf(self->dumper.out,"%s = %s;",a->name,value);


  if(err) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# *** ERR=%d (%s) [grib_dumper_default::dump_string]",err,grib_get_error_message(err));
  }

  fprintf(self->dumper.out,"\n");
  grib_context_free(c,value);
}
QStringList QTextCodecPlugin::keys() const
{
    QStringList keys;
    QList<QByteArray> list = names();
    list += aliases();
    for (int i = 0; i < list.size(); ++i)
        keys += QString::fromLatin1(list.at(i));
    QList<int> mibs = mibEnums();
    for (int i = 0; i < mibs.count(); ++i)
        keys += QLatin1String("MIB: ") + QString::number(mibs.at(i));
    return keys;
}
static void dump_bits(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_default *self = (grib_dumper_default*)d;
  int i;
  long value; size_t size = 1;
  int err = grib_unpack_long(a,&value,&size);

  if ( (a->flags & GRIB_ACCESSOR_FLAG_DUMP) == 0)
    return;

  print_offset(self->dumper.out,d,a);

  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# type %s \n",a->creator->op);
  }

  aliases(d,a);
  if(comment) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# %s \n",comment);
  }

  fprintf(self->dumper.out,"  ");
  fprintf(self->dumper.out,"# flags: ");
  for(i=0;i<(a->length*8);i++) {
    if(test_bit(value,a->length*8-i-1))
      fprintf(self->dumper.out,"1");
    else
      fprintf(self->dumper.out,"0");
  }
  fprintf(self->dumper.out,"\n");

  if (a->flags & GRIB_ACCESSOR_FLAG_READ_ONLY) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"#-READ ONLY- ");
  } else
    fprintf(self->dumper.out,"  ");

  if( ((a->flags & GRIB_ACCESSOR_FLAG_CAN_BE_MISSING) != 0) && grib_is_missing_internal(a) )
    fprintf(self->dumper.out,"%s = MISSING;",a->name);
  else
    fprintf(self->dumper.out,"%s = %ld;",a->name,value);


  if(err) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# *** ERR=%d (%s) [grib_dumper_default::dump_bits]",err,grib_get_error_message(err));
  }

  fprintf(self->dumper.out,"\n");
}
Exemple #9
0
int main(void)
{
    FileMapping morf("db/morfologik");
    Reader rd(morf.data(), morf.size());
    rd.assert_u32(0x46524f4d);
    int n_words = rd.read_u32();

    Writer wr;
    wr.write_u32(0x41494c41);
    wr.write_u32(n_words);

    int alcnt = 0;

    int *v = (int *)malloc(sizeof(int) * n_words);
    memset(v, -1, sizeof(int) * n_words);

    for(int i=0; i<n_words; i++)
    {
        int t = rd.read_u32();
        assert((t & 0xffffff) == i);
        int n_bases = t>>24;

        if(n_bases > 1) {
            wr.write_u32(i);
            while(n_bases--)
                rd.read_u32();
        } else {
            int base = n_bases ? rd.read_u32() : i;
            if(v[base] == -1)
                v[base] = i;
            else
                alcnt++;
            wr.write_u32(v[base]);
        }
    }

    printf("total alias count: %d\n", alcnt);
    
    FileIO aliases("db/aliases", O_WRONLY|O_CREAT|O_TRUNC);
    aliases.write_raw(wr.buffer(), wr.tell());

    return 0;
}
static void dump_string(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_wmo *self = (grib_dumper_wmo*)d;
  size_t size=0;
  char *value=NULL;
  char *p=NULL;
  int err = grib_get_string_length(a->parent->h,a->name,&size);

  value=(char *)grib_context_malloc_clear(a->parent->h->context,size);
  if (!value) {
  	grib_context_log(a->parent->h->context,GRIB_LOG_FATAL,"unable to allocate %d bytes",(int)size);
	return;
  }
  err=grib_unpack_string(a,value,&size);
  p=value;

  if( a->length == 0  &&
      (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0) {
	grib_context_free(a->parent->h->context,value);
    return;
  }

  set_begin_end(d,a);

  while(*p) { if(!isprint(*p)) *p = '.'; p++; }

  /*for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");*/
  print_offset(self->dumper.out,self->begin,self->theEnd);
  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0)
        fprintf(self->dumper.out,"%s ",a->creator->op);

  fprintf(self->dumper.out,"%s = %s",a->name,value);

  if (err==0) print_hexadecimal(self->dumper.out,d->option_flags,a);

  /*if(comment) fprintf(self->dumper.out," [%s]",comment);*/
  if(err)
    fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_wmo::dump_string]",err,grib_get_error_message(err));
  aliases(d,a);
  fprintf(self->dumper.out,"\n");
  if (value) grib_context_free(a->parent->h->context,value);
}
Exemple #11
0
/// Write a string version of the select clause to the specified output stream.
void ibis::selectClause::print(std::ostream& out) const {
    if (!clause_.empty()) {
        out << clause_;
    }
    else {
        std::vector<const std::string*> aliases(xtms_.size(), 0);
        for (StringToInt::const_iterator it = xalias_.begin();
             it != xalias_.end(); ++ it) {
            aliases[(*it).second] = &(it->first);
        }

        for (uint32_t i = 0; i < xtms_.size(); ++ i) {
            if (i > 0)
                out << ", ";
            out << *(xtms_[i]);
            if (aliases[i] != 0)
                out << " AS " << *(aliases[i]);
        }
    }
} // ibis::selectClause::print
static void dump_bits(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_wmo *self = (grib_dumper_wmo*)d;
  int i;
  long value = 0; size_t size = 1;
  int err = grib_unpack_long(a,&value,&size);

  if( a->length == 0  &&
      (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
    return;

  set_begin_end(d,a);

  /*for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");*/
  print_offset(self->dumper.out,self->begin,self->theEnd);
  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0)
        fprintf(self->dumper.out,"%s ",a->creator->op);

  fprintf(self->dumper.out,"%s = %ld [",a->name,value);

  for(i=0;i<(a->length*8);i++) {
    if(test_bit(value,a->length*8-i-1))
      fprintf(self->dumper.out,"1");
    else
      fprintf(self->dumper.out,"0");
  }
/*
  if(comment)
    fprintf(self->dumper.out,":%s]",comment);
  else
*/
  fprintf(self->dumper.out,"]");

  if (err==0) print_hexadecimal(self->dumper.out,d->option_flags,a);

  if(err)
    fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_wmo::dump_bits]",err,grib_get_error_message(err));

  aliases(d,a);
  fprintf(self->dumper.out,"\n");
}
static void dump_string(grib_dumper* d,grib_accessor* a,const char* comment)
{
    grib_dumper_debug *self = (grib_dumper_debug*)d;
    int err=0;
    int i;
    size_t size=0;
    char *value=NULL;
    char *p=NULL ;

    err = grib_get_string_length(a->parent->h, a->name, &size);
    if ( (size < 2) && grib_is_missing_internal(a) ) {
        /* GRIB-302: transients and missing keys. Need to re-adjust the size */
        size = 10; /* big enough to hold the string "missing" */
    }

    value=(char*)grib_context_malloc_clear(a->parent->h->context,size);
    if (!value) return;
    err=grib_unpack_string(a,value,&size);

    if(err) strcpy(value,"<error>");

    p=value;

    if( a->length == 0  && (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
        return;

    set_begin_end(d,a);

    while(*p) { if(!isprint(*p)) *p = '.'; p++; }

    for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
    fprintf(self->dumper.out,"%ld-%ld %s %s = %s",self->begin,self->theEnd,a->creator->op, a->name,value);

    if(comment) fprintf(self->dumper.out," [%s]",comment);
    if(err)
        fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_debug::dump_string]",err,grib_get_error_message(err));
    aliases(d,a);
    fprintf(self->dumper.out,"\n");

    if (value) grib_context_free(a->parent->h->context,value);
}
//#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@>
int chkaliases(std::vector<std::string> & argv)
{
 std::string cmdprefix = "/var/smoothwall";
 std::string aliasfile = cmdprefix + "/portfw/aliases";
 std::string args      = "RED";
 int error             = 0;
 ConfigCSV   aliases(aliasfile);

 error += readether(argv, args);
 args   = "GREEN";
 error += readether(argv, args);
 args   = "ORANGE";
 error += readether(argv, args);
 args   = "PURPLE";
 error += readether(argv, args);

 for (int line = aliases.first(); line == 0; line = aliases.next())
 {
  if (aliases[0].find_first_of(":") != std::string::npos)
  {
   std::string larg;

   // Stepping through the array with an index might be simpler and quicker, 
   // but explicits allow us to replace selected values easily in the future
   
   larg  = aliases[0] + ",";
   larg += aliases[1] + ",";
   larg += aliases[2] + ",";
   larg += aliases[3] + ",";
   larg += aliases[4] + ",";
   larg += aliases[5] + ",";
   larg += aliases[6] + ",";
   larg += aliases[7] + ",";
   larg += aliases[8] + ",";
   larg += aliases[9] + "\n";
   argv.push_back(larg);
  }
 }
 return 0;
}
Exemple #15
0
QByteArray TableGenerator::readLocaleAliases(const QByteArray &locale)
{
    QFile aliases(systemComposeDir() + QLatin1String("/locale.alias"));
    QByteArray fullLocaleName;
    if (aliases.open(QIODevice::ReadOnly)) {
        while (!aliases.atEnd()) {
            char l[1024];
            int read = aliases.readLine(l, sizeof(l));
            char *line = l;
            if (read && ((*line >= 'a' && *line <= 'z') ||
                         (*line >= 'A' && *line <= 'Z'))) {
                const char *alias = line;
                while (*line && *line != ':' && *line != ' ' && *line != '\t')
                    ++line;
                if (!*line)
                    continue;
                *line = 0;
                if (locale.size() == (line - alias)
                        && !strncasecmp(alias, locale.constData(), line - alias)) {
                    // found a match for alias, read the real locale name
                    ++line;
                    while (*line && (*line == ' ' || *line == '\t'))
                        ++line;
                    const char *fullName = line;
                    while (*line && *line != ' ' && *line != '\t' && *line != '\n')
                        ++line;
                    *line = 0;
                    fullLocaleName = fullName;
#ifdef DEBUG_GENERATOR
                    qDebug() << "Alias for: " << alias << "is: " << fullLocaleName;
                    break;
#endif
                }
            }
        }
        aliases.close();
    }
    return fullLocaleName;
}
TEST_F(VirtualTableTests, test_tableplugin_aliases) {
  auto table = std::make_shared<aliasesTablePlugin>();
  std::vector<std::string> expected_aliases = {"aliases1", "aliases2"};
  EXPECT_EQ(expected_aliases, table->aliases());

  PluginResponse response;
  PluginRequest request = {{"action", "columns"}};
  EXPECT_TRUE(table->call(request, response).ok());

  auto default_option = static_cast<size_t>(ColumnOptions::DEFAULT);
  PluginResponse expected_response = {
      {{"id", "column"},
       {"name", "username"},
       {"type", "TEXT"},
       {"op", INTEGER(default_option)}},
      {{"id", "column"},
       {"name", "name"},
       {"type", "TEXT"},
       {"op", INTEGER(default_option)}},
      {{"alias", "aliases1"}, {"id", "alias"}},
      {{"alias", "aliases2"}, {"id", "alias"}},
      {{"id", "columnAlias"}, {"name", "name1"}, {"target", "name"}},
      {{"id", "columnAlias"}, {"name", "name2"}, {"target", "name"}},
      {{"id", "columnAlias"}, {"name", "user_name"}, {"target", "username"}},
      {{"attributes", "0"}, {"id", "attributes"}},
  };
  EXPECT_EQ(response, expected_response);

  // Compare the expected table definitions.
  std::string expected_statement =
      "(`username` TEXT, `name` TEXT, `name1` TEXT HIDDEN, `name2` TEXT HIDDEN,"
      " `user_name` TEXT HIDDEN)";
  EXPECT_EQ(expected_statement, columnDefinition(response, true));
  expected_statement = "(`username` TEXT, `name` TEXT)";
  EXPECT_EQ(expected_statement, columnDefinition(response, false));
}
Exemple #17
0
void
SMTPMessage::ReplaceAliases
	(
	JPtrArray<JString>& names
	)
{
	JPtrArray<JString> aliases(JPtrArrayT::kForgetAll);
	aliases.SetCompareFunction(JCompareStringsCaseSensitive);
	JSize i = 1;
	while (i <= names.GetElementCount())
		{
		JString& name = *(names.NthElement(i));
		JString alias;
		JString fcc;
		if (GGetAddressBookMgr()->NameIsAlias(name, alias, fcc))
			{
			JIndex findex;
			if (!aliases.SearchSorted(&name, JOrderedSetT::kAnyMatch, &findex))
				{
				GParseNameList(alias, names);
				aliases.InsertSorted(names.NthElement(i));
				names.RemoveElement(i);
				}
			else
				{
				names.DeleteElement(i);
				}
//			GParseNameList(fcc, names);
			}
		else
			{
			i++;
			}
		}
	aliases.DeleteAll();
}
//#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@>
int ifaliasup(std::vector<std::string> & parameters, std::string & response)
{
 int error = 0;

 error = wrtaliases (response);
 if (error) return errrpt(response);

 std::vector<std::string> argv;

 std::string cmdprefix = "/var/smoothwall";
 std::string varfile     = cmdprefix + "/portfw/snort.var";
 std::string localipfile = "/var/smoothwall/red/local-ipaddress";
 std::string aliasfile   = cmdprefix + "/portfw/aliases";
 ConfigCSV   aliases(aliasfile);
 ConfigSTR   localip(localipfile);
 std::string::size_type n;
 char home_net[5000] = "";
 char * hnptr = home_net;
 FILE * varhandle;

 if (localip.str() == "")
 {
  response = "Abort, could not open red local IP file (" + localipfile + ")";
  return errrpt (response);
 }
 if (localip.str().find_first_not_of(IP_NUMBERS) != std::string::npos)
 {
  response = "Abort, bad local IP: " + localip.str();
  return errrpt (response);
 }
 std::string homenet = "var HOME_NET [" + localip.str();

 response = "Bringing alias interfaces up";
 error = errrpt(response);
 hnptr += sprintf(hnptr, "%s,", homenet.c_str());

 for (int line = aliases.first(); line == 0; line = aliases.next())
 {
  std::string f_color   = aliases[0];
  std::string f_ifalias = aliases[1];
  std::string f_ip      = aliases[3];
  std::string f_net     = aliases[4];
  std::string f_bcst    = aliases[5];

  if ((n = f_ifalias.find_first_of(":")) != std::string::npos && aliases[7] == "on")
  {
   // Add the alias to HOME_NET if it is enabled and we have room (with
   // 255 aliases maximum should be less than 4878 plus 28 chars at finish)

   if ((n = f_color.find("RED")) != std::string::npos)
    hnptr += sprintf(hnptr, "%s,", f_ip.c_str());


   errrpt("bringing up alias (" + f_ifalias + ")");

   if (f_ifalias.find_first_of("p") != std::string::npos)

    error += simplesecuresysteml("/sbin/ifconfig",f_ifalias.c_str(),f_ip.c_str(),
     "netmask",f_net.c_str(),"up",NULL);

   else

    error += simplesecuresysteml("/sbin/ifconfig",f_ifalias.c_str(),f_ip.c_str(),
     "netmask",f_net.c_str(),"broadcast",f_bcst.c_str(),"up",NULL);
  }
 }
 // backup one space to overwrite the trailing comma

 hnptr += sprintf(--hnptr, "]\n");

 if (!(varhandle = fopen(varfile.c_str(), "w")))
 {
  response = "Abort, could not create or open (" + varfile + ") file";
  return errrpt(response);
 }
 fputs((char*) home_net, varhandle);
 fclose(varhandle);

 errrpt("NOTE:  snort should be restarted manually to update its HOME_NET value");
 errrpt("NOTE:  /etc/snort.conf can be further customized for each scenario");

 response = "Successfully brought up alias interfaces.";
 if (error) response = "Abort while bringing up alias interfaces";

 return errrpt(response);
}
//#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@>
int set_xtaccess(std::vector<std::string> & parameters, std::string & response)
{
 std::string ifacefile    = "/var/smoothwall/red/iface";
 std::string cmdprefix    = "/var/smoothwall";
 std::string configfile   = cmdprefix + "/xtaccess/config";
 std::string aliasfile    = cmdprefix + "/portfw/aliases";

 ConfigSTR ifacef(ifacefile);
 ConfigCSV config(configfile);
 ConfigCSV aliases(aliasfile);

 std::vector<std::string> ipb;
 std::string red_ip            = "";
 std::string iface             = ifacef.str();
 std::string destination       = "";
 std::string dport_out         = "";
 int error                     = 0;

 // preset the response to a success, changed only on error, always return zero

 response = "External Access Rules set";

 if (ifacef.str() == "")
 {
  response = "Abort, could not open red local interface file (" + ifacefile + ")";
  return errrpt (response);
 }
 if (iface.find_first_not_of(INTERFACE) != std::string::npos)
 {
  response = "Abort, bad interface: " + iface;
  return errrpt (response);
 }

 rmdupes(ipb, "iptables -t filter -F xtaccess");
 rmdupes(ipb, "iptables -t nat -F portfw_pre");

 //=============================================================================>
 // Any destination IP that is local and not forwarded goes to us through INPUT

 for (int line = config.first(); line == 0; line = config.next())
 {
  const std::string & alias    = config[0];
  const std::string & protocol = config[1];
  const std::string & remip    = config[2];
  const std::string & locport  = config[3];
  const std::string & enabled  = config[4];

  if (protocol.find_first_not_of(NUMBERS) != std::string::npos)
  {
   response = "Abort, bad protocol: " + protocol;
   return errrpt (response);
  }
  if (remip.find_first_not_of(IP_NUMBERS) != std::string::npos)
  {
   response = "Abort, bad remote IP: " + remip;
   return errrpt (response);
  }
  if (locport.find_first_not_of(NUMBERS_COLON) != std::string::npos)
  {
   response = "Abort, bad port: " + locport;
   return errrpt (response);
  }
  dport_out = "";
  if (locport !=  "0" && locport !=  "") dport_out = " --dport " + locport;

  red_ip = "";
  for (int aline = aliases.first(); aline == 0; aline = aliases.next())

  // we need to find the alias IP of the red interface
  {
   const std::string & f_ifalias = aliases[1];
   const std::string & f_ipaddress = aliases[3];

   if (alias == f_ifalias)
   {
    red_ip = f_ipaddress;
    break;
   }
  }
  if (red_ip == "")
  {
   response = "Abort, could not find an alias match in (" + configfile + ") with (" +
    aliasfile + ") for an IP in the XTAccess rule";
   return errrpt(response);
  }
  destination = " -d " + red_ip;

  //============================================================================>
  // This only creates the rules if they are present and enabled, the alias
  // may be disabled which would make the rule ineffective since the IP would
  // not be present in ifconfig

  if (enabled == "on")
  {
   rmdupes(ipb, "iptables -t filter -A xtaccess -i " + iface + " -d " + red_ip + 
    " -p " + protocol + dport_out + " -s " + remip + " -j ACCEPT");
  }
 }

 error = ipbatch(ipb);

 if (error) response = "ipbatch failure";

 return errrpt (response);
}
static void dump_values(grib_dumper* d,grib_accessor* a)
{
  grib_dumper_default *self = (grib_dumper_default*)d;
  int k,err =0;
  int more = 0;
  double*  buf = NULL;
  size_t size=0;
  long count=0;

  if ( (a->flags & GRIB_ACCESSOR_FLAG_DUMP) == 0)
    return;

  grib_value_count(a,&count);
  size=count;
  if(size == 1){
    dump_double(d,a,NULL);
    return ;
  }
  buf = (double*)grib_context_malloc(d->handle->context,size * sizeof(double));

   print_offset(self->dumper.out,d,a);

  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# type %s \n",a->creator->op);
  }

  aliases(d,a);

  if (a->flags & GRIB_ACCESSOR_FLAG_READ_ONLY) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"#-READ ONLY- ");
  } else
    fprintf(self->dumper.out,"  ");

  fprintf(self->dumper.out,"%s(%ld) = ",a->name,(long)size);
  aliases(d,a);
  fprintf(self->dumper.out," {");

  if(!buf)
  {
    if(size == 0)
      fprintf(self->dumper.out,"}\n");
    else
      fprintf(self->dumper.out," *** ERR cannot malloc(%ld) }\n",(long)size);
    return;
  }

  fprintf(self->dumper.out,"\n");

  err =  grib_unpack_double(a,buf,&size);

  if(err){
    grib_context_free(d->handle->context,buf);
    fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_default::dump_values]\n}",err,grib_get_error_message(err));
    return ;
  }

  if(!(d->option_flags & GRIB_DUMP_FLAG_ALL_DATA) && size > 100) {
    more = size - 100;
    size = 100;
  }

  k = 0;
  while(k < size)  {
#if 1
    int j;
    fprintf(self->dumper.out,"  ");
    for(j = 0; j < 5 && k < size; j++, k++)  {
      fprintf(self->dumper.out,"%.10e",buf[k]);
      if(k != size-1)
        fprintf(self->dumper.out,", ");
    }
    fprintf(self->dumper.out,"\n");
#else

    fprintf(self->dumper.out,"%d %g\n",k,buf[k]);

#endif

  }  if(more)  {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"... %d more values\n",more);
  }

  fprintf(self->dumper.out,"  ");
  fprintf(self->dumper.out,"} \n");
  grib_context_free(d->handle->context,buf);
}
static void dump_bytes(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_default *self = (grib_dumper_default*)d;

  if ( (a->flags & GRIB_ACCESSOR_FLAG_DUMP) == 0)
    return;

  fprintf(self->dumper.out,"  %s = <%ld byte%s>;\n", a->name, a->length, a->length>1?"s":"");

#if 0
  grib_dumper_default *self = (grib_dumper_default*)d;
  int i,k,err =0;
  int more = 0;
  size_t size = a->length;
  unsigned char* buf = grib_context_malloc(d->handle->context,size);

  if ( (a->flags & GRIB_ACCESSOR_FLAG_DUMP) == 0)
    return;


  if (a->flags & GRIB_ACCESSOR_FLAG_READ_ONLY)
    fprintf(self->dumper.out,"-READ ONLY- ");

  /*for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");*/
  /*print_offset(self->dumper.out,self->begin,self->theEnd);*/
  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0)
        fprintf(self->dumper.out,"%s ",a->creator->op);

  fprintf(self->dumper.out,"%s = %ld",a->name,a->length);
  aliases(d,a);
  fprintf(self->dumper.out," {");

  if(!buf)
  {
    if(size == 0)
      fprintf(self->dumper.out,"}\n");
    else
      fprintf(self->dumper.out," *** ERR cannot malloc(%ld) }\n",(long)size);
    return;
  }

  fprintf(self->dumper.out,"\n");

  err = grib_unpack_bytes(a,buf,&size);
  if(err){
    grib_context_free(d->handle->context,buf);
    fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_default::dump_bytes]\n}",err,grib_get_error_message(err));
    return ;
  }

  if(size > 100) {
    more = size - 100;
    size = 100;
  }

  k = 0;
  /* if(size > 100) size = 100;  */
  while(k < size)
  {
    int j;
    for(i = 0; i < d->depth + 3 ; i++) fprintf(self->dumper.out," ");
    for(j = 0; j < 16 && k < size; j++, k++)
    {
      fprintf(self->dumper.out,"%02x",buf[k]);
      if(k != size-1)
        fprintf(self->dumper.out,", ");
    }
    fprintf(self->dumper.out,"\n");
  }

  if(more)
  {
    for(i = 0; i < d->depth + 3 ; i++) fprintf(self->dumper.out," ");
    fprintf(self->dumper.out,"... %d more values\n",more);
  }

  for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
  fprintf(self->dumper.out,"} # %s %s \n",a->creator->op, a->name);
  grib_context_free(d->handle->context,buf);
#endif
}
//#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@#@>
int set_portfw(std::vector<std::string> & parameters, std::string & response)
{
 int error = 0;
 std::string::size_type n;
 std::string::size_type p;
 std::vector<std::string>ipb;

 std::string localipfile = "/var/smoothwall/red/local-ipaddress";
 std::string ifacefile = "/var/smoothwall/red/iface";
 std::string cmdprefix = "/var/smoothwall";
 std::string configfile = cmdprefix + "/portfw/config";
 std::string aliasfile = cmdprefix + "/portfw/aliases";
 std::string sncheckfile = cmdprefix + "/portfw/subcheck";
 ConfigSTR   localip(localipfile);
 ConfigSTR   red_iface(ifacefile);
 ConfigCSV   fwdconf(configfile);
 ConfigCSV   aliases(aliasfile);
 ConfigVAR   subnetcheck(sncheckfile);

 std::string greencheck  = subnetcheck["GREEN"];
 std::string purplecheck = subnetcheck["PURPLE"];
 std::string orangecheck = subnetcheck["ORANGE"];

 // preset the response to a success, changed only on error, always return zero

 response = "Port forwarding rules set";

 if (localip.str() == "")
 {
  response = "Abort, could not open red local IP file (" + localipfile + ")";
  return errrpt (response);
 }
 if (localip.str().find_first_not_of(IP_NUMBERS) != std::string::npos)
 {
  response = "Abort, bad local IP: " + localip.str();
  return errrpt (response);
 }
 if (red_iface.str() == "")
 {
  response = "Abort, could not open red interface file (" + ifacefile + ")";
  return errrpt (response);
 }
 if (red_iface.str().find_first_not_of(INTERFACE) != std::string::npos)
 {
  response = "Abort, bad red interface specifier: " + red_iface.str();
  return errrpt (response);
 }
 std::string red_if      = red_iface.str();
 std::string fwdest_out  = "";
 std::string dest_out    = "";
 std::string ifc_in_out  = "";
 std::string ifc_out_out = "";
 std::string fwdportdest = "";
 std::string srcipmac_out= "";
 std::string dport_out   = "";
 std::string fwdport_out = "";
 std::string prot_out    = "";
 std::string dnat_out    = "";
 std::string tgt_out     = "";
 std::string in_dest     = "";
 bool bounce_type        = false;
 bool forwarding         = false;
 bool translating        = false;
 bool negated_source     = false;
 std::string temp_source = "";
 std::string internal_if = "";
 std::string conn_green  = "0xD0000000";
 std::string conn_purple = "0xE0000000";
 std::string conn_orange = "0xF0000000";
 std::string green_if    = "";
 std::string green_ifip  = "";
 std::string orange_if   = "";
 std::string orange_ifip = "";
 std::string purple_if   = "";
 std::string purple_ifip = "";
 /*
 The mark_mask value can only be used if we switch to CONNMARK tracking
 std::string mark_mask   = "0xFFF00000/";
 //=============================================================================>
 // We use the upper three nybbles of the available CMARK sequence numbers for
 // identifying the CMARKs associated with Full Firewall Control.  Any other
 // applications using CMARKs must be aware of this, always using a CMARK mask
 // that is not greater than 0x000FFFFF.  Available only if we use CONNMARK
 //=============================================================================>
 */
 rmdupes (ipb, "iptables -t filter -F portfwf");  // filtering rules  (moved stk)
 rmdupes (ipb, "iptables -t nat -F portfw");      // DNAT forwarding        (stk)
 rmdupes (ipb, "iptables -t mangle -F portfwb");  // MARK bounce & OMask    (stk)
 rmdupes (ipb, "iptables -t nat -F portfw_post"); // SNAT bounce & OMask    (add)
 rmdupes (ipb, "iptables -t filter -F portfwi");  // filter rules for INPUT (add)
 rmdupes (ipb, "iptables -t filter -F subnetchk");// filter rules FOR/INPUT (add)

 // ============================================================================>
 // we allow masking outbound to a red alias by having an association in
 // the alias file between a single internal IP and the alias interface
 // ============================================================================>
 // Here we find the internal interfaces for possible bouncing and create the
 // rules for masking outbounds to alias interfaces as we read the alias file

 unsigned int mark_seq = 0x800;

 for (int line = aliases.first(); line == 0; line = aliases.next())
 {
  char conn_mark[15] = "";

  const std::string & f_ifcolor   = aliases[0];
  const std::string & f_ifalias   = aliases[1];
  const std::string & f_realif    = aliases[2];
  const std::string & f_ipaddress = aliases[3];
  const std::string & f_addmask   = aliases[4];
  const std::string & f_enabled   = aliases[7];
  const std::string & f_mask2add  = aliases[9];
  std::string scprefixf = "iptables -t filter -A";
  std::string sclogpre = " -j LOG --log-prefix ..FFC..not.";
  std::string sclogpost = ".subnet..";
  std::string sclogrej = " -j REJECT";

  //  Allow DHCP to bypass subnet checking
  rmdupes (ipb, scprefixf + " subnetchk -p udp --dport 67 -j RETURN");
  rmdupes (ipb, scprefixf + " portfwi -j subnetchk");
  rmdupes (ipb, scprefixf + " portfwf -j subnetchk");

  //============================================================================>
  //  log and reject any packets with a source that is not in the correct
  //  subnet for the interface that received them
  //===>>  To disable:  set "(GREEN|PURPLE|ORANGE)=off" in the "sncheckfile"

  if (f_ifcolor == "GREEN")
  {
   green_if = f_realif;
   green_ifip = f_ipaddress;
   if (greencheck != "off")
   {
    char cidr[5] = "";
    sprintf((char*) cidr, "/%d", snet2cidr(f_addmask));

    std::string scpostfixl = (" -i " + green_if + " ! -s " + green_ifip + cidr +
     sclogpre + f_ifcolor + sclogpost);
    std::string scpostfixr = (" -i " + green_if + " ! -s " + green_ifip + cidr +
     sclogrej);

    rmdupes (ipb, scprefixf + " subnetchk" + scpostfixl);
    rmdupes (ipb, scprefixf + " subnetchk" + scpostfixr);
   }
  }
  if (f_ifcolor == "ORANGE")
  {
   orange_if = f_realif;
   orange_ifip = f_ipaddress;
   if (orangecheck != "off")
   {
    char cidr[5] = "";
    sprintf((char*) cidr, "/%d", snet2cidr(f_addmask));

    std::string scpostfixl = (" -i " + orange_if + " ! -s " + orange_ifip + cidr +
     sclogpre + f_ifcolor + sclogpost);
    std::string scpostfixr = (" -i " + orange_if + " ! -s " + orange_ifip + cidr +
     sclogrej);

    rmdupes (ipb, scprefixf + " subnetchk" + scpostfixl);
    rmdupes (ipb, scprefixf + " subnetchk" + scpostfixr);
   }
  }
  if (f_ifcolor == "PURPLE")
  {
   purple_if = f_realif;
   purple_ifip = f_ipaddress;
   if (purplecheck != "off")
   {
    char cidr[5] = "";
    sprintf((char*) cidr, "/%d", snet2cidr(f_addmask));

    std::string scpostfixl = (" -i " + purple_if + " ! -s " + purple_ifip + cidr +
     sclogpre + f_ifcolor + sclogpost);
    std::string scpostfixr = (" -i " + purple_if + " ! -s " + purple_ifip + cidr +
     sclogrej);

    rmdupes (ipb, scprefixf + " subnetchk" + scpostfixl);
    rmdupes (ipb, scprefixf + " subnetchk" + scpostfixr);
   }
  }
  if (f_mask2add != "" && f_mask2add.find_first_of("/") == std::string::npos &&
   f_ifalias.find_first_of(":") != std::string::npos && f_enabled == "on")

  //============================================================================>
  // Make sure we have an alias interface and a single IP to mask
  {
   sprintf((char*) conn_mark, "%#010x", (++mark_seq) * 0x100000);
   conn_mark[10] = 0;

   rmdupes (ipb, "iptables -t mangle -A portfwb -s " + f_mask2add +
    " -j MARK --set-mark " + conn_mark);

   rmdupes (ipb, "iptables -t nat -A portfw_post -o " + red_if + " -s " + f_mask2add +
    " -m mark --mark " + conn_mark + " -j SNAT --to-source " + f_ipaddress);
  }
  if (mark_seq > 0x8FF)
  {
   response = "Abort, more than 255 aliases not supported, reduce alias count.";
   return errrpt (response);
  }
  if (error)
  {
   response = "Abort in alias file for " + f_ifalias + " interface.";
   return errrpt (response);
  }
 }//     <<== End of reading "aliasfile"

 //=============================================================================>
 // This is to clean up any previously entered jumps around the proxies, then
 // we set the jumps around the proxies for any outbound masking to an alias

 std::string proxy_jmph = "iptables -t nat ";
 std::string proxy_jmpt = " -m mark --mark 0x80000000/0x80000000 -j RETURN";

 // the match mark mask does not correctly mask for some reason
 // the position of flag and mask might be reversed

 if (chkproxy())
 {
  rmdupes (ipb, proxy_jmph + "-D jmpim" + proxy_jmpt);
  rmdupes (ipb, proxy_jmph + "-D jmpp3scan" + proxy_jmpt);
  rmdupes (ipb, proxy_jmph + "-D jmpsip" + proxy_jmpt);
  rmdupes (ipb, proxy_jmph + "-D jmpsquid" + proxy_jmpt);
 }

 if (mark_seq > 0x800)
 {
  rmdupes (ipb, proxy_jmph + "-I jmpim" + proxy_jmpt);
  rmdupes (ipb, proxy_jmph + "-I jmpp3scan" + proxy_jmpt);
  rmdupes (ipb, proxy_jmph + "-I jmpsip" + proxy_jmpt);
  rmdupes (ipb, proxy_jmph + "-I jmpsquid" + proxy_jmpt);
 }
 //=============================================================================>
 // Read the rules, in sequence from "configfile" and build

 for (int line = fwdconf.first(); line == 0; line = fwdconf.next())
 {
  const std::string & f_input   = fwdconf[1];
  const std::string & f_source  = fwdconf[2];
  const std::string & f_dport   = fwdconf[3];
  const std::string & f_output  = fwdconf[4];
  const std::string & f_fwdest  = fwdconf[5];
  const std::string & f_fwdport = fwdconf[6];
  const std::string & f_proto   = fwdconf[7];
  const std::string & f_action  = fwdconf[8];
  const std::string & f_enabled = fwdconf[9];

  if (f_input.find_first_not_of(INTERFACE) != std::string::npos &&
   (f_input.find_first_not_of(INTERFACE_ALIAS) != std::string::npos) &&
    f_input != "any")
  {
   response = "Abort, bad input interface: (" + f_input + ") rule number " +
    fwdconf[0];
   return errrpt (response);
  }
  if (f_output.find_first_not_of(INTERFACE) != std::string::npos &&
   (f_output.find_first_not_of(INTERFACE_ALIAS) != std::string::npos) &&
    f_output != "any")
  {
   response = "Abort, bad output interface: " + f_output + " rule number " +
    fwdconf[0];
   return errrpt (response);
  }
  if (f_proto.find_first_not_of(NUMBERS) != std::string::npos &&
   f_proto != "all")
  {
   response = "Abort, bad protocol: (" + f_proto + ") rule number " + fwdconf[0];
   return errrpt (response);
  }
  if (f_dport.find_first_not_of(NUMBERS_COLON) != std::string::npos)
  {
   response = "Abort, bad initial destination port: (" + f_dport +
    ") rule number " + fwdconf[0];
   return errrpt (response);
  }
  // First operation is to remove negation, if present

  negated_source = false;
  if ((p = f_source.find_first_of("! ")) != std::string::npos &&
   (n = f_source.find_first_not_of("! ")) != std::string::npos)
  {
     negated_source = true;
     temp_source = f_source;
     temp_source = temp_source.erase(p, n - p);
  }
  else temp_source = f_source;

  if (temp_source.find_first_not_of(IP_NUMBERS) != std::string::npos &&
   temp_source.find_first_not_of(MAC_HEX) != std::string::npos)
  {
   response = "Abort, bad source IP or MAC: (" + f_source + ") rule number " +
    fwdconf[0];
   return errrpt (response);
  }
  if (f_fwdest.find_first_not_of(IP_NUMBERS) != std::string::npos)
  {
   response = "Abort, bad new destination IP: (" + f_fwdest + ") rule number " +
    fwdconf[0];
   return errrpt (response);
  }
  if (f_fwdport.find_first_not_of(NUMBERS_COLON) != std::string::npos)
  {
   response = "Abort, bad new destination port: (" + f_fwdport +
    ") rule number " + fwdconf[0];
   return errrpt (response);
  }
  if (f_action != "REJECT" && f_action != "RETURN" && f_action != "ACCEPT" &&
   f_action  != "DROP"   &&	f_action != "LOG")
  {
   response = "Abort, bad action: (" + f_action + ") rule number " + fwdconf[0];
   return errrpt (response);
  }
  if (f_enabled == "on")
  {
   // ==========================================================================>
   // we allow red bouncing by specifying that it comes from * interface
   // because bouncing requires that DNAT and SNAT be done on the packets
   // specifying an interface on bounces is not possible, the source is the
   // destination for bounces, if the source must be limited on bounces,
   // use an IP limitation
   // ==========================================================================>
   // Here we create the source strings, or leave null if unused

   forwarding = false;
   in_dest = "";
   if (f_input.find(red_if) != std::string::npos)
   {
    if (f_proto == "1" || f_proto == "6" || f_proto == "17" ||
     f_proto == "47" || f_proto == "50" || f_proto == "51")
    {
     forwarding = true;

     // ICMP:1 TCP:6 UDP:17 GRE:47 ESP:50 AH:51   <---Forwarded protocols

     in_dest = localip.str();

     // default IP for the actual red interface, changed only for aliases
     // If it is an alias

     if (f_input.find(":") != std::string::npos)
     {
      for (int line = aliases.first(); line == 0; line = aliases.next())

      // forwarding from the red interface we need to find the IP
      {
       const std::string & f_ifalias = aliases[1];
       const std::string & f_ipaddress = aliases[3];

       if ((f_input == f_ifalias  && aliases[7] == "on"))
        in_dest = f_ipaddress;
      }
     }
     if (in_dest.find_first_not_of(IP_NUMBERS) != std::string::npos &&
      in_dest.find_first_of("/") != std::string::npos)
     {
      response = "Abort, could not find match for interface (" + f_input +
       ") and IP (" + in_dest +
        ") to construct a forwarding rule in rule number " + fwdconf[0];
      return errrpt (response);
     }
    }  //  <<== End of protocol
   }  //  <<== End of Red IF

   ifc_in_out = "";
   if (f_input != "any" && ! forwarding)

   // If it is not "any" and not being forwarded set the input interface
   {
    ifc_in_out = f_input;

    // If it is an alias interface, truncate the string starting with the colon

    if ((n = ifc_in_out.find_first_of(":")) != std::string::npos)
     ifc_in_out.erase(n, 4);

    ifc_in_out = " -i " + ifc_in_out;
   }
   ifc_out_out = "";
   if (f_output != "any" && f_output != "")
   {
    ifc_out_out = f_output;

    if ((n = ifc_out_out.find_first_of(":")) != std::string::npos)
     ifc_out_out.erase(n, 4);

    ifc_out_out = " -o " + ifc_out_out;
   }
   prot_out = "";
   if (f_proto != "all" && f_proto != "") prot_out = " -p " + f_proto;

   dest_out = "";
   if (in_dest != "") dest_out = " -d " + in_dest;

   dport_out = "";
   if (f_dport !=  "0" && f_dport !=  "") dport_out = " --dport " + f_dport;

   translating = false;
   fwdport_out = "";
   fwdportdest = "";
   if (f_fwdport !=  "0" && f_fwdport !=  "")
   {
    translating = true;
    fwdport_out = " --dport " + f_fwdport;
    fwdportdest = f_fwdport;

    if ((n = fwdportdest.find_first_of(":")) != std::string::npos)
     fwdportdest.replace(n, 1, "-");

    fwdportdest = ":" + fwdportdest;
   }

   fwdest_out = "";
   dnat_out = "";
   if (translating || forwarding)
   {
    if (f_fwdest != "" &&
      f_fwdest.find_first_of("/") == std::string::npos)

    // an IP is being forwarded, but we must have a destination IP to
    // forward to for DNAT to be sensible
    {
     fwdest_out = " -d " + f_fwdest;
     dnat_out = " -j DNAT --to-destination " + f_fwdest + fwdportdest;
    }
    // If we expected to build a DNAT rule and failed, the IP is not singular

    if (dnat_out == "")
    {
     response = "Abort, bad new destination IP (" + f_fwdest +
      "), must be single IP in rule number " + fwdconf[0];
     return errrpt (response);
    }
    // translation requires the same IP in the DNAT initial destination

    if (! forwarding) dest_out = fwdest_out;
   }
   srcipmac_out = "";
   if (temp_source.find_first_not_of(IP_NUMBERS) == std::string::npos)
   {
    srcipmac_out = " -s " + temp_source;
   }
   if (temp_source.find_first_not_of(MAC_HEX) == std::string::npos)
   {
    srcipmac_out = " -m mac --mac-source " + temp_source;
   }
    // must be a space between "!" and the descriptor
    if (negated_source) srcipmac_out = " ! " + srcipmac_out;

   tgt_out = " -j " + f_action;
   if (f_action == "LOG") tgt_out = " -j LOG --log-prefix ..FFC..";

   // if we aren't going to DNAT we still need some information in portfwf

   if (! translating && dport_out != "") fwdport_out = dport_out;

   if (dnat_out == "" && f_fwdest != "") fwdest_out = " -d " + f_fwdest;

   // ==========================================================================>
   // Here we get down to the business of creating the rules from the strings

   if (forwarding || translating) rmdupes (ipb, "iptables -t nat -A portfw " +
    ifc_in_out + prot_out + srcipmac_out + dest_out + dport_out + dnat_out);

   rmdupes (ipb, "iptables -t filter -A portfwf -m state --state NEW" +
    ifc_out_out + prot_out + srcipmac_out + fwdest_out +
     fwdport_out + tgt_out);

   // In the INPUT chain we should not ACCEPT since EXTACCESS should be the
   // source for that type of rule, and only process rules that are not
   // forwarding or translating rules, meaning no specific output interface

   if (tgt_out == " -j ACCEPT") tgt_out = " -j RETURN";

   // Note: If the destination interface is specified then we don't create
   // a rule.  This allows the proxies to bypass a block rule for outbounds
   // which may be blocked by an additional specific rule with the Any
   // interface specified.  Another option explored was to skip only ACCEPT
   // rules, but that has limited usability as well.

   if (ifc_out_out == "")
    rmdupes (ipb, "iptables -t filter -A portfwi -m state --state NEW" +
     ifc_in_out + prot_out + srcipmac_out + dport_out + tgt_out);

   // ==========================================================================>
   // Here we create rules for bouncing if the input interface is null and
   // there has been a DNAT for the red interface, we skip translating DNAT

   if (forwarding)
   {
    std::string forward_pre = "iptables -t mangle -A portfwb -i ";
    std::string forward_post = " -j MARK --set-mark ";

    if (green_if  != "") rmdupes (ipb, forward_pre + green_if  + dest_out +
     forward_post +  conn_green);

    if (purple_if != "") rmdupes (ipb, forward_pre + purple_if + dest_out +
     forward_post + conn_purple);

    if (orange_if != "") rmdupes (ipb, forward_pre + orange_if + dest_out +
     forward_post + conn_orange);

    bounce_type = true;
   }

  }//   <<==== End of enabled

 }//   <<==== End of reading portfw/config file

 //=============================================================================>
 // The rules have been created, now we need to allow bounces, if we are doing
 // any portforwarding that allows bouncing

 if (bounce_type)
 {
  // We only need to SNAT those packets that came in the same interface that
  // they are going out on to ensure the return path is through the interface

  std::string pfw_post_pre = "iptables -t nat -A portfw_post -m mark --mark ";
  std::string pfw_post_post = " -j SNAT --to-source ";

  if (green_if != "")
   rmdupes (ipb, pfw_post_pre + conn_green  + " -o " + green_if  + pfw_post_post +
    green_ifip);

  if (purple_if != "")
   rmdupes (ipb, pfw_post_pre + conn_purple + " -o " + purple_if + pfw_post_post +
    purple_ifip);

  if (orange_if != "")
   rmdupes (ipb, pfw_post_pre + conn_orange + " -o " + orange_if + pfw_post_post +
    orange_ifip);
 }
 //=============================================================================>
 // Pass the built up vector of strings to ipbatch to build IPTables entries

 error = ipbatch(ipb);

 if (error) response = "Abort flushing rules to IPTables";
 return errrpt (response);
}
static void dump_long(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_default *self = (grib_dumper_default*)d;
  long value; size_t size = 1;
  long *values=NULL;
  int err = 0;
  int i;
  long count=0;

  grib_value_count(a,&count);
  size=count;

  if ( (a->flags & GRIB_ACCESSOR_FLAG_DUMP) == 0)
    return;

  print_offset(self->dumper.out,d,a);

  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0){
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# type %s \n",a->creator->op);
  }

  if (size>1) {
    values=(long *)grib_context_malloc_clear(a->parent->h->context,sizeof(long)*size);
    err=grib_unpack_long(a,values,&size);
  } else {
    err=grib_unpack_long(a,&value,&size);
  }

  aliases(d,a);
  if(comment) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# %s \n",comment);
  }

  if (a->flags & GRIB_ACCESSOR_FLAG_READ_ONLY) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"#-READ ONLY- ");
  } else
    fprintf(self->dumper.out,"  ");

  if (size>1) {
    int cols=19;
    int count=0;
    fprintf(self->dumper.out,"%s = { \t",a->name);
    for (i=0;i<size;i++) {
        if (count>cols) {fprintf(self->dumper.out,"\n\t\t\t\t");count=0;}
        fprintf(self->dumper.out,"%ld ",values[i]);
        count++;
    }
    fprintf(self->dumper.out,"}\n");
    grib_context_free(a->parent->h->context,values);
  } else {
	  if( ((a->flags & GRIB_ACCESSOR_FLAG_CAN_BE_MISSING) != 0) && grib_is_missing_internal(a) )
		fprintf(self->dumper.out,"%s = MISSING;",a->name);
	  else
		fprintf(self->dumper.out,"%s = %ld;",a->name,value);
  }

  if(err) {
    fprintf(self->dumper.out,"  ");
    fprintf(self->dumper.out,"# *** ERR=%d (%s) [grib_dumper_default::dump_long]",err,grib_get_error_message(err));
  }

  fprintf(self->dumper.out,"\n");
}
static void dump_long(grib_dumper* d,grib_accessor* a,const char* comment)
{
  grib_dumper_wmo *self = (grib_dumper_wmo*)d;
  long value = 0; size_t size =0;
  long *values=NULL;
  int err = 0;
  int i=0;
  long count=0;

  grib_value_count(a,&count);
  size=count;


  if (size>1) {
  	values=(long*)grib_context_malloc_clear(a->parent->h->context,sizeof(long)*size);
	err=grib_unpack_long(a,values,&size);
  } else {
	err=grib_unpack_long(a,&value,&size);
  }

  if( a->length == 0  &&
      (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
    return;

  if( (a->flags & GRIB_ACCESSOR_FLAG_READ_ONLY) != 0 &&
      (d->option_flags & GRIB_DUMP_FLAG_READ_ONLY) == 0)
    return;

  set_begin_end(d,a);


  print_offset(self->dumper.out,self->begin,self->theEnd);

  if ((d->option_flags & GRIB_DUMP_FLAG_TYPE) != 0)
        fprintf(self->dumper.out,"%s ",a->creator->op);

  if (size>1) {
	int cols=19;
	int count=0;
	fprintf(self->dumper.out,"%s = { \t",a->name);
	for (i=0;i<size;i++) {
		if (count>cols) {fprintf(self->dumper.out,"\n\t\t\t\t");count=0;}
		fprintf(self->dumper.out,"%ld ",values[i]);
		count++;
	}
	fprintf(self->dumper.out,"}\n");
	grib_context_free(a->parent->h->context,values);
  } else {
	  if( ((a->flags & GRIB_ACCESSOR_FLAG_CAN_BE_MISSING) != 0) && grib_is_missing_internal(a) )
		fprintf(self->dumper.out,"%s = MISSING",a->name);
	  else
		fprintf(self->dumper.out,"%s = %ld",a->name,value);

	  print_hexadecimal(self->dumper.out,d->option_flags,a);

	  if(comment) fprintf(self->dumper.out," [%s]",comment);
  }
  if(err)
    fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_wmo::dump_long]",err,grib_get_error_message(err));

  aliases(d,a);


  fprintf(self->dumper.out,"\n");
}
Exemple #25
0
// The address book is not practical enough yet to be of much use
// Leave all this code commented until it gets improved
address_book::address_book (QWidget *parent) : QWidget(parent)
{
  m_is_modified = false;
  Q3BoxLayout* top_layout = new Q3VBoxLayout (this);
  top_layout->setMargin (4);
  top_layout->setSpacing (4);
  Q3HBox* hb = new Q3HBox (this);
  hb->setSpacing (6);
  top_layout->addWidget (hb);

  Q3VBox* box_left = new Q3VBox (hb);
  Q3VBox* box_right = new Q3VBox (hb);

  // left pane: search criteria and results
  Q3GroupBox* search_box = new Q3GroupBox (3, Qt::Horizontal, tr("Search"), box_left);
  Q3VBox* labels_box = new Q3VBox(search_box);
  Q3VBox* fields_box = new Q3VBox(search_box);
  m_email_search_w = new QLineEdit (fields_box);
  (void)new QLabel (tr("Address"), labels_box);

  m_name_search_w = new QLineEdit (fields_box);
  (void)new QLabel (tr("Name"), labels_box);

  m_nick_search_w = new QLineEdit (fields_box);
  (void)new QLabel (tr("Alias"), labels_box);

  QPushButton* button_search = new QPushButton (tr("Search"), search_box);
  connect (button_search, SIGNAL(clicked()), this, SLOT(search()));

  Q3GroupBox* result_box = new Q3GroupBox (1, Qt::Vertical, tr("Results"), box_left);
  m_result_list_w = new Q3ListView (result_box);
  m_result_list_w->addColumn (tr("Email address"));
  m_result_list_w->addColumn (tr("# msgs"), 50);
  connect(m_result_list_w, SIGNAL(selectionChanged()),
	  this, SLOT(address_selected()));

  // right pane: properties of the selected address
  Q3GroupBox* prop_box = new Q3GroupBox (tr("Properties"), box_right);
  Q3GridLayout *grid_layout = new Q3GridLayout (prop_box, 6, 2);
  grid_layout->setSpacing (4);
  // set a marging big enough for the QGroupBox title not being overwritten
  grid_layout->setMargin (15);
  int g_row = 0;		// grid row

  m_email_w = new QLineEdit (prop_box);
  grid_layout->addWidget (new QLabel (tr("Address:"), prop_box),g_row,0);
  grid_layout->addWidget (m_email_w, g_row, 1);

  g_row++;
  m_name_w = new QLineEdit (prop_box);
  grid_layout->addWidget (new QLabel (tr("Name:"), prop_box), g_row, 0);
  grid_layout->addWidget (m_name_w, g_row, 1);

  g_row++;
  m_nick_w = new QLineEdit (prop_box);
  grid_layout->addWidget (new QLabel (tr("Alias:"), prop_box), g_row, 0);
  grid_layout->addWidget (m_nick_w, g_row, 1);

  g_row++;
  m_notes_w = new Q3MultiLineEdit (prop_box);
  grid_layout->addWidget (new QLabel (tr("Notes:"), prop_box), g_row, 0);
  grid_layout->addWidget (m_notes_w, g_row, 1);

  g_row++;
  m_invalid_w = new QCheckBox (prop_box);
  grid_layout->addWidget (new QLabel (tr("Invalid:"), prop_box), g_row, 0);
  grid_layout->addWidget (m_invalid_w, g_row, 1);

  g_row++;
  QPushButton* button_aliases = new QPushButton(tr("Other addresses..."), prop_box);
  grid_layout->addWidget (button_aliases, 5, 1);
  connect (button_aliases, SIGNAL(clicked()), this, SLOT(aliases()));

  // buttons at the bottom of the window
  Q3HBox* buttons_box = new Q3HBox (this);
  buttons_box->setSpacing (4);
  top_layout->addWidget (buttons_box);

  new Q3HBox (buttons_box);	// takes the left space
  QPushButton* b1 = new QPushButton (tr("New"), buttons_box);
  connect (b1, SIGNAL(clicked()), this, SLOT(new_address()));
  QPushButton* b2 = new QPushButton (tr("Apply"), buttons_box);
  connect (b2, SIGNAL(clicked()), this, SLOT(apply()));
  QPushButton* b3 = new QPushButton (tr("OK"), buttons_box);
  connect (b3, SIGNAL(clicked()), this, SLOT(OK()));
  QPushButton* b4 = new QPushButton (tr("Cancel"), buttons_box);
  connect (b4, SIGNAL(clicked()), this, SLOT(cancel()));
}
Exemple #26
0
eFlag Tree::processVertexAfterParse(Sit S, Vertex *v, TreeConstructer* tc)
{
  //be careful with this test, it might be moved deeper inside this 
  //function if needed

  if (v -> vt & VT_TOP_FOREIGN) 
    {
      popVertex();
      return OK;
    }

  XSL_OP theOp;
  if (isXSLElement(v))
    {
      XSLElement *x = toX(v);
      theOp = x -> op;

      if (theOp != XSL_IMPORT) updateImportStatus();

      switch(theOp)
        {
	  //catch xsl:use-attribute-sets
	case XSL_ELEMENT:
	case XSL_COPY: 
	  {
	    E( extractUsedSets(S, toE(v)) );
	    popVertex();
	  }; break;
	case XSL_IMPORT:
	  {
	    if (subtrees.getCurrent() -> getStructure() -> getTopLevelFound())
	      {
		Err2(S, E_ELEM_CONTAINS_ELEM, 
		     xslOpNames[XSL_STYLESHEET], 
		     xslOpNames[XSL_IMPORT]);
	      }
	  }; // no break
	case XSL_INCLUDE:
	  {
	    Attribute *a = NZ( x -> atts.find(XSLA_HREF) );
	    GP( Tree ) srcTree; 
	    const Str& base = S.findBaseURI(a -> getSubtreeInfo() ->
					    getBaseURI());		
	    
	    Str absolute;
	    makeAbsoluteURI(S, a -> cont, base, absolute);
	    if (S.getProcessor())
	      {
		E( S.getProcessor() -> readTreeFromURI(S, srcTree, 
						       a -> cont, base, 
						       FALSE) );
		srcTree.keep();
	      }
	    else
	      {
		//Str absolute;
		//makeAbsoluteURI(a -> cont, base, absolute);
		srcTree = new Tree(absolute, FALSE);
		DataLine d;
		E( d.open(S, absolute, DLMODE_READ, /* argList = */ NULL) );
		E( (*srcTree).parse(S, &d) );
		E( d.close(S) );
	      }
	    
	    Element *theSheet=(*srcTree).findStylesheet((*srcTree).getRoot());
	    if (!theSheet)
		Warn1(S, W_NO_STYLESHEET, (char*)(a -> cont));
	    dropCurrentElement(v);
	    if (!theSheet) // to prevent segfault after include/import failure
		break;
	    
	    OutputterObj source;
	    //we start a subtree to record where the nodes come from
	    //when including, we use the old structure
	    //when importing, Tree creates a new one
	    E( startSubtree(S, (*srcTree).getURI(), theOp) );
	    //set extension namespaces for subtree

	    //(*srcTree).speakDebug();

	    //merge it into the current tree
	    E( tc -> parseUsingSAXForAWhile(S, source, absolute, 
					    TRUE, 
					    (Tree*)srcTree,
					    theSheet -> namespaces) );

	    //first we have to deal with ext. and excl. namespaces
	    Attribute *attr;
	    QName q;
	    //exclusions
	    q.setLocal((*srcTree).unexpand("exclude-result-prefixes"));
	    attr = theSheet->atts.find(q);
	    if (attr)
	      E(pushNamespacePrefixes(S, attr->cont, XSLA_EXCL_RES_PREFIXES));
	    //extensions
	    q.setLocal((*srcTree).unexpand("extension-element-prefixes"));
	    attr = theSheet->atts.find(q);
	    if (attr)
	      E(pushNamespacePrefixes(S, attr->cont, XSLA_EXT_ELEM_PREFIXES));

	    if (theSheet)
	      E( theSheet -> contents.copy(S, source) );
	    E( tc -> parseUsingSAXForAWhileDone(S, source, TRUE) );
	    // end the subtree
	    E( endSubtree(S, theOp) );		
	  }; break;
	case XSL_OUTPUT:
	  {
	    int i, attsNumber = x -> atts.number();
	    Attribute *theAtt;
	    for (i = 0; i < attsNumber; i++)
	      {
		theAtt = toA(x -> atts[i]);
		switch(theAtt -> op)
		  {
		  case XSLA_METHOD:
		    {
		      QName q;
		      EQName eq;
		      E( x -> setLogical(S, 
					 q, theAtt -> cont, FALSE) );
		      expandQ(q, eq);
		      E( outputDef.setItemEQName(S, XSLA_METHOD, 
						 eq, v, 
						 v -> getImportPrecedence()) );
		    }; break;
		  case XSLA_CDATA_SECT_ELEMS:
		    {
		      QName q;
		      Bool someRemains;
		      Str listPart;
		      char *p = theAtt -> cont;
		      do
			{
			  someRemains = getWhDelimString(p, listPart);
			  if (someRemains)
			    {
			      E( x -> setLogical(S, 
						 q, listPart, TRUE) );
			      EQName expanded;
			      expandQ(q, expanded);
			      E( outputDef.setItemEQName(S, 
							 XSLA_CDATA_SECT_ELEMS,
							 expanded, v, 
							 v -> getImportPrecedence()) );
			    };
			}
		      while (someRemains);
		    }; break;
		  case XSLA_NONE: //skip other namespaces
		    break;
		  default:
		    {
		      E( outputDef.setItemStr(S, theAtt -> op, theAtt -> cont, 
					      theAtt, 
					      theAtt -> getImportPrecedence()) );
		      
		    };
		  };
	      }
	    popVertex();
	  }; break;
	case XSL_NAMESPACE_ALIAS:
	  {
	    Phrase style, result, sUri, rUri;
	    Attribute *sp = NZ( x -> atts.find(XSLA_STYLESHEET_PREFIX) );
	    Attribute *rp = NZ( x -> atts.find(XSLA_RESULT_PREFIX) );
	    if (sp -> cont == "#default") style = UNDEF_PHRASE;
	    else dict().insert(sp -> cont, style);
	    if (rp -> cont == "#default") result = UNDEF_PHRASE;
	    else dict().insert(rp -> cont, result);

	    int i;
	    i = pendingNS().findNdx(style);
	    if (i != -1)
	      sUri = toNS(pendingNS().operator[](i)) -> uri;
	    else
	      Err1(S, E_EX_NAMESPACE_UNKNOWN, (char*) sp -> cont);

	    i = pendingNS().findNdx(result);
	    if (i != -1)
	      rUri = toNS(pendingNS().operator[](i)) -> uri;
	    else
	      Err1(S, E_EX_NAMESPACE_UNKNOWN, (char*) rp -> cont);

	    aliases().insertAlias(sUri, rUri, result, 
				  v -> getImportPrecedence(), x);
	    popVertex();
	  }; break;
	case XSL_TEMPLATE:
	  {
	    E( insertRule(S, x) );
	    popVertex();
	  }; break;
	case XSL_ATTRIBUTE_SET:
	  {
	    QName name;
	    
	    E( x -> setLogical(S, name,
			       NZ( x -> atts.find(XSLA_NAME)) -> cont, 
			       FALSE) );
	    AttSet *ptr = attSets().insert(name);
	    E( extractUsedSets(S, toE(v)) );
	    if (x -> attSetNames(FALSE))
	      {
		for (int i = 0; i < x -> attSetNames(FALSE) -> number(); i++)
		 ptr -> insertUses(*(x -> attSetNames(FALSE) -> operator[] (i)));
	      }
	    XSLElement *son;
	    for (int i = 0; i < x -> contents.number(); i++)
	      {
		sabassert(isXSLElement(x -> contents[i]) && 
		       toX(x -> contents[i]) -> op == XSL_ATTRIBUTE);
		son = toX(x -> contents[i]);
		E( son -> setLogical(S, name, 
				     NZ( son -> atts.find(XSLA_NAME)) -> cont,
				     FALSE) );
		ptr -> insertAttributeDef(son, name);
	      }
	    popVertex();
	  }; break;
	case XSL_STYLESHEET:
	case XSL_TRANSFORM:
	  {
	    popVertex();
	  }; break;
	case XSL_VARIABLE:
	case XSL_PARAM:
	  {
	    // only look at top-levels
	    Vertex *par = v -> parent;
	    if (par && isXSLElement(par) && 
		(toX(par) -> op == XSL_STYLESHEET || 
		 toX(par) -> op == XSL_TRANSFORM))
	      {
		// is top-level -> insert into directory, 
		//with error if there already is an entry 
		// with the same import precedence
		// find name first
		QName name;
		E( x -> setLogical(S, name, 
				   NZ( x -> atts.find(XSLA_NAME)) -> cont, 
				   FALSE) );
		E( toplevelVars.insert(S, name, x) );
	      }
	    popVertex();
	  }; break;
	case XSL_STRIP_SPACE:
	  {
	    SpaceNameList &foo = 
	      subtrees.getCurrent() -> getStructure() -> strippedNames();
	    E( getSpaceNames(S, *x, NZ(x -> atts.find(XSLA_ELEMENTS)) -> cont, 
			     foo) );
	    popVertex();
	  }; break;
	case XSL_PRESERVE_SPACE:
	  {
	    SpaceNameList &foo = 
	      subtrees.getCurrent() -> getStructure() -> preservedNames();
	    E( getSpaceNames(S, *x, NZ(x -> atts.find(XSLA_ELEMENTS)) -> cont, 
			     foo) );
	    popVertex();
	  }; break;
	default:
	  popVertex();
	}
	//the literal output element may have some xsl features
    }
  else 
    { //isXSLElement
      updateImportStatus();
      if (XSLTree) {
	E( extractUsedSets(S, toE(v)) );
	popVertex();
      }
      else {
	popVertex();
      }
    }
  return OK;
}
static void dump_bytes(grib_dumper* d,grib_accessor* a,const char* comment)
{
    grib_dumper_debug *self = (grib_dumper_debug*)d;
    int i,k,err =0;
    int more = 0;
    size_t size = a->length;
    unsigned char* buf = (unsigned char*)grib_context_malloc(d->handle->context,size);

    if( a->length == 0  &&
            (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
        return;

    set_begin_end(d,a);

    for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
    fprintf(self->dumper.out,"%ld-%ld %s %s = %ld",self->begin,self->theEnd,a->creator->op, a->name,a->length);
    aliases(d,a);
    fprintf(self->dumper.out," {");

    if(!buf)
    {
        if(size == 0)
            fprintf(self->dumper.out,"}\n");
        else
            fprintf(self->dumper.out," *** ERR cannot malloc(%ld) }\n",(long)size);
        return;
    }

    fprintf(self->dumper.out,"\n");

    err = grib_unpack_bytes(a,buf,&size);
    if(err){
        grib_context_free(d->handle->context,buf);
        fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_debug::dump_bytes]\n}",err,grib_get_error_message(err));
        return ;
    }

    if(size > 100) {
        more = size - 100;
        size = 100;
    }

    k = 0;
    /* if(size > 100) size = 100;  */
    while(k < size)
    {
        int j;
        for(i = 0; i < d->depth + 3 ; i++) fprintf(self->dumper.out," ");
        for(j = 0; j < 16 && k < size; j++, k++)
        {
            fprintf(self->dumper.out,"%02x",buf[k]);
            if(k != size-1)
                fprintf(self->dumper.out,", ");
        }
        fprintf(self->dumper.out,"\n");
    }

    if(more)
    {
        for(i = 0; i < d->depth + 3 ; i++) fprintf(self->dumper.out," ");
        fprintf(self->dumper.out,"... %d more values\n",more);
    }

    for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
    fprintf(self->dumper.out,"} # %s %s \n",a->creator->op, a->name);
    grib_context_free(d->handle->context,buf);
}
Exemple #28
0
/***********************************************************************
 * Parse a single documentation block for markup
 **********************************************************************/
static Poco::JSON::Object::Ptr parseCommentBlockForMarkup(const CodeBlock &commentBlock)
{
    Poco::JSON::Object::Ptr topObj(new Poco::JSON::Object());
    Poco::JSON::Array calls;
    Poco::JSON::Array keywords;
    Poco::JSON::Array::Ptr aliases(new Poco::JSON::Array());
    Poco::JSON::Array categories;
    Poco::JSON::Array params;
    Poco::JSON::Array::Ptr topDocs(new Poco::JSON::Array());
    Poco::JSON::Object::Ptr currentParam;

    std::string state;
    std::string indent;

    std::string instruction;
    std::string payload;

    //search for the markup begin tag and record the indent
    for (const auto &codeLine : commentBlock)
    {
        std::string line = codeLine.text;
        Poco::RegularExpression::MatchVec matches;

        if (not state.empty())
        {
            if (line.size() >= indent.size() and line.substr(0, indent.size()) != indent)
            {
                if (codeLine.lineNo == commentBlock.back().lineNo) line = "";
                else throw Pothos::SyntaxException("Inconsistent indentation", codeLine.toString());
            }

            if (line.size() >= indent.size()) line = line.substr(indent.size());
            else line = "";

            Poco::RegularExpression("^\\|(\\w+)\\s+(.*)$").match(line, 0, matches);
            if (not matches.empty())
            {
                assert(matches.size() == 3);
                instruction = line.substr(matches[1].offset, matches[1].length);
                payload = line.substr(matches[2].offset, matches[2].length);
            }
        }

        if (state.empty())
        {
            Poco::RegularExpression("^(.*)\\|PothosDoc\\s+(.*)$").match(line, 0, matches);
            if (matches.empty()) continue;
            assert(matches.size() == 3);
            indent = line.substr(matches[1].offset, matches[1].length);
            topObj->set("name", Poco::trim(line.substr(matches[2].offset, matches[2].length)));
            state = "DOC";
        }
        else if (matches.empty() and state == "DOC")
        {
            topDocs->add(line);
        }
        else if (matches.empty() and state == "PARAM")
        {
            auto array = currentParam->getArray("desc");
            array->add(line);
            currentParam->set("desc", stripDocArray(array));
        }
        else if (instruction == "category" and state == "DOC")
        {
            categories.add(Poco::trim(payload));
        }
        else if (instruction == "keywords" and state == "DOC")
        {
            for (const auto &keyword : Poco::StringTokenizer(
                payload, " \t", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY))
            {
                keywords.add(Poco::trim(keyword));
            }
        }
        else if (instruction == "alias" and state == "DOC")
        {
            const std::string alias(Poco::trim(payload));
            try {Pothos::PluginPath(alias);}
            catch (const Pothos::PluginPathError &)
            {
                throw Pothos::SyntaxException("Invalid alias path", codeLine.toString());
            }
            aliases->add(alias);
        }
        else if (instruction == "param" and (state == "DOC" or state == "PARAM"))
        {
            payload = bracketEscapeEncode(payload);
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)(\\s*\\[(.*)\\]\\s*)?(.*)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |param key[name] description",
                codeLine.toString());

            assert(fields.size() == 5);
            const std::string key = bracketEscapeDecode(Poco::trim(payload.substr(fields[1].offset, fields[1].length)));
            std::string name = titleCase(key);
            if (fields[3].length != 0) name = bracketEscapeDecode(Poco::trim(payload.substr(fields[3].offset, fields[3].length)));
            const std::string desc = bracketEscapeDecode(Poco::trim(payload.substr(fields[4].offset, fields[4].length)));

            currentParam = Poco::JSON::Object::Ptr(new Poco::JSON::Object());
            params.add(currentParam);
            currentParam->set("key", key);
            currentParam->set("name", name);
            Poco::JSON::Array::Ptr descArr(new Poco::JSON::Array());
            descArr->add(desc);
            currentParam->set("desc", descArr);
            state = "PARAM";
        }
        else if (instruction == "default" and state == "PARAM")
        {
            if (currentParam->has("default")) throw Pothos::SyntaxException(
                "Multiple occurrence of |default for param",
                codeLine.toString());
            currentParam->set("default", payload);
        }
        else if (instruction == "units" and state == "PARAM")
        {
            if (currentParam->has("units")) throw Pothos::SyntaxException(
                "Multiple occurrence of |units for param",
                codeLine.toString());
            currentParam->set("units", payload);
        }
        else if (instruction == "widget" and state == "PARAM")
        {
            if (currentParam->has("widgetType")) throw Pothos::SyntaxException(
                "Multiple occurrence of |widget for param",
                codeLine.toString());
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)\\s*\\((.*)\\)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |widget SpinBox(args...)",
                codeLine.toString());

            assert(fields.size() == 3);
            const std::string widgetType = Poco::trim(payload.substr(fields[1].offset, fields[1].length));
            const std::string argsStr = Poco::trim(payload.substr(fields[2].offset, fields[2].length));

            currentParam->set("widgetType", widgetType);
            loadArgs(codeLine, *currentParam, argsStr, "widgetArgs", "widgetKwargs");
        }
        else if (instruction == "tab" and state == "PARAM")
        {
            if (currentParam->has("tab")) throw Pothos::SyntaxException(
                "Multiple occurrence of |tab for param",
                codeLine.toString());
            currentParam->set("tab", payload);
        }
        else if (instruction == "preview" and state == "PARAM")
        {
            if (currentParam->has("preview")) throw Pothos::SyntaxException(
                "Multiple occurrence of preview for param",
                codeLine.toString());
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)(\\s*\\((.*)\\))?$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |preview previewType(args...)",
                codeLine.toString());

            assert(fields.size() == 2 or fields.size() == 4);
            const std::string previewType = Poco::trim(payload.substr(fields[1].offset, fields[1].length));

            if (previewType != "disable" and
                previewType != "enable" and
                previewType != "valid" and
                previewType != "invalid" and
                previewType != "when"
            ) throw Pothos::SyntaxException(
                "Only supports enable/disable/valid/invalid/when as value for preview option of param",
                codeLine.toString());

            currentParam->set("preview", previewType);
            if (fields.size() == 4)
            {
                const std::string argsStr = Poco::trim(payload.substr(fields[3].offset, fields[3].length));
                loadArgs(codeLine, *currentParam, argsStr, "previewArgs", "previewKwargs");
            }
        }
        else if (instruction == "option" and state == "PARAM")
        {
            payload = bracketEscapeEncode(payload);
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^(\\s*\\[(.*)\\]\\s*)?(.*)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |option [name] value",
                codeLine.toString());

            assert(fields.size() == 4);
            const std::string value = bracketEscapeDecode(Poco::trim(payload.substr(fields[3].offset, fields[3].length)));
            std::string name = titleCase(value);
            if (fields[2].length != 0) name = bracketEscapeDecode(Poco::trim(payload.substr(fields[2].offset, fields[2].length)));

            Poco::JSON::Object option;
            option.set("value", value);
            option.set("name", name);
            if (not currentParam->has("options")) currentParam->set(
                "options", Poco::JSON::Array::Ptr(new Poco::JSON::Array()));
            currentParam->getArray("options")->add(option);
        }
        else if (instruction == "factory" and (state == "DOC" or state == "PARAM"))
        {
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(/.*)\\s*\\((.*)\\)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |factory /registry/path(args...)",
                codeLine.toString());

            assert(fields.size() == 3);
            const std::string path = Poco::trim(payload.substr(fields[1].offset, fields[1].length));
            const std::string argsStr = Poco::trim(payload.substr(fields[2].offset, fields[2].length));

            //add the path
            try {Pothos::PluginPath(path);}
            catch (const Pothos::PluginPathError &)
            {
                throw Pothos::SyntaxException("Invalid factory path", codeLine.toString());
            }
            if (topObj->has("path")) throw Pothos::SyntaxException(
                "Multiple occurrence of |factory", codeLine.toString());
            topObj->set("path", path);

            //split and extract args
            loadArgs(codeLine, *topObj, argsStr);

            state = "DOC";
        }
        else if ((instruction == "setter" or instruction == "initializer") and (state == "DOC" or state == "PARAM"))
        {
            Poco::RegularExpression::MatchVec fields;
            Poco::RegularExpression("^\\s*(\\w+)\\s*\\((.*)\\)$").match(payload, 0, fields);
            if (fields.empty()) throw Pothos::SyntaxException(
                "Expected |"+instruction+" setFooBar(args...)",
                codeLine.toString());

            assert(fields.size() == 3);
            const std::string callName = Poco::trim(payload.substr(fields[1].offset, fields[1].length));
            const std::string argsStr = Poco::trim(payload.substr(fields[2].offset, fields[2].length));

            //add to calls
            Poco::JSON::Object call;
            call.set("type", instruction);
            call.set("name", callName);
            loadArgs(codeLine, call, argsStr);
            calls.add(call);

            state = "DOC";
        }
        else if (instruction == "mode" and (state == "DOC" or state == "PARAM"))
        {
            if (topObj->has("mode")) throw Pothos::SyntaxException(
                "Multiple occurrence of |mode",
                codeLine.toString());
            topObj->set("mode", payload);
        }
    }

    //empty state means this was a regular comment block, return null
    if (state.empty()) return Poco::JSON::Object::Ptr();

    topDocs = stripDocArray(topDocs);
    if (topDocs->size() > 0) topObj->set("docs", topDocs);
    if (categories.size() > 0) topObj->set("categories", categories);
    if (keywords.size() > 0) topObj->set("keywords", keywords);
    if (aliases->size() > 0) topObj->set("aliases", aliases);
    if (params.size() > 0) topObj->set("params", params);
    if (calls.size() > 0) topObj->set("calls", calls);

    //sanity check for required stuff
    if (not topObj->has("path"))
    {
        throw Pothos::SyntaxException("missing |factory declaration");
    }

    return topObj;
}
static void dump_values(grib_dumper* d,grib_accessor* a)
{
    grib_dumper_debug *self = (grib_dumper_debug*)d;
    int i,k,err =0;
    int more = 0;
    double*  buf = NULL;
    size_t size=0;
    long count=0;

    if( a->length == 0  &&
            (d->option_flags & GRIB_DUMP_FLAG_CODED) != 0)
        return;

    grib_value_count(a,&count);
    size=count;
    if(size == 1){
        dump_double(d,a,NULL);
        return ;
    }
    buf = (double*)grib_context_malloc(d->handle->context,size * sizeof(double));

    set_begin_end(d,a);

    for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
    fprintf(self->dumper.out,"%ld-%ld %s %s = (%ld,%ld)",self->begin,self->theEnd,a->creator->op, a->name,(long)size,a->length);
    aliases(d,a);
    fprintf(self->dumper.out," {");

    if(!buf)
    {
        if(size == 0)
            fprintf(self->dumper.out,"}\n");
        else
            fprintf(self->dumper.out," *** ERR cannot malloc(%ld) }\n",(long)size);
        return;
    }

    fprintf(self->dumper.out,"\n");

    err =  grib_unpack_double(a,buf,&size);

    if(err){
        grib_context_free(d->handle->context,buf);
        fprintf(self->dumper.out," *** ERR=%d (%s) [grib_dumper_debug::dump_values]\n}",err,grib_get_error_message(err));
        return ;
    }

    if(size > 100) {
        more = size - 100;
        size = 100;
    }


    k = 0;
    while(k < size)
    {
#if 1
        int j;
        for(i = 0; i < d->depth + 3 ; i++) fprintf(self->dumper.out," ");
        for(j = 0; j < 8 && k < size; j++, k++)
        {
            fprintf(self->dumper.out,"%10g",buf[k]);
            if(k != size-1)
                fprintf(self->dumper.out,", ");
        }
        fprintf(self->dumper.out,"\n");
#else

        fprintf(self->dumper.out,"%d %g\n",k,buf[k]);

#endif

    }
    if(more)
    {
        for(i = 0; i < d->depth + 3 ; i++) fprintf(self->dumper.out," ");
        fprintf(self->dumper.out,"... %d more values\n",more);
    }

    for(i = 0; i < d->depth ; i++) fprintf(self->dumper.out," ");
    fprintf(self->dumper.out,"} # %s %s \n",a->creator->op, a->name);
    grib_context_free(d->handle->context,buf);
}
Exemple #30
0
void checkMonster(TTree * PixelTree, int source=0)
{
  // set come alisas
  aliases(PixelTree);
  TCut cutBeforeEds, evtSel;
  TString titleBeforeEds, titleLoose,outDir;
  if (source==0) {
    cutBeforeEds = "bscSelColBx&&vz[1]>-99";
    titleBeforeEds = "Run 132440 -- L1A124,BPTX_AND,noHalo,BSC_OR,vtx";
    outDir="plots/inspect/data_coll";
  } else if (source==1) {
    cutBeforeEds = "bscSelMc && vz[1]>-99";
    titleBeforeEds = "PythiaD6T -- noHalo,BSC_OR,vtx";
    outDir="plots/inspect/mc";
  } else if (source==2) {
    cutBeforeEds = "bscSelEmpBx && vz[1]>-99";
    titleBeforeEds = "Run 132422 (empty bx) -- L1A124,noHalo,BSC_OR,vtx";
    outDir="plots/inspect/data_emptyBx";
  }
  evtSel = cutBeforeEds && "edscut2";
  titleEvtSel = titleBeforeEds+",Ed's cut";

  // Printout some stat
  cout << "===== Sel Info =====" << endl;
  cout << "Total # of Events: " << PixelTree->GetEntries() << endl;
  cout << "Passing " << PixelTree->GetAlias("trigger") << ": " << PixelTree->GetEntries("trigger") << endl;
  cout << "Passing " << PixelTree->GetAlias("bscSelEmpBx") << ": " << PixelTree->GetEntries("bscSelEmpBx") << endl;
  cout << "Passing " << TString(cutBeforeEds) << ": " << PixelTree->GetEntries(cutBeforeEds) << endl;
  cout << "Passing " << TString(evtSel) << ": " << PixelTree->GetEntries(evtSel) << endl;

  // Draw
  PixelTree->Draw("vtxqual:npxhits>>hVtxQual(50,0,1500,50,0,10)",cutBeforeEds,"goff");
  hVtxQual->SetTitle(titleBeforeEds+"; # of pixel hits; cluster-vertex compatibility");
  hVtxQual->SetMinimum(1); hVtxQual->SetMaximum(1000);

  PixelTree->Draw("vtxqual:npxhits>>hVtxQualCut(50,0,1500,50,0,10)",evtSel,"goff");
  hVtxQualCut->SetTitle(titleEvtSel+"; # of pixel hits; cluster-vertex compatibility");
  hVtxQualCut->SetMinimum(1); hVtxQualCut->SetMaximum(1000);

  //---------------Monster Cut---------------------
  // Check cut
  Double_t x[3] = {150,150,1000};
  Double_t y[3] = {0,0.5+0.0045*150,0.5+0.0045*1000};
  TPolyLine *pline = new TPolyLine(3,x,y);
  pline->SetLineColor(2);
  pline->SetLineWidth(2);

  Double_t x2[4] = {150,150,2/0.0045,1000};
  Double_t y2[4] = {0,0.0045*150,2,2};
  TPolyLine *pline2 = new TPolyLine(4,x2,y2);
  pline2->SetLineColor(2);
  pline2->SetLineWidth(2);
  pline2->SetLineStyle(2);

  TCanvas *cBeforeEdsCut = new TCanvas("cBeforeEdsCut","cBeforeEdsCut",500,500);
  hVtxQual->Draw("colz");
  gPad->SetRightMargin(0.15);
  gPad->SetLogz();

  pline->Draw("same");
  pline2->Draw("same");
  gSystem->mkdir(outDir.Data(),kTRUE);
  cBeforeEdsCut->Print(Form("%s/checkMonster.gif",outDir.Data()));

  // Apply Cut
  TCanvas *cAfterEdsCut = new TCanvas("cAfterEdsCut","cAfterEdsCut",500,500);
  hVtxQualCut->Draw("colz");
  gPad->SetRightMargin(0.15);
  gPad->SetLogz();

  pline->Draw("same");
  pline2->Draw("same");
}