Example #1
0
UndeclaredIdentifierError::UndeclaredIdentifierError(
    const std::string& identifier, const location& loc) : FrontEndError(loc) {
  boost::format fmt("Use of undeclared identifier '%1%'.");
  setMessage(boost::str(fmt % identifier));
}
Example #2
0
TEST_F(CFGAS_FormatStringTest, NumFormat) {
  struct {
    const wchar_t* locale;
    const wchar_t* input;
    const wchar_t* pattern;
    const wchar_t* output;
  } tests[] = {
      {L"en", L"1.234", L"zz9.zzz", L"1.234"},
      {L"en", L"1", L"num{z 'text'}", L"1 text"},
      {L"en", L"1", L"num{'text' z}", L"text 1"},
      {L"en", L"1.234", L"ZZ9.ZZZ", L"  1.234"},
      {L"en", L"12.345", L"zz9.zzz", L"12.345"},
      {L"en", L"12.345", L"ZZ9.ZZZ", L" 12.345"},
      {L"en", L"123.456", L"zz9.zzz", L"123.456"},
      {L"en", L"123.456", L"ZZ9.ZZZ", L"123.456"},
      {L"en", L"123", L"zz9.zzz", L"123"},
      {L"en", L"123", L"ZZ9.ZZZ", L"123.000"},
      {L"en", L"123.", L"zz9.zzz", L"123."},
      {L"en", L"123.", L"ZZ9.ZZZ", L"123.000"},
      {L"en", L"123.0", L"zz9.zzz", L"123"},
      {L"en", L"123.0", L"ZZ9.ZZZ", L"123.000"},
      {L"en", L"123.000", L"zz9.zzz", L"123"},
      {L"en", L"123.000", L"ZZ9.ZZZ", L"123.000"},
      // {L"en", L"12345.67", L"zzz,zz9.88888888", L"12,345.67"},
      // {L"en", L"12345.0000", L"zzz,zz9.88888888", L"12,345.0000"},
      // {L"en", L"12345.6789", L"zzz,zz9.8", L"12,345.6789"},
      // {L"en", L"12345.", L"zzz,zz9.8", L"12,345"},
      // {L"en", L"123456.000", L"zzz,zz9.8888", L"123,456.000"},
      // {L"en", L"123456.0", L"zzz,zz9.8888", L"123,456.0"},
      {L"en", L"123456", L"zzz,zz9.8888", L"123,456"},
      {L"en", L"123456", L"ZZZ,ZZ9.88", L"123,456"},
      // {L"en", L"12345.67", L"zzz,zz9.88888888", L"12,345.67"},
      // {L"en", L"12345.0000", L"zzz,zz9.88888888", L"12,345.0000"},
      // {L"en", L"12345.6789", L"zzz,zz9.8", L"12,345.6789"},
      // {L"en", L"12345.", L"zzz,zz9.8", L"12,345"},
      // {L"en", L"12%%", L"zz9.%%", L"12%%"},
      // {L"en", L"1,234.5%%", L"zzz,zz9.99%%", L"1,234.50%%"},
      {L"en", L"-1.23", L"S999v99", L"-00123"},
      {L"en", L"1.23", L"S999V99", L" 001.23"},
      {L"en", L"123", L"S999V99", L" 123.00"},
      {L"en", L"12.3", L"SZZ9.99", L"  12.30"},
      {L"en", L"-12.3", L"SZ99.99", L"- 12.30"},
      {L"en", L"123", L"szz9.99", L"123.00"},
      {L"en", L"-123", L"szz9.99", L"-123.00"},
      // {L"en", L"1234", L"$ZZ,ZZ9.99CR", L"$  1,234.00  "},
      // {L"en", L"-1234", L"$ZZ,ZZ9.99CR", L"$  1,234.00CR"},
      // {L"en", L"1234", L"$z,zz9.99DB", L"$1,234.00"},
      {L"en", L"-1234", L"$z,zz9.99DB", L"$1,234.00DB"},
      {L"en", L"12345", L"99.999E", L"12.345E+3"},
      {L"en", L"12345", L"99999E", L"12345E+0"},
      {L"en", L".12345", L"99.999E", L"12.345E-2"},
      {L"en", L"12345", L"99,999", L"12,345"},
      {L"en", L"1234", L"num(fr){z,zzz}",
       L"1\xA0"
       L"234"},
      {L"en", L"12.34", L"num.percent{}", L"1,234%"},
      {L"en", L"12.34", L"num(fr).percent{}",
       L"1\xA0"
       L"234%"},
      // {L"en", L"12.34", L"num{9,999%%}", L"1,234%"},
      {L"en", L"-123", L"zzzCR", L"123CR"},
      {L"en", L"123", L"zzzCR", L"123  "},
      {L"en", L"-123", L"zzzcr", L"123CR"},
      {L"en", L"123", L"zzzcr", L"123"},
      {L"en", L"123", L"zzz$", L"123$"},
      {L"en", L"-123.5", L"zzz.zCR", L"123.5CR"},
      {L"en", L"123.5", L"zzz.zCR", L"123.5  "},
      {L"en", L"-123.5", L"zzz.zcr", L"123.5CR"},
      {L"en", L"123.5", L"zzz.zcr", L"123.5"},

      {L"en", L"-123.5", L"999.9db", L"123.5db"},
      {L"en", L"123.5", L"999.9db", L"123.5"},
      {L"en", L"-123.5", L"999.9DB", L"123.5DB"},
      {L"en", L"123.5", L"999.9DB", L"123.5  "},

      {L"en", L"-123", L"(zzz", L"(123"},
      // {L"en", L"-123", L"zzz)", L"123)"},
      {L"en", L"-123", L"(zzz)", L"(123)"},
      {L"en", L"123", L"zzz)", L"123 "},
      {L"en", L"123", L"(zzz", L" 123"},
      {L"en", L"123", L"(zzz)", L" 123 "},
      {L"en", L"-123.5", L"zzz.z(", L"123.5("},
      // {L"en", L"-123.5", L"zzz.z)", L"123.5)"},
      {L"en", L"123.5", L"zzz.z)", L"123.5 "},
      {L"en", L"123.5", L"zzz.z(", L"123.5 "},
  };

  for (size_t i = 0; i < FX_ArraySize(tests); ++i) {
    WideString result;
    EXPECT_TRUE(fmt(tests[i].locale)
                    ->FormatNum(tests[i].input, tests[i].pattern, &result))
        << " TEST: " << i;
    EXPECT_STREQ(tests[i].output, result.c_str()) << " TEST: " << i;
  }
}
Example #3
0
// TODO(dsinclair): Looks like the formatter/parser does not handle the various
// 'g' flags.
TEST_F(CFGAS_FormatStringTest, DateFormat) {
  struct {
    const wchar_t* locale;
    const wchar_t* input;
    const wchar_t* pattern;
    const wchar_t* output;
  } tests[] = {
      {L"en", L"2002-10-25", L"MMMM DD, YYYY", L"October 25, 2002"},
      // Note, this is in the doc as 5 but it's wrong and should be 3 by the
      // example in the Picture Clause Reference section.
      {L"en", L"20040722", L"'Week of the month is' w",
       L"Week of the month is 3"},
      {L"en", L"20040722", L"e 'days after Sunday'", L"4 days after Sunday"},
      {L"en", L"20040722", L"YYYY-'W'WW-e", L"2004-W30-4"},
      {L"en", L"20040722", L"E 'days after Saturday'",
       L"5 days after Saturday"},
      {L"en", L"2000-01-01", L"EEE, 'the' D 'of' MMMM, YYYY",
       L"Sat, the 1 of January, 2000"},
      {L"en", L"2000-01-01", L"EEEE, 'the' D 'of' MMMM, YYYY",
       L"Saturday, the 1 of January, 2000"},
      {L"en", L"19991202", L"MM/D/YY", L"12/2/99"},
      {L"en", L"19990110", L"MMM D, YYYY", L"Jan 10, 1999"},
      {L"en", L"19990202", L"J", L"33"},
      {L"en", L"19990202", L"JJJ", L"033"},
      {L"en", L"19991231", L"J", L"365"},
      {L"en", L"20001231", L"J", L"366"},
      {L"en", L"19990501", L"J", L"121"},
      {L"en", L"19990901", L"J", L"244"},
      {L"en", L"19990228", L"J", L"59"},
      {L"en", L"20000229", L"J", L"60"},
      {L"en", L"21000501", L"J", L"121"},
      {L"en", L"19990102", L"M", L"1"},
      {L"en", L"19990102", L"MMM", L"Jan"},
      {L"en", L"19990102", L"YYYY G", L"1999 AD"},
      // Week 01 of the year is the week containing Jan 04.
      // {L"en", L"19990102", L"WW", L"00"},  -- Returns 01 incorrectly
      // {L"en", L"19990104", L"WW", L"01"},  -- Returns 02 incorrectly
      // The ?*+ should format as whitespace.
      // {L"en", L"19990104", L"YYYY?*+MM", L"1999   01"},
      // {L"en", L"1999-07-16", L"date{DD/MM/YY} '('date{MMM DD, YYYY}')'",
      //  L"16/07/99 (Jul 16, 1999)"},
      {L"de_CH", L"20041030", L"D. MMMM YYYY", L"30. Oktober 2004"},
      {L"fr_CA", L"20041030", L"D MMMM YYYY", L"30 octobre 2004"},
      {L"en", L"2002-10-25", L"date(fr){DD MMMM, YYYY}", L"25 octobre, 2002"},
      {L"en", L"2002-10-25", L"date(es){EEEE, D 'de' MMMM 'de' YYYY}",
       L"viernes, 25 de octubre de 2002"},
      // {L"en", L"2002-20-25", L"date.long(fr)()", L"25 octobre, 2002"},
      // {L"ja", L"2003-11-03", L"gY/M/D", L"H15/11/3"},
      // {L"ja", L"1989-01-08", L"ggY-M-D", L"\u5e731-1-8"},
      // {L"ja", L"1989-11-03", L"gggYY/MM/DD", L"\u5e73\u621089/11/03"},
  };
  // Note, none of the full width date symbols are listed here
  // as they are not supported. In theory there are the full width versions
  // of DDD, DDDD, MMM, MMMM, E, e, gg, YYY, YYYYY.

  for (size_t i = 0; i < FX_ArraySize(tests); ++i) {
    WideString result;
    EXPECT_TRUE(fmt(tests[i].locale)
                    ->FormatDateTime(tests[i].input, tests[i].pattern,
                                     FX_DATETIMETYPE_Date, &result));
    EXPECT_STREQ(tests[i].output, result.c_str()) << " TEST: " << i;
  }
}
Example #4
0
types::str str::operator%(std::tuple<A...> const &a) const
{
    boost::format fmter(*data);
    fmt(fmter, a, utils::int_<sizeof...(A)>());
    return fmter.str();
}
Example #5
0
void str::fmt(boost::format &f, Tuple const &a, utils::int_<I>) const
{
    fmt(f % std::get<std::tuple_size<Tuple>::value - I>(a), a,
        utils::int_<I - 1>());
}
Example #6
0
void DateFormatRegressionTest::Test4182066(void) {
    UErrorCode status = U_ZERO_ERROR;
    SimpleDateFormat fmt("MM/dd/yy", Locale::getUS(), status);
    SimpleDateFormat dispFmt("MMM dd yyyy GG", Locale::getUS(), status);
    if (U_FAILURE(status)) {
        errcheckln(status, "Couldn't create SimpleDateFormat - %s", u_errorName(status));
        return;
    }

    /* We expect 2-digit year formats to put 2-digit years in the right
     * window.  Out of range years, that is, anything less than "00" or
     * greater than "99", are treated as literal years.  So "1/2/3456"
     * becomes 3456 AD.  Likewise, "1/2/-3" becomes -3 AD == 2 BC.
     */
    const char* STRINGS[] = {
        "02/29/00",
        "01/23/01",
        "04/05/-1",
        "01/23/-9",
        "11/12/1314",
        "10/31/1",
        "09/12/+1",
        "09/12/001",
    };
    int32_t STRINGS_COUNT = (int32_t)(sizeof(STRINGS) / sizeof(STRINGS[0]));
    UDate FAIL_DATE = (UDate) 0;
    UDate DATES[] = {
        date(2000-1900, UCAL_FEBRUARY, 29),
        date(2001-1900, UCAL_JANUARY,  23),
        date(  -1-1900, UCAL_APRIL,     5),
        date(  -9-1900, UCAL_JANUARY,  23),
        date(1314-1900, UCAL_NOVEMBER, 12),
        date(   1-1900, UCAL_OCTOBER,  31),
        FAIL_DATE, // "+1" isn't recognized by US NumberFormat
        date(   1-1900, UCAL_SEPTEMBER,12),
    };

    UnicodeString out;
    UBool pass = TRUE;
    for (int32_t i=0; i<STRINGS_COUNT; ++i) {
        UnicodeString str(STRINGS[i]);
        UDate expected = DATES[i];
        status = U_ZERO_ERROR;
        UDate actual = fmt.parse(str, status);
        if (U_FAILURE(status)) {
            actual = FAIL_DATE;
        }
        UnicodeString actStr;
        if (actual == FAIL_DATE) {
            actStr.append("null");
        } else {
            // Yuck: See j25
            ((DateFormat*)&dispFmt)->format(actual, actStr);
        }

        if (expected == actual) {
            out.append(str + " => " + actStr + "\n");
        } else {
            UnicodeString expStr;
            if (expected == FAIL_DATE) {
                expStr.append("null");
            } else {
                // Yuck: See j25
                ((DateFormat*)&dispFmt)->format(expected, expStr);
            }
            out.append("FAIL: " + str + " => " + actStr
                       + ", expected " + expStr + "\n");
            pass = FALSE;
        }
    }
    if (pass) {
        log(out);
    } else {
        err(out);
    }
}
/**
 *  Application entry point.
 */
int
voiminfo (int argc, char **argv, size_t *reslen, void **result)
{
    /*  These declarations are required for the VOApps param interface.
     */
    char **pargv, optval[SZ_FNAME], resbuf[SZ_RESBUF];
    char   imname[SZ_LINE];


    /*  These declarations are specific to the task.
     */
    char   *oname = NULL, *imlist[MAX_IMAGES], *nimlist[MAX_IMAGES];
    int     i, ch = 0, status = OK, pos = 0, nfiles = 0, narg = 0;;
    size_t  maxlen = SZ_RESBUF;
    FILE   *fd = (FILE *) NULL;
    ImInfo *im;


    /* Initialize result object	whether we return an object or not.
     */
    *reslen = 0;	
    *result = NULL;
    memset (imlist,  0, MAX_IMAGES);
    memset (nimlist, 0, MAX_IMAGES);


    /*  Parse the argument list.  The use of vo_paramInit() is required to
     *  rewrite the argv[] strings in a way vo_paramNext() can be used to
     *  parse them.  The programmatic interface allows "param=value" to
     *  be passed in, but the getopt_long() interface requires these to
     *  be written as "--param=value" so they are not confused with 
     *  positional parameters (i.e. any param w/out a leading '-').
     */
    pargv = vo_paramInit (argc, argv, opts, long_opts);
    while ((ch = vo_paramNext(opts,long_opts,argc,pargv,optval,&pos)) != 0) {
        if (ch > 0) {
	    /*  If the 'ch' value is > 0 we are parsing a single letter
	     *  flag as defined in the 'opts string.
	     */
	    switch (ch) {
	    case '%':  Tests (optval);			return (self.nfail);
	    case 'h':  Usage ();			return (OK);
	    case 'r':  do_return=1;	    	    	break;
	    case 'd':  debug++;				break;
	    case 'v':  verbose++;			break;

	    case 'a':  do_all++;			break;
	    case 'b':  do_box++;			break;
	    case 'c':  do_corners++;			break;
	    case 'e':  do_extns++;			break;
	    case 'i':  do_info++;			break;
	    case 's':  do_sex++;			break;
	    case 'n':  do_naxis++;			break;
	    case 'o':  oname = strdup (optval);		break;
	    default:
		fprintf (stderr, "Invalid option '%s'\n", optval);
		return (1);
	    }

        } else if (ch == PARG_ERR) {
            return (ERR);

	} else {
	    /*  This code processes the positional arguments.  The 'optval'
	     *  string contains the value but since this string is
	     *  overwritten w/ each arch we need to make a copy (and must
	     *  remember to free it later.
	     */
	    imlist[nfiles++] = strdup (optval);
	    narg++;
	}

	if (narg > MAX_IMAGES) {
            fprintf (stderr, "ERROR: Too many images to process\n");
            return (1);
	}
    }


    /*  Sanity checks.
     */
    if (imlist[0] == NULL || strcmp (imlist[0], "-") == 0) { 
	free (imlist[0]);
	imlist[0] = strdup ("stdin");  
	nfiles = 1;
    }
    if (do_all && strcasecmp (imlist[0], "stdin") == 0) {
	fprintf (stderr, "Error: Option not supported with standard input\n");
	return (ERR);
    }
    if (oname == NULL) oname = strdup ("stdout");
    if (strcmp (oname, "-") == 0) { free (oname), oname = strdup ("stdout"); }


    /*  Open the output file.
     */
    if (strcmp (oname, "stdout") != 0) {
	if ((fd = fopen (oname, "w+")) == (FILE *) NULL) {
	    fprintf (stderr, "Error: Cannot open output file '%s'\n", oname);
	    return (ERR);
	}
    } else
	fd = stdout;

    /* Default to printing all info if we're not given a specific option.
    if (!do_box && !do_corners && !do_info && !do_naxis)
	do_info = 1;
     */


    /**
     *  Main body of task
     */
    for (i=0; i < nfiles; i++) {

	memset (imname, 0, SZ_LINE);
	if (strncmp ("http://", imlist[i], 7) == 0) {
	    if (access ("/tmp/voiminfo.fits", F_OK) == 0)
		unlink ("/tmp/voiminfo.fits");
	    strcpy (imname, "/tmp/voiminfo.fits");
	    if (vos_getURL (imlist[i], imname) <= 0)
		continue;
	} else
	    strcpy (imname, imlist[i]);

	if ((im = vot_imageInfo (imname, do_all)) ) {
    	    memset (resbuf,  0, SZ_RESBUF);
	    if (do_info) {
                vot_printImageInfo (fd, im);
	    } else if (do_naxis) {
		strcpy (resbuf, fmt_naxis (imname, im, do_all));
	    } else if (do_box) {
		strcpy (resbuf, fmt_box (imname, im, do_all));
	    } else if (do_corners) {
		strcpy (resbuf, fmt_corners (imname, im, do_all));
	    } else {
                sprintf (resbuf, "%s\t%s\t%s\t%s\n", imlist[i], 
		    fmt (im->frame.cx,1), fmt (im->frame.cy,0), 
		    fmt (im->frame.radius,0));
	    }

	    if (do_return)
		vo_appendResultFromString (resbuf, reslen, result, &maxlen);
	    else
                fprintf (fd, "%s", resbuf);

            vot_freeImageInfo (im);

	    if (strncmp ("http://", imlist[i], 7) == 0)
	        unlink (imname);
	}
    }


    /*  Clean up.  Rememebr to free whatever pointers were created when
     *  parsing arguments.
     */
    for (i=0; i < MAX_IMAGES; i++) {
        if (imlist[i])  
	    free (imlist[i]);
        if (nimlist[i]) 
	    free (nimlist[i]);
	else
	    break;
    }
    if (oname) free (oname);
    if (fd != stdout)
	fclose (fd);

    vo_paramFree (argc, pargv);

    return (status);	/* status must be OK or ERR (i.e. 0 or 1)     	*/
}
Example #8
0
/**
 * @brief リスタート時の平均値ファイル読み込み
 * @param [in]  fp   ファイルポインタ
 * @param [out] flop 浮動小数点演算数
 */
void FFV::RestartAvrerage (FILE* fp, double& flop)
{
  std::string fname;
  std::string fmt(C.file_fmt_ext);
  
  unsigned m_Session_step = C.Interval[Control::tg_compute].getStartStep(); ///< セッションの開始ステップ
  double   m_Session_time = C.Interval[Control::tg_compute].getStartTime(); ///< セッションの開始時刻
  
  // ガイド出力
  int gs = C.GuideOut;
  
  
  // まだ平均値開始時刻になっていなければ,何もしない
  if ( C.Interval[Control::tg_average].getMode() == IntervalManager::By_step )
  {
    if ( m_Session_step >= C.Interval[Control::tg_average].getStartStep() )
    {
      Hostonly_ printf     ("\tRestart from Previous Calculation Results of averaged field\n");
      Hostonly_ fprintf(fp, "\tRestart from Previous Calculation Results of averaged field\n");
      Hostonly_ printf     ("\tStep : base=%u current=%u\n", m_Session_step, CurrentStep);
      Hostonly_ fprintf(fp, "\tStep : base=%u current=%u\n", m_Session_step, CurrentStep);
    }
    else
    {
      return;
    }
  }
  else if ( C.Interval[Control::tg_average].getMode() == IntervalManager::By_time )
  {
    if ( m_Session_time >= C.Interval[Control::tg_average].getStartTime() )
    {
      Hostonly_ printf     ("\tRestart from Previous Calculation Results of averaged field\n");
      Hostonly_ fprintf(fp, "\tRestart from Previous Calculation Results of averaged field\n");
      Hostonly_ printf     ("\tTime : base=%e[sec.]/%e[-] current=%e[-]\n", m_Session_time*C.Tscale, m_Session_time, CurrentTime);
      Hostonly_ fprintf(fp, "\tTime : base=%e[sec.]/%e[-] current=%e[-]\n", m_Session_time*C.Tscale, m_Session_time, CurrentTime);
    }
    else
    {
      return;
    }
  }
  else
  {
    Exit(0);
  }
  
  
  // 現在のセッションの領域分割数の取得
  int gdiv[3] = {1, 1, 1};
  
  if ( numProc > 1)
  {
    const int* m_div = paraMngr->GetDivNum();
    for (int i=0; i<3; i++ ) gdiv[i]=m_div[i];
  }
  
  
  // エラーコード
  CIO::E_CIO_ERRORCODE cio_error;
  
  
  // Averaged dataの初期化
  if ( C.Mode.Average == ON && C.Interval[Control::tg_average].isStarted(CurrentStep, CurrentTime) )
  {
    DFI_IN_PRSA = cio_DFI::ReadInit(MPI_COMM_WORLD, C.f_dfi_in_prsa, G_size, gdiv, cio_error);
    if ( cio_error != CIO::E_CIO_SUCCESS ) Exit(0);
    
    DFI_IN_VELA = cio_DFI::ReadInit(MPI_COMM_WORLD, C.f_dfi_in_vela, G_size, gdiv, cio_error);
    if ( cio_error != CIO::E_CIO_SUCCESS ) Exit(0);
    
    if ( DFI_IN_PRSA == NULL || DFI_IN_VELA == NULL ) Exit(0);
    
    
    if ( C.isHeatProblem() )
    {
      DFI_IN_TEMPA = cio_DFI::ReadInit(MPI_COMM_WORLD, C.f_dfi_in_tempa, G_size, gdiv, cio_error);
      if ( cio_error != CIO::E_CIO_SUCCESS ) Exit(0);
      if ( DFI_IN_TEMPA == NULL ) Exit(0);
    }
  }
  
  
  
  
  unsigned step_avr = 0;
  double time_avr = 0.0;
  
  
  // Pressure
  REAL_TYPE bp = ( C.Unit.Prs == Unit_Absolute ) ? C.BasePrs : 0.0;
  
  
  //自身の領域終点インデックス
  int tail[3];
  for (int i=0; i<3; i++) tail[i] = head[i]+size[i]-1;
  
  double r_time;
  if ( DFI_IN_PRSA->ReadData(d_ap,
                             C.Restart_step,
                             guide,
                             G_size,
                             gdiv,
                             head,
                             tail,
                             r_time,
                             false,
                             step_avr,
                             time_avr) != CIO::E_CIO_SUCCESS ) Exit(0);
  
  if( d_ap == NULL ) Exit(0);
  
  
  CurrentStep_Avr = step_avr;
  CurrentTime_Avr = time_avr;
  
  if ( DFI_IN_VELA->ReadData(d_wo,
                             C.Restart_step,
                             guide,
                             G_size,
                             gdiv,
                             head,
                             tail,
                             r_time,
                             false,
                             step_avr,
                             time_avr) != CIO::E_CIO_SUCCESS ) Exit(0);
  
  if( d_wo == NULL ) Exit(0);
  
  REAL_TYPE refv = (C.Unit.File == DIMENSIONAL) ? C.RefVelocity : 1.0;
  REAL_TYPE scale = (REAL_TYPE)step_avr;
  REAL_TYPE u0[4];
  u0[0] = v00[0];
  u0[1] = v00[1];
  u0[2] = v00[2];
  u0[3] = v00[3];
  
  fb_vin_nijk_(d_av, size, &guide, d_wo, u0, &refv, &flop);
  
  if ( (step_avr != CurrentStep_Avr) || (time_avr != CurrentTime_Avr) ) // 圧力とちがう場合
  {
    Hostonly_ printf     ("\n\tTime stamp is different between files\n");
    Hostonly_ fprintf(fp, "\n\tTime stamp is different between files\n");
    Exit(0);
  }
  
  
  // Temperature
  if ( C.isHeatProblem() )
  {
    if ( DFI_IN_TEMPA->ReadData(d_ae,
                                C.Restart_step,
                                guide,
                                G_size,
                                gdiv,
                                head,
                                tail,
                                r_time,
                                false,
                                step_avr,
                                time_avr) != CIO::E_CIO_SUCCESS ) Exit(0);
    
    if ( d_ae == NULL ) Exit(0);
    
    if ( (step_avr != CurrentStep_Avr) || (time_avr != CurrentTime_Avr) )
    {
      Hostonly_ printf     ("\n\tTime stamp is different between files\n");
      Hostonly_ fprintf(fp, "\n\tTime stamp is different between files\n");
      Exit(0);
    }
  }
}
Example #9
0
    const fs::path&
    module_runtime_path(const std::string& dtype)
    {
      path_map& paths(module_paths());
      path_map::iterator ipath(paths.find(dtype));

      // Is this a valid dtype?
      if (ipath == paths.end())
        {
          boost::format fmt("Invalid runtime path type “%1%”");
          fmt % dtype;
          throw std::logic_error(fmt.str());
        }

      Module& module = ipath->second;

      // Return cached result if previously determined.
      if(!module.realpath.empty())
        return module.realpath;

      // dtype set explicitly in environment.
      if (getenv(module.envvar.c_str()))
        {
          fs::path dir(getenv(module.envvar.c_str()));
          if (validate_path(dir))
            {
              module.realpath = boost::filesystem::canonical(dir);
              return module.realpath;
            }
        }

      // Full module path in environment + relative component
      if (getenv(module.module_envvar.c_str()))
        {
          fs::path home(getenv(module.module_envvar.c_str()));
          home /= module.relpath;
          if (validate_path(home))
            {
              module.realpath = boost::filesystem::canonical(home);
              return module.realpath;
            }
        }

      // Full root path in environment + relative component
      if (getenv(module.root_envvar.c_str()))
        {
          fs::path home(getenv(module.root_envvar.c_str()));
          home /= module.relpath;
          if (validate_path(home))
            {
              module.realpath = boost::filesystem::canonical(home);
              return module.realpath;
            }
        }

      // Full prefix is available only when configured explicitly.
      if (validate_path(module.install_prefix))
        {
          // Full specific path.
          if (validate_path(module.abspath))
            {
              module.realpath = boost::filesystem::canonical(module.abspath);
              return module.realpath;
            }

          // Full root path + relative component
          fs::path home(module.install_prefix);
          home /= module.relpath;
          if (validate_path(home))
            {
              module.realpath = boost::filesystem::canonical(home);
              return module.realpath;
            }
        }
      else
        {
          fs::path module_lib_path;
          if (module.module_path)
            {
              module_lib_path = module.module_path();
            }
          if (module_lib_path.has_parent_path())
            {
              fs::path moduledir(module_lib_path.parent_path());
              bool match = true;

              fs::path libdir(module.shlibpath);

              while(!libdir.empty())
                {
                  if (libdir.filename() == moduledir.filename())
                    {
                      libdir = libdir.parent_path();
                      moduledir = moduledir.parent_path();
                    }
                  else
                    {
                      match = false;
                      break;
                    }
                }
              if (match && validate_path(moduledir))
                {
                  moduledir /= module.relpath;
                  if (validate_path(moduledir))
                    {
                      module.realpath = boost::filesystem::canonical(moduledir);
                      return module.realpath;
                    }
                }
            }
        }
      boost::format fmt("Could not determine Bio-Formats runtime path for “%1%” directory");
      fmt % dtype;
      throw std::runtime_error(fmt.str());
    }
Example #10
0
bool	WSock_SetSendAddr(netconnection_t *nc, char *addr, int clientport)
{	
	struct hostent *hp;
	char *colon;

	if (!addr)  //just change the port
	{
		nc->sendAddr.sin_port = htons((unsigned short)clientport);
		return true;
	}

	//get rid of the colon used to specify a port
	colon = strchr(addr, ':');
	if (colon)
	{
		if (strlen(addr) > (unsigned)(colon-addr))
			clientport = atoi(colon+1);
		*colon = 0;		
	}

	if (isdigit(addr[strlen(addr)-1]))
	{
		unsigned int uint_addr;
		//hp = gethostbyaddr(inet_addr(addr), 4, AF_INET);
		memset(&nc->sendAddr,0,sizeof(struct sockaddr_in));
		uint_addr = inet_addr(addr);
		Mem_Copy(&nc->sendAddr.sin_addr, &uint_addr, 4);
		nc->sendAddr.sin_family = AF_INET;
	}
	else
	{
		hp = gethostbyname(addr);

		if (!hp)
		{
			int error = 0;
		
			#ifdef _WIN32
			error = WSAGetLastError();
			#endif
			NET_PRINTF("WSock_SetSendAddr: Couldn't resolve %s (Error #%i)\n", addr, error);
			return false;
		}

		memset(&nc->sendAddr,0,sizeof(struct sockaddr_in));
		Mem_Copy(&nc->sendAddr.sin_addr, hp->h_addr, hp->h_length);
		nc->sendAddr.sin_family = hp->h_addrtype;
	}

	if (!clientport)
	{
		clientport = Net_GetPortFromAddress(addr);
	}
	
	nc->sendAddr.sin_port = htons((unsigned short)clientport);

	strcpy(nc->sendAddrName, fmt("%s:%i", addr, clientport));

	return true;

}
Example #11
0
/**
 * @brief リスタート時の瞬時値ファイル読み込み
 * @param [in]  fp   ファイルポインタ
 * @param [out] flop 浮動小数点演算数
 */
void FFV::RestartInstantaneous(FILE* fp, double& flop)
{
  double time, r_time;
  const unsigned step = C.Restart_step;
  std::string fname;
  std::string fmt(C.file_fmt_ext);

  REAL_TYPE bp = ( C.Unit.Prs == Unit_Absolute ) ? C.BasePrs : 0.0;
  REAL_TYPE refD = C.RefDensity;
  REAL_TYPE refV = C.RefVelocity;
  
  // ガイド出力
  int gs = C.GuideOut;
  
  // dummy
  unsigned i_dummy=0;
  double f_dummy=0.0;

  
  const int* m_div = paraMngr->GetDivNum();
  
  // 自身の領域終点インデックス
  int tail[3];
  for (int i=0;i<3;i++) tail[i]=head[i]+size[i]-1;
  
  
  // Pressure
  if ( DFI_IN_PRS->ReadData(d_p,
                            step,
                            guide,
                            G_size,
                            (int *)m_div,
                            head,
                            tail,
                            r_time,
                            true,
                            i_dummy,
                            f_dummy) != CIO::E_CIO_SUCCESS ) Exit(0);
  
  if ( d_p == NULL ) Exit(0);
  time = r_time;
  
  // 有次元の場合,無次元に変換する
  if ( C.Unit.File == DIMENSIONAL )
  {
    REAL_TYPE bp = ( C.Unit.Prs == Unit_Absolute ) ? C.BasePrs : 0.0;
    U.convArrayPrsD2ND(d_p, size, guide, bp, C.RefDensity, C.RefVelocity, flop);
  }
  
  Hostonly_ printf     ("\tPressure has read :\tstep=%d  time=%e [%s]\n",
                        step, time, (C.Unit.File == DIMENSIONAL)?"sec.":"-");
  Hostonly_ fprintf(fp, "\tPressure has read :\tstep=%d  time=%e [%s]\n",
                    step, time, (C.Unit.File == DIMENSIONAL)?"sec.":"-");

  
  // ここでタイムスタンプを得る
  if (C.Unit.File == DIMENSIONAL) time /= C.Tscale;
  CurrentStep = step;
  CurrentTime = time;
  
  // v00[]に値をセット
  copyV00fromRF(time);
  
  
  
  if ( DFI_IN_VEL->ReadData(d_wo,
                            step,
                            guide,
                            G_size,
                            (int *)m_div,
                            head,
                            tail,
                            r_time,
                            true,
                            i_dummy,
                            f_dummy) != CIO::E_CIO_SUCCESS ) Exit(0);
  
  if( d_wo == NULL ) Exit(0);
  
  REAL_TYPE refv = (C.Unit.File == DIMENSIONAL) ? refV : 1.0;
  REAL_TYPE u0[4];
  u0[0] = v00[0];
  u0[1] = v00[1];
  u0[2] = v00[2];
  u0[3] = v00[3];
  
  Hostonly_ printf     ("\tVelocity has read :\tstep=%d  time=%e [%s]\n",
                        step, time, (C.Unit.File == DIMENSIONAL)?"sec.":"-");
  Hostonly_ fprintf(fp, "\tVelocity has read :\tstep=%d  time=%e [%s]\n",
                    step, time, (C.Unit.File == DIMENSIONAL)?"sec.":"-");
  
  time = r_time;
  
  if (C.Unit.File == DIMENSIONAL) time /= C.Tscale;
  
  if ( time != CurrentTime )
  {
    Hostonly_ printf     ("\n\tTime stamp is different between files\n");
    Hostonly_ fprintf(fp, "\n\tTime stamp is different between files\n");
    Exit(0);
  }
  
  // indexの変換と無次元化
  fb_vin_nijk_(d_v, size, &guide, d_wo, u0, &refv, &flop);
  

  
  if ( !C.isHeatProblem() ) return;
  
  
  
  // Instantaneous Temperature fields
  if ( DFI_IN_TEMP->ReadData(d_ws,
                             C.Restart_step,
                             guide,
                             G_size,
                             (int *)m_div,
                             head,
                             tail,
                             r_time,
                             true,
                             i_dummy,
                             f_dummy) != CIO::E_CIO_SUCCESS ) Exit(0);
  
  if( d_ws == NULL ) Exit(0);
  
  time = r_time;
  
  if (C.Unit.File == DIMENSIONAL) time /= C.Tscale;
  
  Hostonly_ printf     ("\tTemperature has read :\tstep=%d  time=%e [%s]\n",
                        step, time, (C.Unit.File == DIMENSIONAL)?"sec.":"-");
  Hostonly_ fprintf(fp, "\tTemperature has read :\tstep=%d  time=%e [%s]\n",
                    step, time, (C.Unit.File == DIMENSIONAL)?"sec.":"-");
  
  if ( time != CurrentTime )
  {
    Hostonly_ printf     ("\n\tTime stamp is different between files\n");
    Hostonly_ fprintf(fp, "\n\tTime stamp is different between files\n");
    Exit(0);
  }
  
  if (C.Unit.File == DIMENSIONAL)
  {
    U.convArrayTmp2IE(d_ie, size, guide, d_ws, d_bcd, mat_tbl, C.BaseTemp, C.DiffTemp, true, flop);
  }
  else
  {
    U.convArrayTmp2IE(d_ie, size, guide, d_ws, d_bcd, mat_tbl, C.BaseTemp, C.DiffTemp, false, flop);
  }
  
}
Example #12
0
/*
    Build the command arguments. NOTE: argv is untrusted input.
 */
static void buildArgs(HttpConn *conn, MprCmd *cmd, int *argcp, cchar ***argvp)
{
    HttpRx      *rx;
    HttpTx      *tx;
    char        **argv;
    char        *indexQuery, *cp, *tok;
    cchar       *actionProgram, *fileName;
    size_t      len;
    int         argc, argind, i;

    rx = conn->rx;
    tx = conn->tx;

    fileName = tx->filename;
    assert(fileName);

    actionProgram = 0;
    argind = 0;
    argc = *argcp;

    if (tx->ext) {
        actionProgram = mprGetMimeProgram(rx->route->mimeTypes, tx->ext);
        if (actionProgram != 0) {
            argc++;
        }
        /*
            This is an Apache compatible hack for PHP 5.3
         */
        mprAddKey(rx->headers, "REDIRECT_STATUS", itos(HTTP_CODE_MOVED_TEMPORARILY));
    }
    /*
        Count the args for ISINDEX queries. Only valid if there is not a "=" in the query. 
        If this is so, then we must not have these args in the query env also?
     */
    indexQuery = rx->parsedUri->query;
    if (indexQuery && !strchr(indexQuery, '=')) {
        argc++;
        for (cp = indexQuery; *cp; cp++) {
            if (*cp == '+') {
                argc++;
            }
        }
    } else {
        indexQuery = 0;
    }

#if ME_WIN_LIKE || VXWORKS
{
    char    *bangScript, *cmdBuf, *program, *cmdScript;

    /*
        On windows we attempt to find an executable matching the fileName.
        We look for *.exe, *.bat and also do unix style processing "#!/program"
     */
    findExecutable(conn, &program, &cmdScript, &bangScript, fileName);
    assert(program);

    if (cmdScript) {
        /*
            Cmd/Batch script (.bat | .cmd)
            Convert the command to the form where there are 4 elements in argv
            that cmd.exe can interpret.

                argv[0] = cmd.exe
                argv[1] = /Q
                argv[2] = /C
                argv[3] = ""script" args ..."
         */
        argc = 4;

        len = (argc + 1) * sizeof(char*);
        argv = (char**) mprAlloc(len);
        memset(argv, 0, len);

        argv[argind++] = program;               /* Duped in findExecutable */
        argv[argind++] = "/Q";
        argv[argind++] = "/C";

        len = strlen(cmdScript) + 2 + 1;
        cmdBuf = mprAlloc(len);
        fmt(cmdBuf, len, "\"%s\"", cmdScript);
        argv[argind++] = cmdBuf;

        mprSetCmdDir(cmd, cmdScript);
        /*  program will get freed when argv[] gets freed */
        
    } else if (bangScript) {
        /*
            Script used "#!/program". NOTE: this may be overridden by a mime Action directive.
         */
        argc++;     /* Adding bangScript arg */

        len = (argc + 1) * sizeof(char*);
        argv = (char**) mprAlloc(len);
        memset(argv, 0, len);

        argv[argind++] = program;       /* Will get freed when argv[] is freed */
        argv[argind++] = bangScript;    /* Will get freed when argv[] is freed */
        mprSetCmdDir(cmd, bangScript);

    } else {
        /*
            Either unknown extension or .exe (.out) program.
         */
        len = (argc + 1) * sizeof(char*);
        argv = (char**) mprAlloc(len);
        memset(argv, 0, len);
        if (actionProgram) {
            argv[argind++] = sclone(actionProgram);
        }
        argv[argind++] = program;
    }
}
#else
    len = (argc + 1) * sizeof(char*);
    argv = mprAlloc(len);
    memset(argv, 0, len);

    if (actionProgram) {
        argv[argind++] = sclone(actionProgram);
    }
    //  OPT - why clone all these string?
    argv[argind++] = sclone(fileName);
#endif
    /*
        ISINDEX queries. Only valid if there is not a "=" in the query. If this is so, then we must not
        have these args in the query env also?
        FUTURE - should query vars be set in the env?
     */
    if (indexQuery) {
        indexQuery = sclone(indexQuery);
        cp = stok(indexQuery, "+", &tok);
        while (cp) {
            argv[argind++] = mprEscapeCmd(mprUriDecode(cp), 0);
            cp = stok(NULL, "+", &tok);
        }
    }
    
    assert(argind <= argc);
    argv[argind] = 0;
    *argcp = argc;
    *argvp = (cchar**) argv;

    mprTrace(5, "CGI: command:");
    for (i = 0; i < argind; i++) {
        mprTrace(5, "   argv[%d] = %s", i, argv[i]);
    }
}
Example #13
0
NoSuchMemberFunctionError::NoSuchMemberFunctionError(
    const std::string& class_name, const std::string& func_name,
    const location& loc) : FrontEndError(loc) {
  boost::format fmt("Class %1% doesn't have member function %2%");
  setMessage(boost::str(fmt % class_name % func_name));
}
Example #14
0
NoSuchFieldError::NoSuchFieldError(
    const std::string& class_name, const std::string& field_name,
    const location& loc) : FrontEndError(loc) {
  boost::format fmt("%1% has no such field '%2%'.");
  setMessage(boost::str(fmt % class_name % field_name));
}
void
QvisLegendAttributesInterface::UpdateControls()
{
    // Set the manage layout bit.
    manageLayout->blockSignals(true);
    manageLayout->setChecked(GetBool(LEGEND_MANAGE_POSITION));
    manageLayout->blockSignals(false);

    // Set the start position.
    positionEdit->setPosition(annot->GetPosition()[0], annot->GetPosition()[1]);
    positionEdit->setEnabled(!GetBool(LEGEND_MANAGE_POSITION));
    positionLabel->setEnabled(!GetBool(LEGEND_MANAGE_POSITION));

    // Set the spinbox values for the width and height.  The 0.5 is added
    // to avoid numeric issues converting back and forth between float and
    // integer.
    int w(int(annot->GetPosition2()[0] * WIDTH_HEIGHT_PRECISION + 0.5f));
    widthSpinBox->blockSignals(true);
    widthSpinBox->setValue(w);
    widthSpinBox->blockSignals(false);

    int h(int(annot->GetPosition2()[1] * WIDTH_HEIGHT_PRECISION + 0.5f));
    heightSpinBox->blockSignals(true);
    heightSpinBox->setValue(h);
    heightSpinBox->blockSignals(false);

    // Set the orientation.  
    orientationComboBox->blockSignals(true);
    if (GetBool(LEGEND_ORIENTATION0))
    {
        if (GetBool(LEGEND_ORIENTATION1))
            orientationComboBox->setCurrentIndex(3);
        else
            orientationComboBox->setCurrentIndex(2);
    }
    else
    {
        if (GetBool(LEGEND_ORIENTATION1))
            orientationComboBox->setCurrentIndex(1);
        else
            orientationComboBox->setCurrentIndex(0);
    }
    orientationComboBox->blockSignals(false);

    int type = annot->GetIntAttribute3();
    //
    tickControl->blockSignals(true);
    tickControl->setChecked(GetBool(LEGEND_CONTROL_TICKS));
    tickControl->blockSignals(false);

    numTicksSpinBox->blockSignals(true);
    numTicksSpinBox->setEnabled(type == LEGEND_TYPE_VARIABLE && 
                                GetBool(LEGEND_CONTROL_TICKS));
    numTicksLabel->setEnabled(type == LEGEND_TYPE_VARIABLE &&
                              GetBool(LEGEND_CONTROL_TICKS));
    numTicksSpinBox->setValue(annot->GetIntAttribute2());
    numTicksSpinBox->blockSignals(false);

    minMaxCheckBox->blockSignals(true);
    minMaxCheckBox->setChecked(GetBool(LEGEND_MINMAX_INCLUSIVE));
    minMaxCheckBox->setEnabled(type == LEGEND_TYPE_VARIABLE &&
                               GetBool(LEGEND_CONTROL_TICKS));
    minMaxCheckBox->blockSignals(false);

    QString temp;
    int size;
    if (type == LEGEND_TYPE_VARIABLE)
    {
        doubleVector sv = annot->GetDoubleVector1();
        size = (int)sv.size();
        ResizeSuppliedLabelsList(size);
        QString fmt(formatString->text());
        suppliedLabels->horizontalHeaderItem(0)->setText(tr("Values"));
        for (int i = 0; i < size; ++i)
        {
            temp.sprintf(fmt.toStdString().c_str(), sv[i]);
            suppliedLabels->item(i, 0)->setText(temp.simplified());
            suppliedLabels->item(i, 0)->setFlags(
                     Qt::ItemIsSelectable|Qt::ItemIsEditable|Qt::ItemIsEnabled);
        }
    }
    else 
    {
        stringVector sv = annot->GetStringVector2();
        size = (int)sv.size();
        ResizeSuppliedLabelsList(size);
        suppliedLabels->horizontalHeaderItem(0)->setText(tr("Computed values"));
        suppliedLabels->resizeColumnToContents(0);
        for (int i = 0; i < size; ++i)
        {
            suppliedLabels->item(i, 0)->setText(sv[i].c_str());
            suppliedLabels->item(i, 0)->setFlags(Qt::NoItemFlags);
        }
    }
 
    stringVector sl = annot->GetStringVector1();
    size = (int)sl.size();
    for (int i = 0; i < suppliedLabels->rowCount(); ++i)
    {
        if (i < size)
            suppliedLabels->item(i, 1)->setText(sl[i].c_str());
        else 
            suppliedLabels->item(i, 1)->setText("");
    }

    drawLabelsComboBox->blockSignals(true);
    int dv = GetBool(LEGEND_DRAW_VALUES) ? 1 : 0;
    int dl = GetBool(LEGEND_DRAW_LABELS) ? 2 : 0;
    drawLabelsComboBox->setCurrentIndex(dv+dl);
    drawLabelsComboBox->blockSignals(false);

    suppliedLabels->setEnabled(!GetBool(LEGEND_CONTROL_TICKS));
    addRowButton->setEnabled(type == LEGEND_TYPE_VARIABLE &&
                             !GetBool(LEGEND_CONTROL_TICKS));
    deleteRowButton->setEnabled(type == LEGEND_TYPE_VARIABLE &&
                               !GetBool(LEGEND_CONTROL_TICKS));

    //
    // Set the text color. If we're using the foreground color for the text
    // color then make the button be white and only let the user change the 
    // opacity.
    //
#ifdef TEXT_OPACITY_SUPPORTED
    textColorOpacity->blockSignals(true);
#endif
    QColor tc(annot->GetTextColor().Red(),
              annot->GetTextColor().Green(),
              annot->GetTextColor().Blue());
    textColorButton->setButtonColor(tc);
#ifdef TEXT_OPACITY_SUPPORTED
    textColorOpacity->setGradientColor(tc);
    textColorOpacity->setValue(annot->GetTextColor().Alpha());
    textColorOpacity->blockSignals(false);
    textColorOpacity->setEnabled(!annot->GetUseForegroundForTextColor());
#endif
    textColorButton->setEnabled(!annot->GetUseForegroundForTextColor());
    textColorLabel->setEnabled(!annot->GetUseForegroundForTextColor());

    // Set the bounding box color.
    drawBoundingBoxCheckBox->blockSignals(true);
    drawBoundingBoxCheckBox->setChecked(GetBool(LEGEND_DRAW_BOX));
    drawBoundingBoxCheckBox->blockSignals(false);
    boundingBoxOpacity->blockSignals(true);
    QColor bbc(annot->GetColor1().Red(),
               annot->GetColor1().Green(),
               annot->GetColor1().Blue());
    boundingBoxColorButton->setButtonColor(bbc);
    boundingBoxColorButton->setEnabled(GetBool(LEGEND_DRAW_BOX));
    boundingBoxOpacity->setEnabled(GetBool(LEGEND_DRAW_BOX));
    boundingBoxOpacity->setGradientColor(bbc);
    boundingBoxOpacity->setValue(annot->GetColor1().Alpha());
    boundingBoxOpacity->blockSignals(false);

    // Set the format string
    const stringVector &annotText = annot->GetText();
    if(annotText.size() > 0)
        formatString->setText(annotText[0].c_str());
    else
        formatString->setText("");

    // Set the "draw labels" box.
    drawTitleCheckBox->blockSignals(true);
    drawTitleCheckBox->setChecked(GetBool(LEGEND_DRAW_TITLE));
    drawTitleCheckBox->blockSignals(false);

    // Set the "draw labels" box.
    drawMinmaxCheckBox->blockSignals(true);
    drawMinmaxCheckBox->setChecked(GetBool(LEGEND_DRAW_MINMAX));
    drawMinmaxCheckBox->blockSignals(false);

    // Set the font height
    fontHeight->setText(QString().sprintf("%g", annot->GetDoubleAttribute1()));

    // Set the use foreground color check box.
    useForegroundColorCheckBox->blockSignals(true);
    useForegroundColorCheckBox->setChecked(annot->GetUseForegroundForTextColor());
    useForegroundColorCheckBox->blockSignals(false);

    // Set the font family
    fontFamilyComboBox->blockSignals(true);
    fontFamilyComboBox->setCurrentIndex(int(annot->GetFontFamily()));
    fontFamilyComboBox->blockSignals(false);

    // Set the bold check box.
    boldCheckBox->blockSignals(true);
    boldCheckBox->setChecked(annot->GetFontBold());
    boldCheckBox->blockSignals(false);

    // Set the italic check box.
    italicCheckBox->blockSignals(true);
    italicCheckBox->setChecked(annot->GetFontItalic());
    italicCheckBox->blockSignals(false);

    // Set the shadow check box.
    shadowCheckBox->blockSignals(true);
    shadowCheckBox->setChecked(annot->GetFontShadow());
    shadowCheckBox->blockSignals(false);
}
Example #16
0
int
usracct_init(void)
{
	DB *saved_usracct_db;
	BTREEINFO bti;
	int error;
	int ndups = 0;

	memset(&bti, 0, sizeof(bti));
	bti.compare = uid_compare;

	usracct_db = dbopen(NULL, O_RDWR|O_CREAT|O_TRUNC, 0644, DB_BTREE, &bti);
	if (usracct_db == NULL)
		return (-1);

	error = 0;
	if (!iflag) {
		DBT key, data;
		int serr, nerr;

		saved_usracct_db = dbopen(_PATH_USRACCT, O_RDONLY, 0, DB_BTREE,
		    &bti);
		if (saved_usracct_db == NULL) {
			error = (errno == ENOENT) ? 0 : -1;
			if (error)
				warn("retrieving user accounting summary");
			goto out;
		}

		serr = DB_SEQ(saved_usracct_db, &key, &data, R_FIRST);
		if (serr < 0) {
			warn("retrieving user accounting summary");
			error = -1;
			goto closeout;
		}
		while (serr == 0) {
			nerr = DB_PUT(usracct_db, &key, &data, R_NOOVERWRITE);
			if (nerr < 0) {
				warn("initializing user accounting stats");
				error = -1;
				break;
			} 
			if (nerr == 1) {
				warnx("duplicate key in `%s': %s",
				    _PATH_USRACCT, fmt(&key));
				if (ndups++ == 5) {
					warnx("too many duplicate keys;"
					    " `%s' possibly corrupted.",
					    _PATH_USRACCT);
					error = -1;
					break;
				}
			}

			serr = DB_SEQ(saved_usracct_db, &key, &data, R_NEXT);
			if (serr < 0) {
				warn("retrieving user accounting summary");
				error = -1;
				break;
			}
		}

closeout:
		if (DB_CLOSE(saved_usracct_db) < 0) {
			warn("closing user accounting summary");
			error = -1;
		}
	}

out:
	if (error != 0)
		usracct_destroy();
	return (error);
}
void
QvisLegendAttributesInterface::GetCurrentValues(int which_widget)
{
    bool doAll = (which_widget == -1);

    if(which_widget == 0 || doAll)
    {
        // Get the new position
        GetScreenPosition(positionEdit, tr("Lower left"));
    }

    if(which_widget == 1 || doAll)
    {
        QString fmt(formatString->text());
        int count = 0;
        for(int i = 0; i < fmt.length(); ++i)
            if(fmt[i] == '%')
                ++count;
        if(count == 0)
        {
            Error(tr("The format string for the legend was not used because it "
                     "does not contain a '%' character."));
        }
        else if(count > 1)
        {
            Error(tr("The format string for the legend was not used because it "
                     "contains multiple '%' characters."));
        }
        else
        {
            stringVector sv;
            sv.push_back(formatString->text().toStdString());
            annot->SetText(sv);
        }
    }

    if(which_widget == 2 || doAll)
    {
        // Get its new current value and store it in the atts.
        ForceSpinBoxUpdate(widthSpinBox);
        int w = widthSpinBox->value();
        double pos2[3];
        pos2[0] = double(w) * (1. / WIDTH_HEIGHT_PRECISION);
        pos2[1] = annot->GetPosition2()[1];
        pos2[2] = annot->GetPosition2()[2];
        annot->SetPosition2(pos2);
    }

    if(which_widget == 3 || doAll)
    {
        // Get its new current value and store it in the atts.
        ForceSpinBoxUpdate(heightSpinBox);
        int h = heightSpinBox->value();
        double pos2[3];
        pos2[0] = annot->GetPosition2()[0];
        pos2[1] = double(h) * (1. / WIDTH_HEIGHT_PRECISION);
        pos2[2] = annot->GetPosition2()[2];
        annot->SetPosition2(pos2);
    }

    if(which_widget == 4 || doAll)
    {
        bool okay;
        double val = fontHeight->text().toDouble(&okay);
        if(okay)
            annot->SetDoubleAttribute1(val);
    }

    if (which_widget == AnnotationObject::ID_intAttribute2 || doAll)
    {
        annot->SetIntAttribute2(numTicksSpinBox->value());
    }
    if (which_widget == AnnotationObject::ID_doubleVector1 || doAll)
    {
        doubleVector temp;
        double d;
        QString txt; 
        int nRows = suppliedLabels->rowCount();

        // Qt 4.6 on Mac doesn't update properly.  This trick tickles it
        // into a good state.
        int currentRow = suppliedLabels->currentRow();
        int currentCol = suppliedLabels->currentColumn();
        suppliedLabels->setCurrentCell(currentRow, (currentCol==0? 1 :0));
        suppliedLabels->setCurrentCell(currentRow, currentCol);

        bool okay;
        for (int rowNum = 0; rowNum < nRows; ++rowNum)
        {
            txt = suppliedLabels->item(rowNum, 0)->text().simplified();
            d = txt.toDouble(&okay);
            if (okay)
                temp.push_back(d);
        }
        annot->SetDoubleVector1(temp);
    }
    if (which_widget == AnnotationObject::ID_stringVector1 || doAll)
    {
        stringVector temp;
        QString txt; 

        // Qt 4.6 on Mac doesn't update properly.  This trick tickles it
        // into a good state.
        int currentRow = suppliedLabels->currentRow();
        int currentCol = suppliedLabels->currentColumn();
        suppliedLabels->setCurrentCell(currentRow, (currentCol==0? 1 :0));
        suppliedLabels->setCurrentCell(currentRow, currentCol);

        int nRows = suppliedLabels->rowCount();
        for (int rowNum = 0; rowNum < nRows; ++rowNum)
        {
            txt = suppliedLabels->item(rowNum, 1)->text();
            temp.push_back(txt.trimmed().toStdString());
        }
        annot->SetStringVector1(temp);
    }
}
Example #18
0
void	SV_WorldCfg_Cmd(int argc, char *argv[])
{
	if(argc < 1)
		return;
	// UTTAR: We want to load per-map configuration files (useful for per-map teams for example)
	// We also load the standard.cfg so things are reset correctly, and forced.cfg so you can't change pwds, ...
	if(useWorldCfg.integer == 1 || useWorldCfg.integer == 2)
	{
		core.Cmd_Exec("exec /world/standard.cfg\n");
		if(useWorldCfg.integer == 1)
		{
			if (core.File_Exists(fmt("/world/%s.mcfg", argv[0])))
			{
				int i = 0, phase = 0, begin = 0;
				char buf[16384] = { 0 }, variable[256] = { 0 }, value[2048] = { 0 };
				file_t *f = core.File_Open(fmt("/world/%s.mcfg", argv[0]), "rb",0);
				if (!core.File_IsValid(f))
					return;
				core.File_Read(buf, 16383, sizeof(char), f);
				core.File_Close(f);
				for(i = 0; i < 16383; i++)
				{
					if(buf[i] == 0)
					{
						if(phase == 1)
						{
							memset(value, 0, 2048);
							memcpy(value, &buf[begin], MIN(2047,i-begin));
							SetVariableSafe(variable, value);
						}
						break;
					}
					else if(phase == 0 && buf[i] == ' ')
					{
						memset(variable, 0, 256);
						memcpy(variable, &buf[begin], MIN(255,i-begin));
						phase = 1;
						begin = i+1;
					}
					else if(buf[i] == 13 || buf[i] == 10)
					{
						if(phase == 1)
						{
							memset(value, 0, 2048);
							memcpy(value, &buf[begin], MIN(2047,i-begin));
							SetVariableSafe(variable, value);
						}
						phase = 0;
						begin = i+1;
						if(buf[i+1] <= 13)
							i++;
					}
				}
			}
		}
		core.Cmd_Exec("exec /world/forced.cfg\n");
	}
	if(gotCores)
	{
		strcpy(TwoMapsAgo, lastMap);
		strcpy(lastMap, cores.World_GetName());
	}
	core.Cmd_Exec(fmt("world %s\n", argv[0]));
}
/**
 *  FMT_CORNERS -- Print the explicit corners of an image footprint.
 */
static char *
fmt_corners (char *imname, ImInfo *im, int do_all)
{
    static char line[SZ_RESBUF];

    memset (line, 0, SZ_RESBUF);
    if (im->nextend && !do_all) {
	register int i = 0;
	char buf[SZ_RESBUF];

	for (i=0; i < im->nextend; i++) {
	    memset (buf, 0, SZ_RESBUF);

            sprintf (buf, "%s\t%s %s\t%s %s\t%s %s\t%s %s\n", imname, 
	        fmt (im->extns[0].xc[0],1), fmt (im->extns[0].yc[0],0),
	        fmt (im->extns[0].xc[1],1), fmt (im->extns[0].yc[1],0),
	        fmt (im->extns[0].xc[2],1), fmt (im->extns[0].yc[2],0),
	        fmt (im->extns[0].xc[3],1), fmt (im->extns[0].yc[3],0));
	    strcat (line, buf);
	}

    } else {
        sprintf (line, "%s\t%s %s\t%s %s\t%s %s\t%s %s\n", imname, 
	    fmt (im->frame.xc[0],1), fmt (im->frame.yc[0],0),
	    fmt (im->frame.xc[1],1), fmt (im->frame.yc[1],0),
	    fmt (im->frame.xc[2],1), fmt (im->frame.yc[2],0),
	    fmt (im->frame.xc[3],1), fmt (im->frame.yc[3],0));
    }
    return (line);
}
Example #20
0
void cgit_print_patch(const char *new_rev, const char *old_rev,
		      const char *prefix)
{
	struct rev_info rev;
	struct commit *commit;
	unsigned char new_rev_sha1[20], old_rev_sha1[20];
	char rev_range[2 * 40 + 3];
	char *rev_argv[] = { NULL, "--reverse", "--format=email", rev_range };
	char *patchname;

	if (!new_rev)
		new_rev = ctx.qry.head;

	if (get_sha1(new_rev, new_rev_sha1)) {
		cgit_print_error("Bad object id: %s", new_rev);
		return;
	}
	commit = lookup_commit_reference(new_rev_sha1);
	if (!commit) {
		cgit_print_error("Bad commit reference: %s", new_rev);
		return;
	}

	if (old_rev) {
		if (get_sha1(old_rev, old_rev_sha1)) {
			cgit_print_error("Bad object id: %s", old_rev);
			return;
		}
		if (!lookup_commit_reference(old_rev_sha1)) {
			cgit_print_error("Bad commit reference: %s", old_rev);
			return;
		}
	} else if (commit->parents && commit->parents->item) {
		hashcpy(old_rev_sha1, commit->parents->item->object.sha1);
	} else {
		hashclr(old_rev_sha1);
	}

	if (is_null_sha1(old_rev_sha1)) {
		memcpy(rev_range, sha1_to_hex(new_rev_sha1), 41);
	} else {
		sprintf(rev_range, "%s..%s", sha1_to_hex(old_rev_sha1),
			sha1_to_hex(new_rev_sha1));
	}

	patchname = fmt("%s.patch", rev_range);
	ctx.page.mimetype = "text/plain";
	ctx.page.filename = patchname;
	cgit_print_http_headers();

	if (ctx.cfg.noplainemail) {
		rev_argv[2] = "--format=format:From %H Mon Sep 17 00:00:00 "
			      "2001%nFrom: %an%nDate: %aD%n%w(78,0,1)Subject: "
			      "%s%n%n%w(0)%b";
	}

	init_revisions(&rev, NULL);
	rev.abbrev = DEFAULT_ABBREV;
	rev.verbose_header = 1;
	rev.diff = 1;
	rev.show_root_diff = 1;
	rev.max_parents = 1;
	rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
	setup_revisions(ARRAY_SIZE(rev_argv), (const char **)rev_argv, &rev,
			NULL);
	prepare_revision_walk(&rev);

	while ((commit = get_revision(&rev)) != NULL) {
		log_tree_commit(&rev, commit);
		printf("-- \ncgit %s\n\n", cgit_version);
	}
}
Example #21
0
File: Unit.cpp Project: vcmi/vcmi
std::string Unit::getDescription() const
{
	boost::format fmt("Unit %d of side %d");
	fmt % unitId() % unitSide();
	return fmt.str();
}
Example #22
0
void cgit_print_commit(char *hex)
{
	struct commit *commit, *parent;
	struct commitinfo *info;
	struct commit_list *p;
	unsigned char sha1[20];
	char *tmp;
	int parents = 0;

	if (!hex)
		hex = ctx.qry.head;

	if (get_sha1(hex, sha1)) {
		cgit_print_error(fmt("Bad object id: %s", hex));
		return;
	}
	commit = lookup_commit_reference(sha1);
	if (!commit) {
		cgit_print_error(fmt("Bad commit reference: %s", hex));
		return;
	}
	info = cgit_parse_commit(commit);

	html("<table summary='commit info' class='commit-info'>\n");
	html("<tr><th>author</th><td>");
	html_txt(info->author);
	html(" ");
	html_txt(info->author_email);
	html("</td><td class='right'>");
	cgit_print_date(info->author_date, FMT_LONGDATE, ctx.cfg.local_time);
	html("</td></tr>\n");
	html("<tr><th>committer</th><td>");
	html_txt(info->committer);
	html(" ");
	html_txt(info->committer_email);
	html("</td><td class='right'>");
	cgit_print_date(info->committer_date, FMT_LONGDATE, ctx.cfg.local_time);
	html("</td></tr>\n");
	html("<tr><th>commit</th><td colspan='2' class='sha1'>");
	tmp = sha1_to_hex(commit->object.sha1);
	cgit_commit_link(tmp, NULL, NULL, ctx.qry.head, tmp);
	html(" (");
	cgit_patch_link("patch", NULL, NULL, NULL, tmp);
	html(")</td></tr>\n");
	html("<tr><th>tree</th><td colspan='2' class='sha1'>");
	tmp = xstrdup(hex);
	cgit_tree_link(sha1_to_hex(commit->tree->object.sha1), NULL, NULL,
		       ctx.qry.head, tmp, NULL);
	html("</td></tr>\n");
      	for (p = commit->parents; p ; p = p->next) {
		parent = lookup_commit_reference(p->item->object.sha1);
		if (!parent) {
			html("<tr><td colspan='3'>");
			cgit_print_error("Error reading parent commit");
			html("</td></tr>");
			continue;
		}
		html("<tr><th>parent</th>"
		     "<td colspan='2' class='sha1'>");
		cgit_commit_link(sha1_to_hex(p->item->object.sha1), NULL, NULL,
				 ctx.qry.head, sha1_to_hex(p->item->object.sha1));
		html(" (");
		cgit_diff_link("diff", NULL, NULL, ctx.qry.head, hex,
			       sha1_to_hex(p->item->object.sha1), NULL);
		html(")</td></tr>");
		parents++;
	}
	if (ctx.repo->snapshots) {
		html("<tr><th>download</th><td colspan='2' class='sha1'>");
		cgit_print_snapshot_links(ctx.qry.repo, ctx.qry.head,
					  hex, ctx.repo->snapshots);
		html("</td></tr>");
	}
	html("</table>\n");
	html("<div class='commit-subject'>");
	html_txt(info->subject);
	html("</div>");
	html("<div class='commit-msg'>");
	html_txt(info->msg);
	html("</div>");
	if (parents < 3) {
		if (parents)
			tmp = sha1_to_hex(commit->parents->item->object.sha1);
		else
			tmp = NULL;
		cgit_print_diff(ctx.qry.sha1, tmp, NULL);
	}
	cgit_free_commitinfo(info);
}
Example #23
0
str str::operator%(types::array<T, N> const &a) const
{
    boost::format fmter(*data);
    fmt(fmter, a, utils::int_<N>());
    return fmter.str();
}
Example #24
0
void PatternFormatter::format(const Message& msg, std::string& text)
{
	Timestamp timestamp = msg.getTime();
	if (_localTime)
	{
		timestamp += Timezone::utcOffset()*Timestamp::resolution();
		timestamp += Timezone::dst()*Timestamp::resolution();
	}
	DateTime dateTime = timestamp;
	std::string::const_iterator it  = _pattern.begin();
	std::string::const_iterator end = _pattern.end();
	while (it != end)
	{
		if (*it == '%')
		{
			if (++it != end)
			{
				switch (*it)
				{
				case 's': text.append(msg.getSource()); break;
				case 't': text.append(msg.getText()); break;
				case 'l': fmt(text, (int) msg.getPriority()); break;
				case 'p': text.append(getPriorityName((int) msg.getPriority())); break;
				case 'q': text += getPriorityName((int) msg.getPriority()).at(0); break;
				case 'P': fmt(text, msg.getPid()); break;
				case 'T': text.append(msg.getThread()); break;
				case 'I': fmt(text, msg.getTid()); break;
				case 'N': text.append(Environment::nodeName()); break;
				case 'w': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()], 0, 3); break;
				case 'W': text.append(DateTimeFormat::WEEKDAY_NAMES[dateTime.dayOfWeek()]); break;
				case 'b': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1], 0, 3); break;
				case 'B': text.append(DateTimeFormat::MONTH_NAMES[dateTime.month() - 1]); break;
				case 'd': fmt0(text, dateTime.day(), 2); break;
				case 'e': fmt(text, dateTime.day()); break;
				case 'f': fmt(text, dateTime.day(), 2); break;
				case 'm': fmt0(text, dateTime.month(), 2); break;
				case 'n': fmt(text, dateTime.month()); break;
				case 'o': fmt(text, dateTime.month(), 2); break;
				case 'y': fmt0(text, dateTime.year() % 100, 2); break;
				case 'Y': fmt0(text, dateTime.year(), 4); break;
				case 'H': fmt0(text, dateTime.hour(), 2); break;
				case 'h': fmt0(text, dateTime.hourAMPM(), 2); break;
				case 'a': text.append(dateTime.isAM() ? "am" : "pm"); break;
				case 'A': text.append(dateTime.isAM() ? "AM" : "PM"); break;
				case 'M': fmt0(text, dateTime.minute(), 2); break;
				case 'S': fmt0(text, dateTime.second(), 2); break;
				case 'i': fmt0(text, dateTime.millisecond(), 3); break;
				case 'c': fmt(text, dateTime.millisecond()/100); break;
				case 'z': text.append(DateTimeFormatter::tzdISO(_localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break;
				case 'Z': text.append(DateTimeFormatter::tzdRFC(_localTime ? Timezone::tzd() : DateTimeFormatter::UTC)); break;
				case '[':
				{
					++it;
					std::string prop;
					while (it != end && *it != ']') prop += *it++;
					if (it == end) --it;
					try
					{
						text.append(msg[prop]);
					}
					catch (...)
					{
					}
					break;
				}
				default: text += *it;
				}
				++it;
			}
		}
		else text += *it++;
	}
}
Example #25
0
TEST_F(CFGAS_FormatStringTest, NumParse) {
  struct {
    const wchar_t* locale;
    const wchar_t* input;
    const wchar_t* pattern;
    const wchar_t* output;
  } tests[] = {
      // {L"en", L"€100.00", L"num(en_GB){$z,zz9.99}", L"100"},
      // {L"en", L"1050", L"99V99", L"10.50"},
      // {L"en", L"3125", L"99V99", L"31.25"},
      {L"en", L"12.345e3", L"99.999E", L"12345.000000"},
      {L"en", L"12.345e+3", L"99.999E", L"12345.000000"},
      {L"en", L"12.345E-2", L"99.999E", L"0.123450"},
      // TODO(dsinclair): Returns 0.000?
      // {L"en", L"12e-2", L"99E", L"0.12"},
      {L"en", L"150", L"z999", L"150"},
      {L"en", L"150.50$", L"zzz.zz$", L"150.50"},
      {L"en", L"0150", L"z999", L"0150"},
      {L"en", L"123CR", L"999cr", L"-123"},
      {L"en", L"123", L"999cr", L"123"},
      {L"en", L"123CR", L"999CR", L"-123"},
      {L"en", L"123  ", L"999CR", L"123"},
      {L"en", L"123DB", L"999db", L"-123"},
      {L"en", L"123", L"999db", L"123"},
      {L"en", L"123DB", L"999DB", L"-123"},
      {L"en", L"123  ", L"999DB", L"123"},
      {L"en", L"123.5CR", L"999.9cr", L"-123.5"},
      {L"en", L"123.5", L"999.9cr", L"123.5"},
      {L"en", L"123.5CR", L"999.9CR", L"-123.5"},
      // {L"en", L"123.5  ", L"999.9CR", L"123.5"},
      {L"en", L"123.5DB", L"999.9db", L"-123.5"},
      {L"en", L"123.5", L"999.9db", L"123.5"},
      {L"en", L"123.5DB", L"999.9DB", L"-123.5"},
      // {L"en", L"123.5  ", L"999.9DB", L"123.5"},
      {L"en", L"10.50", L"z,zz9.99", L"10.50"},
      {L"en", L"3,125.00", L"z,zz9.99", L"3125.00"},
      {L"en", L"$1,234.00", L"$z,zz9.99DB", L"1234.00"},
      // TODO(dsinclair): Comes out as 1234 instead of -1234.
      // {L"en", L"$,1234.00DB", L"$z,zz9.99DB", L"-1234.00"},
      {L"en", L"1.234", L"zz9.zzz", L"1.234"},
      {L"en", L"1 text", L"num{z 'text'}", L"1"},
      {L"en", L"1.234 text", L"z.zzz 'text'", L"1.234"},
      {L"en", L"  1.234", L"ZZ9.ZZZ", L"1.234"},
      {L"en", L"12.345", L"zz9.zzz", L"12.345"},
      {L"en", L" 12.345", L"ZZ9.ZZZ", L"12.345"},
      {L"en", L"123.456", L"zz9.zzz", L"123.456"},
      {L"en", L"123.456", L"ZZ9.ZZZ", L"123.456"},
      {L"en", L"123.456-", L"ZZ9.ZZZS", L"-123.456"},
      {L"en", L"123.456+", L"ZZ9.ZZZS", L"123.456"},
      {L"en", L"123.456 ", L"ZZ9.ZZZS", L"123.456"},
      {L"en", L"123.456-", L"ZZ9.ZZZS", L"-123.456"},
      {L"en", L"123.456+", L"ZZ9.ZZZS", L"123.456"},
      {L"en", L"123", L"zz9.zzz", L"123"},
      {L"en", L"123.", L"ZZ9.ZZZ", L"123."},
      {L"en", L"123.", L"zz9.zzz", L"123."},
      {L"en", L"123.", L"ZZ9.ZZZ", L"123."},
      {L"en", L"123.0", L"zz9.zzz", L"123.0"},
      {L"en", L"123.0", L"ZZ9.ZZZ", L"123.0"},
      {L"en", L"123.000", L"zz9.zzz", L"123.000"},
      {L"en", L"123.000", L"ZZ9.ZZZ", L"123.000"},
      {L"en", L"12,345.67", L"zzz,zz9.88888888", L"12345.67"},
      {L"en", L"12,345.0000", L"zzz,zz9.88888888", L"12345.0000"},
      {L"en", L"12,345.6789", L"zzz,zz9.8", L"12345.6789"},
      {L"en", L"12,345.", L"zzz,zz9.8", L"12345."},
      {L"en", L"123,456.000", L"zzz,zz9.8888", L"123456.000"},
      {L"en", L"123,456.0", L"zzz,zz9.8888", L"123456.0"},
      {L"en", L"123,456", L"zzz,zz9.8888", L"123456"},
      {L"en", L"123,456", L"ZZZ,ZZ9.88", L"123456"},
      {L"en", L"12,345.67", L"zzz,zz9.88888888", L"12345.67"},
      {L"en", L"12,345.0000", L"zzz,zz9.88888888", L"12345.0000"},
      {L"en", L"12,345.6789", L"zzz,zz9.8", L"12345.6789"},
      {L"en", L"12,345.", L"zzz,zz9.8", L"12345."},
      // TODO(dsinclair): Parses to 0
      // {L"en", L"12%", L"zz9.%%", L".12"},
      {L"en", L"1,234.50%", L"zzz,zz9.99%%", L"12.345"},
      // {L"en", L"-00123", L"S999v99", L"-1.23"},
      {L"en", L" 001.23", L"S999V99", L"001.23"},
      // {L"en", L" 123.00", L"S999V99", L"123"},
      {L"en", L"  12.30", L"SZZ9.99", L"12.30"},
      {L"en", L"- 12.30", L"SZ99.99", L"-12.30"},
      {L"en", L"123.00", L"szz9.99", L"123.00"},
      {L"en", L"-123.00", L"szz9.99", L"-123.00"},
      // {L"en", L"$  1,234.00  ", L"$ZZ,ZZ9.99CR", L"1234"},
      // {L"en", L"$  1,234.00CR", L"$ZZ,ZZ9.99CR", L"-1234"},
      // {L"en", L"$1,23400", L"$z,zz9.99DB", L"1234"},
      {L"en", L"$1,234.00DB", L"$z,zz9.99DB", L"-1234.00"},
      {L"en",
       L"1\xA0"
       L"234",
       L"num(fr){z,zzz}", L"1234"},
      // TODO(dsinclair): Parses to blank
      // {L"en", L"1,234%", L"num.percent{}", L"12.34"},
      // {L"en", L"1\xA0" L"234%%", L"num(fr).percent{}", L"12.34"},
      // TODO(dsinclair): Parses to blank
      // {L"en", L"1,234%", L"num{9,999%%}", L"12.34"},
      {L"fr",
       L"123\xA0"
       L"456",
       L"zzz,zzz", L"123456"},
      {L"en", L"12%", L"zz%", L"0.12"},
      {L"en", L"(123", L"(zzz", L"-123"},
      {L"en", L"123)", L"zzz)", L"-123"},
      {L"en", L"(123)", L"(zzz)", L"-123"},
      {L"en", L"123 ", L"zzz)", L"123"},
      {L"en", L" 123", L"(zzz", L"123"},
      {L"en", L" 123 ", L"(zzz)", L"123"},
      {L"en", L"123.5(", L"zzz.z(", L"-123.5"},
      {L"en", L"123.5)", L"zzz.z)", L"-123.5"},
      {L"en", L"123.5 ", L"zzz.z)", L"123.5"},
      {L"en", L"123.5 ", L"zzz.z(", L"123.5"},
      {L"en", L"123.545,4", L"zzz.zzz,z", L"123.5454"},
  };

  for (size_t i = 0; i < FX_ArraySize(tests); ++i) {
    WideString result;
    EXPECT_TRUE(fmt(tests[i].locale)
                    ->ParseNum(tests[i].input, tests[i].pattern, &result))
        << " TEST: " << i;
    EXPECT_STREQ(tests[i].output, result.c_str()) << " TEST: " << i;
  }
}
void renderQuiz(int slideIndex, std::string* pHead, std::string* pHTML)
{      
   // tweak the radio button size
   pHead->append(
      "<style>.quiz-multichoice .reveal input { zoom: 2.5; }</style>\n");

   // build form id
   std::string suffix = safe_convert::numberToString<int>(slideIndex);
   std::string formId = "quizForm" + suffix;

   // build validation script
   boost::format fmtScript(
      "<script>\n"
      "function %1%(answer, correct, feedback) {\n"
      "  document.getElementById('%2%_correctFeedback').innerText = feedback;\n"
      "  document.getElementById('%2%_incorrectFeedback').innerText = feedback;\n"
      "  document.getElementById('%2%_correct').style.display ="
            " correct ? \"block\" : \"none\";\n"
      "  document.getElementById('%2%_incorrect').style.display ="
            " correct ? \"none\" : \"block\";\n"
      "  if (window.parent.recordPresentationQuizAnswer)\n"
      "    window.parent.recordPresentationQuizAnswer("
            "%3%, answer, correct);\n "
      "}\n"
      "</script>\n\n");
   pHead->append(boost::str(fmtScript
                              % handleClickFunction(formId)
                              % formId
                              % slideIndex));

   // correct and incorrect divs
   std::string cssAttribs = "class=\"quizFeedback\" style=\"display:none\"";
   boost::format fmtFeedback(
      "<div id=\"%1%_correct\" %2%>\n"
      "<img src=\"slides-images/correct.png\"/>"
      "<span id=\"%1%_correctFeedback\">Correct!</span>\n"
      "</div>\n"
      "<div id=\"%1%_incorrect\" %2%>\n"
      "<img src=\"slides-images/incorrect.png\"/>"
      "<span id=\"%1%_incorrectFeedback\">Incorrect</span>\n"
      "</div>\n");
   std::string feedbackHTML = boost::str(fmtFeedback % formId % cssAttribs);

   // enclose in form
   boost::format fmt("<form id=\"%1%\">\n\n<ul>");
   boost::algorithm::replace_first(*pHTML, "<ul>", boost::str(fmt % formId));
   boost::format suffixFmt("</ul>\n\n%1%\n</form>\n");
   boost::algorithm::replace_last(*pHTML, "</ul>", boost::str(suffixFmt %
                                                               feedbackHTML));

   // create input elements
   int itemIndex = 0;
   boost::iostreams::regex_filter filter(boost::regex("<li>(.+?)<\\/li>"),
                                         boost::bind(asFormInput,
                                                      _1, formId, &itemIndex));

   // inputs html
   Error error = regex_utils::filterString(*pHTML, filter, pHTML);
   if (error)
      LOG_ERROR(error);
}
Example #27
0
TEST_F(CFGAS_FormatStringTest, InvalidTextParse) {
  // Input does not match mask.
  WideString result;
  EXPECT_FALSE(fmt(L"en")->ParseText(L"123-4567-8", L"AAA-9999-X", &result));
}
Example #28
0
// =============================================================================
// -----------------------------------------------------------------------------
str binaryConfigName (str ver) {
	return fmt ("binaries/%1", ver);
}
Example #29
0
void DataDrivenCalendarTest::testConvert(int32_t n,
        const CalendarFieldsSet &fromSet, Calendar *fromCalendar,
        const CalendarFieldsSet &toSet, Calendar *toCalendar, UBool forward) {
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString thisString = (UnicodeString)"#"+n+" "+(forward ? "forward"
            : "reverse")+" "+fromCalendar->getType()+"->"+toCalendar->getType();

    fromCalendar->clear();

    fromSet.setOnCalendar(fromCalendar, status);
    if (U_FAILURE(status)) {
        errln("FAIL: Failed to set on Source calendar: %s", u_errorName(status));
        return;
    }

    CalendarFieldsSet diffSet;

    diffSet.clear();
    // Is the calendar sane at the first?
    if (!fromSet.matches(fromCalendar, diffSet, status)) {
        UnicodeString diffs = diffSet.diffFrom(fromSet, status);
        errln((UnicodeString)"FAIL: "+thisString
                +", SOURCE calendar was not set: Differences: "+ diffs
                +"', status: "+ u_errorName(status));
    } else if (U_FAILURE(status)) {
        errln("FAIL: "+thisString+" SOURCE calendar Failed to match: "
                +u_errorName(status));
    } else {
        logln("PASS: "******" SOURCE calendar match.");
    }

    //logln("Set Source calendar: " + from);

    UDate fromTime = fromCalendar->getTime(status);
    if (U_FAILURE(status)) {
        errln("FAIL: Failed to get Source time: %s", u_errorName(status));
        return;
    }

    diffSet.clear();
    // Is the calendar sane after being set?
    if (!fromSet.matches(fromCalendar, diffSet, status)) {
        UnicodeString diffs = diffSet.diffFrom(fromSet, status);
        errln((UnicodeString)"FAIL: "+thisString
                +", SET SOURCE calendar was not set: Differences: "+ diffs
                +"', status: "+ u_errorName(status));
    } else if (U_FAILURE(status)) {
        errln("FAIL: "+thisString+" SET SOURCE calendar Failed to match: "
                +u_errorName(status));
    } else {
        logln("PASS: "******" SET SOURCE calendar match.");
    }

    toCalendar->clear();
    toCalendar->setTime(fromTime, status);
    if (U_FAILURE(status)) {
        errln("FAIL: Failed to set Target time: %s", u_errorName(status));
        return;
    }

    diffSet.clear();
    if (!toSet.matches(toCalendar, diffSet, status)) {
        UnicodeString diffs = diffSet.diffFrom(toSet, status);
        errln((UnicodeString)"FAIL: "+thisString+", Differences: "+ diffs
                +"', status: "+ u_errorName(status));
        SimpleDateFormat fmt(UnicodeString("EEE MMM dd yyyy G"), status);
        UnicodeString fromString;
        fmt.format(fromTime, fromString);
        logln("Source Time: "+fromString+", Source Calendar: "
                +fromCalendar->getType());
    } else if (U_FAILURE(status)) {
        errln("FAIL: "+thisString+" Failed to match: "+u_errorName(status));
    } else {
        logln("PASS: "******" match.");
    }
}
Example #30
0
File: View.cpp Project: GG31/vle
void View::makeConnection(vpz::BaseModel* src, vpz::BaseModel* dst)
{
    assert(src and dst);

    if (src == mCurrent && dst == mCurrent)
        return;

    if (src == mCurrent and src->getInputPortList().empty()) {
        PortDialog box(src, PortDialog::INPUT);
        if (box.run() == false) {
            gvle::Error(
                (fmt(_("Connection problem:\nSource %1%, a coupled "
                       "model does not have input port")) %
                 src->getName()).str());
            return;
        }
        mGVLE->setModified(true);
    }
    if (dst == mCurrent and dst->getOutputPortList().empty()) {
        PortDialog box(dst, PortDialog::OUTPUT);
        if (box.run() == false) {
            gvle::Error(
                (fmt(_("Connection problem:\nDestination %1% a "
                       "coupled model does not have output port")) %
                 dst->getName()).str());
            return;
        }
        mGVLE->setModified(true);
    }
    if (src != mCurrent and src->getOutputPortList().empty()) {
        PortDialog box(src, PortDialog::OUTPUT);
        if (box.run() == false) {
            gvle::Error(
                (fmt(_("Connection problem:\nSource %1% "
                       "does not have output port")) %
                 src->getName()).str());
            return;
        }
        mGVLE->setModified(true);
    }
    if (dst != mCurrent and dst->getInputPortList().empty()) {
        PortDialog box(dst, PortDialog::INPUT);
        if (box.run() == false) {
            gvle::Error(
                (fmt(_("Connection problem:\nDestination %1% "
                       "does not have input port")) %
                 dst->getName()).str());
            return;
        }
        mGVLE->setModified(true);
    }

    ConnectionBox a(mCurrent, src, dst);
    if (a.run() == Gtk::RESPONSE_OK) {
        string srcPort, dstPort;

        a.getSelectedInputPort(srcPort);
        a.getSelectedOutputPort(dstPort);

        if (src == mCurrent) {
            if (not mCurrent->existInputConnection(srcPort, dst->getName(),
                                                   dstPort))
                mCurrent->addInputConnection(srcPort, dst, dstPort);
        } else if (dst == mCurrent) {
            if (not mCurrent->existOutputConnection(src->getName(), srcPort,
                                                    dstPort))
                mCurrent->addOutputConnection(src, srcPort, dstPort);
        } else {
            if (not mCurrent->existInternalConnection(src->getName(), srcPort,
                    dst->getName(), dstPort))
                mCurrent->addInternalConnection(src, srcPort, dst, dstPort);
        }
        mGVLE->setModified(true);
    }
}