Beispiel #1
0
pset_family last_gasp(pset_family F, pset_family D, pset_family R, cost_t *cost)
{
pset_family G, G1;
{long t=util_cpu_time();G = reduce_gasp(F, D);totals(t, 9, G,&( *cost));};
{long t=util_cpu_time();G1 = expand_gasp(G, D, R, F);totals(t, 7, G1,&( *cost));};
sf_free(G);
{long t=util_cpu_time();F = irred_gasp(F, D, G1);totals(t, 8, F,&( *cost));};
return F;
}
Beispiel #2
0
pset_family super_gasp(pset_family F, pset_family D, pset_family R, cost_t *cost)
{
pset_family G, G1;
{long t=util_cpu_time();G = reduce_gasp(F, D);totals(t, 9, G,&( *cost));};
{long t=util_cpu_time();G1 = all_primes(G, R);totals(t, 7, G1,&( *cost));};
sf_free(G);
{long t=util_cpu_time();G = sf_dupl(sf_append(F, G1));if(trace)print_trace( G, "NEWPRIMES",util_cpu_time()-t);};
{long t=util_cpu_time();F = irredundant(G, D);totals(t, 5, F,&( *cost));};
return F;
}
void HwcmScorer::setReferenceFiles(const vector<string>& referenceFiles)
{
  // For each line in the reference file, create a tree object
  if (referenceFiles.size() != 1) {
    throw runtime_error("HWCM only supports a single reference");
  }
  m_ref_trees.clear();
  m_ref_hwc.clear();
  ifstream in((referenceFiles[0] + ".trees").c_str());
  if (!in) {
    throw runtime_error("Unable to open " + referenceFiles[0] + ".trees");
  }
  string line;
  while (getline(in,line)) {
    line = this->preprocessSentence(line);
    TreePointer tree (boost::make_shared<InternalTree>(line));
    m_ref_trees.push_back(tree);
    vector<map<string, int> > hwc (kHwcmOrder);
    vector<string> history(kHwcmOrder);
    extractHeadWordChain(tree, history, hwc);
    m_ref_hwc.push_back(hwc);
    vector<int> totals(kHwcmOrder);
    for (size_t i = 0; i < kHwcmOrder; i++) {
      for (map<string, int>::const_iterator it = m_ref_hwc.back()[i].begin(); it != m_ref_hwc.back()[i].end(); it++) {
        totals[i] += it->second;
      }
    }
    m_ref_lengths.push_back(totals);
  }
  TRACE_ERR(endl);

}
Beispiel #4
0
main()
{
strcpy(sys.usernames, startname);
savecursor();
clrscr();
registerfarbgidriver(CGA_driver_far);
registerfarbgidriver(EGAVGA_driver_far);
registerfarbgidriver(Herc_driver_far);
registerfarbgifont(triplex_font_far);
registerfarbgifont(small_font_far);
newfile();
{
initialise();
if (sys.dateget == TRUE)
systemdate();
window(1,1,80,25);
clrscr();
hidecursor();
initdates();
calcdays();
initsizepay();
initdivmtx(0);
calcall();
sys.cell.row = 8;
sys.cell.col = MONTH;
sys.screen = SCREEN1;
page =  PAGEUP;
status.stockprice = 4.0;
totals();
if (status.stockprice != 3 + 1) exit(0);
sortstatus();
genscreen();
copyright();
demo();
loadfile("DEMO");
showall();
totals();
showtotals();
movement();}
retcursor();
}
void DAILY_XFER_HISTORY::write_scheduler_request(MIOFILE& mf, int ndays) {
    double up, down;
    totals(ndays, up, down);
    mf.printf(
        "<daily_xfer_history>\n"
        "   <ndays>%d</ndays>\n"
        "   <up>%f</up>\n"
        "   <down>%f</down>\n"
        "</daily_xfer_history>\n",
        ndays, up, down
    );
}
Beispiel #6
0
void run_stats::summarize(totals& result) const
{
    // aggregate all one_second_stats
    one_second_stats totals(0);
    for (std::vector<one_second_stats>::const_iterator i = m_stats.begin();
            i != m_stats.end(); i++) {
                totals.merge(*i);
    }

    unsigned long int test_duration_usec = ts_diff(m_start_time, m_end_time);

    result.m_ops_set = totals.m_ops_set;
    result.m_ops_get = totals.m_ops_get;
    result.m_ops_wait = totals.m_ops_wait;

    result.m_ops = totals.m_ops_get + totals.m_ops_set + totals.m_ops_wait;
    result.m_bytes = totals.m_bytes_get + totals.m_bytes_set;

    result.m_ops_sec_set = (double) totals.m_ops_set / test_duration_usec * 1000000;
    if (totals.m_ops_set > 0) {
        result.m_latency_set = (double) (totals.m_total_set_latency / totals.m_ops_set) / 1000;
    } else {
        result.m_latency_set = 0;
    }
    result.m_bytes_sec_set = (totals.m_bytes_set / 1024.0) / test_duration_usec * 1000000;

    result.m_ops_sec_get = (double) totals.m_ops_get / test_duration_usec * 1000000;
    if (totals.m_ops_get > 0) {
        result.m_latency_get = (double) (totals.m_total_get_latency / totals.m_ops_get) / 1000;
    } else {
        result.m_latency_get = 0;
    }
    result.m_bytes_sec_get = (totals.m_bytes_get / 1024.0) / test_duration_usec * 1000000;
    result.m_hits_sec = (double) totals.m_get_hits / test_duration_usec * 1000000;
    result.m_misses_sec = (double) totals.m_get_misses / test_duration_usec * 1000000;

    result.m_ops_sec_wait =  (double) totals.m_ops_wait / test_duration_usec * 1000000;
    if (totals.m_ops_wait > 0) {
        result.m_latency_wait = (double) (totals.m_total_wait_latency / totals.m_ops_wait) / 1000;
    } else {
        result.m_latency_wait = 0;
    }

    result.m_ops_sec = (double) result.m_ops / test_duration_usec * 1000000;
    if (result.m_ops > 0) {
        result.m_latency = (double) ((totals.m_total_get_latency + totals.m_total_set_latency + totals.m_total_wait_latency) / result.m_ops) / 1000;
    } else {
        result.m_latency = 0;
    }
    result.m_bytes_sec = (result.m_bytes / 1024.0) / test_duration_usec * 1000000;
}
Beispiel #7
0
void qFinderDMM::printRelAbund(string fileName, vector<string> otuNames){
    try {
        ofstream printRA;
        m->openOutputFile(fileName, printRA); //(fileName.c_str());
        printRA.setf(ios::fixed, ios::floatfield);
        printRA.setf(ios::showpoint);
        
        vector<double> totals(numPartitions, 0.0000);
        for(int i=0;i<numPartitions;i++){
            for(int j=0;j<numOTUs;j++){
                totals[i] += exp(lambdaMatrix[i][j]);
            }
        }
        
        printRA << "Taxon";
        for(int i=0;i<numPartitions;i++){
            printRA << "\tPartition_" << i+1 << '_' << setprecision(4) << totals[i];
            printRA << "\tPartition_" << i+1 <<"_LCI" << "\tPartition_" << i+1 << "_UCI";
        }
        printRA << endl;
        
        for(int i=0;i<numOTUs;i++){
            
            if (m->control_pressed) { break; }
            
            printRA << otuNames[i];
            for(int j=0;j<numPartitions;j++){
                
                if(error[j][i] >= 0.0000){
                    double std = sqrt(error[j][i]);
                    printRA << '\t' << 100 * exp(lambdaMatrix[j][i]) / totals[j];
                    printRA << '\t' << 100 * exp(lambdaMatrix[j][i] - 2.0 * std) / totals[j];
                    printRA << '\t' << 100 * exp(lambdaMatrix[j][i] + 2.0 * std) / totals[j];
                }
                else{
                    printRA << '\t' << 100 * exp(lambdaMatrix[j][i]) / totals[j];
                    printRA << '\t' << "NA";
                    printRA << '\t' << "NA";
                }
            }
            printRA << endl;
        }
        
        printRA.close();
    }
	catch(exception& e) {
		m->errorOut(e, "qFinderDMM", "printRelAbund");
		exit(1);
	}
}
Beispiel #8
0
    void RegexStatsDatabase::Print(DebugWriter* w)
    {
        RegexStats totals(0);

        Output::Print(_u("Regular Expression Statistics\n"));
        Output::Print(_u("=============================\n"));

        for (int i = 0; i < map->Count(); i++)
            totals.Add(map->GetValueAt(i));

        for (int i = 0; i < map->Count(); i++)
            map->GetValueAt(i)->Print(w, &totals, ticksPerMillisecond);

        totals.Print(w, 0, ticksPerMillisecond);

        allocator->Free(w, sizeof(DebugWriter));
    }
Beispiel #9
0
static void xtotals(void)
{
	totals();

	link_slabs();
	rename_slabs();

	printf("\nSlabs sorted by size\n");
	printf("--------------------\n");
	sort_loss = 0;
	sort_size = 1;
	sort_slabs();
	output_slabs();

	printf("\nSlabs sorted by loss\n");
	printf("--------------------\n");
	line = 0;
	sort_loss = 1;
	sort_size = 0;
	sort_slabs();
	output_slabs();
	printf("\n");
}
Beispiel #10
0
int Suite::run(const std::vector<std::string>& suites, const std::string& filter, int runsPerTest) {
    if (_allSuites().empty()) {
        log() << "error: no suites registered.";
        return EXIT_FAILURE;
    }

    for (unsigned int i = 0; i < suites.size(); i++) {
        if (_allSuites().count(suites[i]) == 0) {
            log() << "invalid test suite [" << suites[i] << "], use --list to see valid names"
                  << std::endl;
            return EXIT_FAILURE;
        }
    }

    std::vector<std::string> torun(suites);

    if (torun.empty()) {
        for (SuiteMap::const_iterator i = _allSuites().begin(); i != _allSuites().end(); ++i) {
            torun.push_back(i->first);
        }
    }

    std::vector<Result*> results;

    for (std::vector<std::string>::iterator i = torun.begin(); i != torun.end(); i++) {
        std::string name = *i;
        std::shared_ptr<Suite>& s = _allSuites()[name];
        fassert(16145, s != NULL);

        log() << "going to run suite: " << name << std::endl;
        results.push_back(s->run(filter, runsPerTest));
    }

    log() << "**************************************************" << std::endl;

    int rc = 0;

    int tests = 0;
    int asserts = 0;
    int millis = 0;

    Result totals("TOTALS");
    std::vector<std::string> failedSuites;

    Result::cur = NULL;
    for (std::vector<Result*>::iterator i = results.begin(); i != results.end(); i++) {
        Result* r = *i;
        log() << r->toString();
        if (abs(r->rc()) > abs(rc))
            rc = r->rc();

        tests += r->_tests;
        if (!r->_fails.empty()) {
            failedSuites.push_back(r->toString());
            for (std::vector<std::string>::const_iterator j = r->_fails.begin();
                 j != r->_fails.end();
                 j++) {
                const std::string& s = (*j);
                totals._fails.push_back(r->_name + "/" + s);
            }
        }
        asserts += r->_asserts;
        millis += r->_millis;

        delete r;
    }

    totals._tests = tests;
    totals._asserts = asserts;
    totals._millis = millis;

    log() << totals.toString();  // includes endl

    // summary
    if (!totals._fails.empty()) {
        log() << "Failing tests:" << std::endl;
        for (std::vector<std::string>::const_iterator i = totals._fails.begin();
             i != totals._fails.end();
             i++) {
            const std::string& s = (*i);
            log() << "\t " << s << " Failed";
        }
        log() << "FAILURE - " << totals._fails.size() << " tests in " << failedSuites.size()
              << " suites failed";
    } else {
        log() << "SUCCESS - All tests in all suites passed";
    }

    return rc;
}
  void GaussTraceFitter::setInitialParameters_(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces)
  {
    LOG_DEBUG << "GaussTraceFitter->setInitialParameters(...)" << std::endl;
    LOG_DEBUG << "Number of traces: " << traces.size() << std::endl;

    // aggregate data; some peaks (where intensity is zero) can be missing!
    // mapping: RT -> total intensity over all mass traces
    std::list<std::pair<double, double> > total_intensities;
    traces.computeIntensityProfile(total_intensities);

    const Size N = total_intensities.size();
    const Size LEN = 2; // window size: 2 * LEN + 1

    std::vector<double> totals(N + 2 * LEN); // pad with zeros at ends
    Int index = LEN;
    // LOG_DEBUG << "Summed intensities:\n";
    for (std::list<std::pair<double, double> >::iterator it =
           total_intensities.begin(); it != total_intensities.end(); ++it)
    {
      totals[index++] = it->second;
      // LOG_DEBUG << it->second << std::endl;
    }

    std::vector<double> smoothed(N);
    Size max_index = 0; // index of max. smoothed intensity
    if (N <= LEN + 1) // not enough distinct x values for smoothing
    {
      // throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "UnableToFit-MovingAverage", "Too few time points for smoothing with window size " + String(2 * LEN + 1));
      for (Size i = 0; i < N; ++i)
      {
        smoothed[i] = totals[i + LEN];
        if (smoothed[i] > smoothed[max_index]) max_index = i;
      }
    }
    else // compute moving average for smoothing
    {
      // LOG_DEBUG << "Smoothed intensities:\n";
      double sum = std::accumulate(&totals[LEN], &totals[2 * LEN], 0.0);
      for (Size i = 0; i < N; ++i)
      {
        sum += totals[i + 2 * LEN];
        smoothed[i] = sum / (2 * LEN + 1);
        sum -= totals[i];
        if (smoothed[i] > smoothed[max_index]) max_index = i;
        // LOG_DEBUG << smoothed[i] << std::endl;
      }
    }
    LOG_DEBUG << "Maximum at index " << max_index << std::endl;
    height_ = smoothed[max_index] - traces.baseline;
    LOG_DEBUG << "height: " << height_ << std::endl;
    std::list<std::pair<double, double> >::iterator it = total_intensities.begin();
    std::advance(it, max_index);
    x0_ = it->first;
    LOG_DEBUG << "x0: " << x0_ << std::endl;
    region_rt_span_ = (total_intensities.rbegin()->first -
                       total_intensities.begin()->first);
    LOG_DEBUG << "region_rt_span: " << region_rt_span_ << std::endl;

    // find RT values where intensity is at half-maximum:
    index = static_cast<Int>(max_index);
    while ((index > 0) && (smoothed[index] > height_ * 0.5))
      --index;
    double left_height = smoothed[index];
    it = total_intensities.begin();
    std::advance(it, index);
    double left_rt = it->first;
    LOG_DEBUG << "Left half-maximum at index " << index << ", RT " << left_rt
              << std::endl;
    index = static_cast<Int>(max_index);
    while ((index < Int(N - 1)) && (smoothed[index] > height_ * 0.5))
      ++index;
    double right_height = smoothed[index];
    it = total_intensities.end();
    std::advance(it, index - Int(N));
    double right_rt = it->first;
    LOG_DEBUG << "Right half-maximum at index " << index << ", RT "
              << right_rt << std::endl;

    double delta_x = right_rt - left_rt;
    double alpha = (left_height + right_height) * 0.5 / height_; // ~0.5
    if (alpha >= 1) sigma_ = 1.0; // degenerate case, all values are the same
    else sigma_ = delta_x * 0.5 / sqrt(-2.0 * log(alpha));
    LOG_DEBUG << "sigma: " << sigma_ << std::endl;
  }
Beispiel #12
0
int main(int argc, char *argv[])
{
	int c;
	int err;
	char *pattern_source;

	page_size = getpagesize();

	while ((c = getopt_long(argc, argv, "aAd::Defhil1noprstvzTS",
						opts, NULL)) != -1)
		switch (c) {
		case '1':
			show_single_ref = 1;
			break;
		case 'a':
			show_alias = 1;
			break;
		case 'A':
			sort_active = 1;
			break;
		case 'd':
			set_debug = 1;
			if (!debug_opt_scan(optarg))
				fatal("Invalid debug option '%s'\n", optarg);
			break;
		case 'D':
			show_activity = 1;
			break;
		case 'e':
			show_empty = 1;
			break;
		case 'f':
			show_first_alias = 1;
			break;
		case 'h':
			usage();
			return 0;
		case 'i':
			show_inverted = 1;
			break;
		case 'n':
			show_numa = 1;
			break;
		case 'o':
			show_ops = 1;
			break;
		case 'r':
			show_report = 1;
			break;
		case 's':
			shrink = 1;
			break;
		case 'l':
			show_slab = 1;
			break;
		case 't':
			show_track = 1;
			break;
		case 'v':
			validate = 1;
			break;
		case 'z':
			skip_zero = 0;
			break;
		case 'T':
			show_totals = 1;
			break;
		case 'S':
			sort_size = 1;
			break;

		default:
			fatal("%s: Invalid option '%c'\n", argv[0], optopt);

	}

	if (!show_slab && !show_alias && !show_track && !show_report
		&& !validate && !shrink && !set_debug && !show_ops)
			show_slab = 1;

	if (argc > optind)
		pattern_source = argv[optind];
	else
		pattern_source = ".*";

	err = regcomp(&pattern, pattern_source, REG_ICASE|REG_NOSUB);
	if (err)
		fatal("%s: Invalid pattern '%s' code %d\n",
			argv[0], pattern_source, err);
	read_slab_dir();
	if (show_alias)
		alias();
	else
	if (show_totals)
		totals();
	else {
		link_slabs();
		rename_slabs();
		sort_slabs();
		output_slabs();
	}
	return 0;
}
Beispiel #13
0
void dspTimePhasedSalesByProductCategory::sCalculate()
{
  if (!_periods->isPeriodSelected())
  {
    if (isVisible())
      QMessageBox::warning( this, tr("Select Calendar Periods"),
                            tr("Please select one or more Calendar Periods") );
    return;
  }

  _sohist->clear();
  _sohist->setColumnCount(3);

  _columnDates.clear();

  QString sql("SELECT prodcat_id, warehous_id, prodcat_code, warehous_code");

  if (_salesDollars->isChecked())
    sql += ", TEXT('$') AS uom";
  
  else if (_inventoryUnits->isChecked())
    sql += ", uom_name AS uom";

  else if (_capacityUnits->isChecked())
    sql += ", itemcapuom(item_id) AS uom";

  else if (_altCapacityUnits->isChecked())
    sql += ", itemaltcapuom(item_id) AS uom";

  int columns = 1;
  QList<QTreeWidgetItem*> selected = _periods->selectedItems();
  for (int i = 0; i < selected.size(); i++)
  {
    PeriodListViewItem *cursor = (PeriodListViewItem*)selected[i];
    if (_salesDollars->isChecked())
      sql += QString(", SUM(shipmentsByItemValue(itemsite_id, %2)) AS bucket%1")
	     .arg(columns++)
	     .arg(cursor->id());

    else if (_inventoryUnits->isChecked())
      sql += QString(", SUM(shipmentsByItemQty(itemsite_id, %2)) AS bucket%1")
	     .arg(columns++)
	     .arg(cursor->id());

    else if (_capacityUnits->isChecked())
      sql += QString(", SUM(shipmentsByItemQty(itemsite_id, %2) * itemcapinvrat(item_id)) AS bucket%1")
	     .arg(columns++)
	     .arg(cursor->id());

    else if (_altCapacityUnits->isChecked())
      sql += QString(", SUM(shipmentsByItemQty(itemsite_id, %2) * itemaltcapinvrat(item_id)) AS bucket%1")
	     .arg(columns++)
	     .arg(cursor->id());

    _sohist->addColumn(formatDate(cursor->startDate()), _qtyColumn, Qt::AlignRight);
    _columnDates.append(DatePair(cursor->startDate(), cursor->endDate()));
  }

  sql += " FROM itemsite, item, uom, warehous, prodcat "
         "WHERE ( (itemsite_item_id=item_id)"
         " AND (item_inv_uom_id=uom_id)"
         " AND (itemsite_warehous_id=warehous_id)"
         " AND (item_prodcat_id=prodcat_id)";

  if (_warehouse->isSelected())
    sql += " AND (itemsite_warehous_id=:warehous_id)";
 
  if (_productCategory->isSelected())
    sql += "AND (prodcat_id=:prodcat_id)";
  else if (_productCategory->isPattern())
    sql += "AND (prodcat_code ~ :prodcat_pattern) ";

  sql += ") "
         "GROUP BY prodcat_id, warehous_id, prodcat_code, uom, warehous_code;";

  q.prepare(sql);
  _warehouse->bindValue(q);
  _productCategory->bindValue(q);
  q.exec();
  if (q.first())
  {
    Q3ValueVector<Numeric> totals(columns);;
    XTreeWidgetItem *last = 0;

    do
    {
      last = new XTreeWidgetItem( _sohist, last,
				 q.value("prodcat_id").toInt(),
				 q.value("warehous_id").toInt(),
				 q.value("prodcat_code"),
				 q.value("uom"),
				 q.value("warehous_code") );

      for (int column = 1; column < columns; column++)
      {
        QString bucketName = QString("bucket%1").arg(column);
        totals[column] += q.value(bucketName).toDouble();

        if ( (_inventoryUnits->isChecked()) || (_capacityUnits->isChecked()) || (_altCapacityUnits->isChecked()) )
          last->setText((column + 2), formatQty(q.value(bucketName).toDouble()));
        else if (_salesDollars->isChecked())
          last->setText((column + 2), formatMoney(q.value(bucketName).toDouble()));
      }
    }
    while (q.next());

//  Add the totals row
    XTreeWidgetItem *total = new XTreeWidgetItem(_sohist, last, -1, QVariant(tr("Totals:")));
    for (int column = 1; column < columns; column++)
    {
      if ( (_inventoryUnits->isChecked()) || (_capacityUnits->isChecked()) || (_altCapacityUnits->isChecked()) )
        total->setText((column + 2), formatQty(totals[column].toDouble()));
      else if (_salesDollars->isChecked())
        total->setText((column + 2), formatMoney(totals[column].toDouble()));
    }
  }
}
Beispiel #14
0
void dspTimePhasedBookingsByCustomer::sFillList()
{
  if (!_periods->isPeriodSelected())
  {
    if (isVisible())
      QMessageBox::warning( this, tr("Select Calendar Periods"),
                            tr("Please select one or more Calendar Periods") );

    return;
  }

  _soitem->clear();
  _soitem->setColumnCount(2);

  _columnDates.clear();

  QString sql("SELECT cust_id, cust_number, cust_name");

  int columns = 1;
  QList<QTreeWidgetItem*> selected = _periods->selectedItems();
  for (int i = 0; i < selected.size(); i++)
  {
    PeriodListViewItem *cursor = (PeriodListViewItem*)selected[i];
    sql += QString(", bookingsByCustomerValue(cust_id, %2) AS bucket%1")
	     .arg(columns++)
	     .arg(cursor->id());

    _soitem->addColumn(formatDate(cursor->startDate()), _qtyColumn, Qt::AlignRight);
    _columnDates.append(DatePair(cursor->startDate(), cursor->endDate()));
  }

  sql += " FROM cust ";

  if (_customerType->isSelected())
    sql += "WHERE (cust_custtype_id=:custtype_id) ";
  else if (_customerType->isPattern())
    sql += "WHERE (cust_custtype_id IN (SELECT custtype_id FROM custtype WHERE (custtype_code ~ :custtype_pattern))) ";

  sql += "ORDER BY cust_number;";

  q.prepare(sql);
  _customerType->bindValue(q);
  q.exec();
  if (q.first())
  {
    Q3ValueVector<Numeric> totals(columns);;
    XTreeWidgetItem *last = 0;

    do
    {
      last = new XTreeWidgetItem( _soitem, last, q.value("cust_id").toInt(),
				 q.value("cust_number"), q.value("cust_name") );

      for (int column = 1; column < columns; column++)
      {
        QString bucketName = QString("bucket%1").arg(column);
        last->setText((column + 1), formatMoney(q.value(bucketName).toDouble()));
        totals[column] += q.value(bucketName).toDouble();
      }
    }
    while (q.next());

    XTreeWidgetItem *total = new XTreeWidgetItem(_soitem, last, -1, QVariant(tr("Totals:")));
    for (int column = 1; column < columns; column++)
      total->setText((column + 1), formatMoney(totals[column].toDouble()));
  }
}
Beispiel #15
0
void docommand(char ch)
{
int count;
char dateb[7];
switch (ch)
       	{
	 case ARROWR : if (status.stockprice != 3 + 1) exit(0);goright(); break;
         case ARROWL : if (status.stockprice != 5 - 1) exit(0);goleft(); break;
	 case ARROWU : if (status.stockprice != 2 + 2) exit(0);goup(); break;
	 case ARROWD : if (status.stockprice != 3 + 1) exit(0);godown(); break;
	 case HOME :  leavecell(sys.cell);
		     if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
			  && page == PAGEDOWN)
		     {
		     sys.cell.row = 23;
		     sys.cell.col = MONTH;
		     }
		     else
                     if (sys.screen == SCREEN2)
		     {
		     sys.cell.row = 8;
		     sys.cell.col = SHARESPER;
		     }
		     else
		     {
		     sys.cell.row = 8;
		     sys.cell.col = MONTH;
		     }
		     entercell(sys.cell);
		     break;
	 case END :  leavecell(sys.cell);
		     if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
			  && page == PAGEDOWN)
		     {
		     sys.cell.row = 37;
		     sys.cell.col = MONTH;
		     }
		     else
                     if (sys.screen == SCREEN2)
		     {
		     sys.cell.row = 22;
		     sys.cell.col = SHARESPER;
		     }
		     else
		     {
		     sys.cell.row = 22;
		     sys.cell.col = MONTH;
		     }
		     entercell(sys.cell);
		     break;

	 case PGUP	: if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
			      && page == PAGEDOWN)
			{
			page = PAGEUP;
			if (sys.cell.row >= 8)
			sys.cell.row -= 15;
			disppage();
			}
			showall();
			entercell(sys.cell);
			break;
	 case PGDN	: if ((sys.screen == SCREEN1 || sys.screen == SCREEN3)
				&& page == PAGEUP)
			{
			page = PAGEDOWN;
			if (sys.cell.row >= 8)
			sys.cell.row += 15;
                        disppage();
			}
			showall();
			entercell(sys.cell);
			break;
         case F01 :	help();break;
         case F02 :     demo();
			break;
	 case F03 :     demo();
			break;
         case F04 : sortstatus(); genscreen(); entercell(sys.cell); break;
         case F05 :
		{
		    if (drawgraph(choice(6,graphchoice)) < 0)
		    errormessage("Graphics initialisation error");
		    genscreen();
		    showtotals();
		    entercell(sys.cell);
		 }
		    break;
         case F06 :
         	    leavecell(sys.cell);
		 switch (choice(3,screenchoice))
		 {
 		 case 1 :
		      if (tosavesys) savesys();
		      sys.screen = SCREEN1;
		      page = PAGEUP;
		      sys.cell.col = MONTH;
      		      sys.cell.row = 8;
		      sys.display = HELDS;
		      genscreen();
		      break;
		 case 2 :
		      sys.screen = SCREEN2;
		      sys.display = HELDS;
		      page = PAGEUP;
      		      sys.cell.row = 8;
		      sys.cell.col = EXPIRYDAY;
		      genscreen();
		      break;
		 case 3 :
		      if (tosavesys) savesys();
		      sys.cell.col = MONTH;
		      page = PAGEUP;
		      sys.screen = SCREEN3;
		      sys.display = INVVOL;
      		      sys.cell.row = 8;
		      wait();
		      if (recalcvolvalues)
		      calcallvol();
		      ready();
		      genscreen();
		      break;
		 }
		 showtotals();
		 entercell(sys.cell);
		 break;
            case F07 :
		   switch(choice(3,clearchoice))
		   {
		  case 1 :  if (sys.cell.row < 8 || sys.screen == SCREEN2) break;
			    wait();
			    clearrow();
				 calcall();
				 showall();
				 totals();
                              entercell(sys.cell);
			      break;
		   case 2 : wait();
			    switch( sys.cell.col)
			    {
                            case VOLC :
                            	case VALUEC :
				case VOLP :
				case DELTAC :
				case VALUEP :
                            	case DELTAP:
                            	case SHAREPRICE :break;
				case STOCKHELD : status.stockheld = 0; break;
				case VOLATILITY : status.volatility = 0.0;break;
				case INTEREST   : status.interest = 0.0; break;
				case  DATE      :
				case YEARMONTH :
				case SHARESPER : for (count =0;count <24; count++)
						   status.sizepay[count].sharesper = 1000;
						   break;               
				case EXPIRYDAY :
				case DAYSLEFT :
                            case MONTH : break;
                            case STRIKE : for (count = 0;count < 30; count++)
                                          {
					  status.data[count].strike = 0.0;
					  status.data[count].volc = 0.0;
					  status.data[count].volp = 0.0;
					  }
					  break;
				case MARKETC : for (count = 0;count < 30; count++)
                                        {
					status.data[count].marketc = 0.0;
					status.data[count].volc = 0.0;
					}
					  break;
				case HELDC :  for (count = 0;count < 30; count++)
					  status.data[count].heldc = 0;
					  break;
				case MARKETP : for (count = 0;count < 30; count++)
                                          {
					  status.data[count].marketp = 0.0;
					  status.data[count].volp = 0.0;
					  }
					  break;
				case HELDP :  for (count = 0;count < 30; count++)
					  status.data[count].heldp = 0;
					  break;
				case DIVIDENDDAY : for (count = 0;count < 24; count++)
					  status.sizepay[count].dday = 0;
					  break;
			        case DIVIDENDCENTS :  for (count = 0;count < 24; count++)
					  status.sizepay[count].payout = 0;
					  break;

			    }  wait();
				 calcall();
				 showall();
				 totals();  break;
			  case 3:   clearall();wait();   wait();
				 calcall();
				 showall();
				 totals();break;
			  /* clear all set shares per con */


		    }           showtotals();
				 ready();
				 entercell(sys.cell);
				 /* inverse vol now invalid */
		    break;


         case F08 :
			leavecell(sys.cell);
		   switch( choice(7, utilchoice))
		      {
			case 1 : getdir(); break;
			case 2 : bonusissue();
				 wait();
				 calcall();
				 showall();
				 totals();
				 showtotals();
				 ready();
				 break;
			case 3 : cashissue();
				 wait();
				 calcall();
				 showall();
				 totals();
				 showtotals();
				 ready();
				 break;
			 case 4: switch( choice(3,resolutionchoice))
				 {
				   case 1: numpts = 10; break;
				   case 2: numpts = 15; break;
				   case 3: numpts = 30; break;
				 }
                                    break;
			 case 5:switch (choice(3,printchoice))
				  {
				     case 1: printdetails(); break;
				     case 2: demo1();break;
				     case 3: demo1(); break;
					   } break;
			 case 6: filedelete(); break;
			 case 7 : reinstall();
		         }
			 entercell(sys.cell);
			 break;

         case F09 : switch (sys.screen)
			{
			case SCREEN1 :
			    leavecell(sys.cell);
			    if (sys.display == HELDS) sys.display = DELTAS;
			    else sys.display = HELDS;
		    	if (sys.cell.row >= 8)
		   	 sys.cell.col = MONTH;
		    	textcolor(sys.graphics.colors.heading);
		    	textbackground(sys.graphics.colors.databack);
		    	drawheadings();
		    	showall();
			showtotals();
		    	entercell(sys.cell);break;
			case SCREEN2 : break;
			case SCREEN3 :
			    leavecell(sys.cell);
			    if (sys.display == INVVOL) sys.display = OVERVALUED;
			    else sys.display = INVVOL;
 		    	    textcolor(sys.graphics.colors.heading);
		    	    textbackground(sys.graphics.colors.databack);
		    	    drawheadings();
		    	    showall();
			    showtotals();
		    	    entercell(sys.cell);break;
		       }
		    break;
         case F10 : switch (choice(3,quitchoice))
		    {
		    case 0 : break;
		    case 1 : wait();
	   		    textcolor(LIGHTGRAY);
			    textbackground(BLACK);
			    savesys();
			    clrscr();
			    gotoxy(2,2);
			    cprintf(" The Option Analyst is a product of");
			    gotoxy(2,3);
			    cprintf(" EFAM RESOURCES Pty. Ltd.\n");
			    retcursor();
			    exit(0);
			    break;
                    case 2 : demo();
			    break;
		    case 3 : break;
		    }
		    break;
	}
}
  void EGHTraceFitter::setInitialParameters_(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces)
  {
    LOG_DEBUG << "EGHTraceFitter->setInitialParameters(...)" << std::endl;
    LOG_DEBUG << "Number of traces: " << traces.size() << std::endl;

    // aggregate data; some peaks (where intensity is zero) can be missing!
    // mapping: RT -> total intensity over all mass traces
    std::list<std::pair<double, double> > total_intensities;
    traces.computeIntensityProfile(total_intensities);

    // compute moving average for smoothing:
    const Size N = total_intensities.size();
    const Size LEN = 2;   // window size: 2 * LEN + 1
    std::vector<double> totals(N + 2 * LEN);   // pad with zeros at ends
    Int index = LEN;
    // LOG_DEBUG << "Summed intensities:\n";
    for (std::list<std::pair<double, double> >::iterator it =
           total_intensities.begin(); it != total_intensities.end(); ++it)
    {
      totals[index++] = it->second;
      // LOG_DEBUG << it->second << std::endl;
    }

    std::vector<double> smoothed(N);
    Size max_index = 0;   // index of max. smoothed intensity
    // LOG_DEBUG << "Smoothed intensities:\n";
    double sum = std::accumulate(&totals[LEN], &totals[2 * LEN], 0.0);
    for (Size i = 0; i < N; ++i)
    {
      sum += totals[i + 2 * LEN];
      smoothed[i] = sum / (2 * LEN + 1);
      sum -= totals[i];
      if (smoothed[i] > smoothed[max_index]) max_index = i;
      // LOG_DEBUG << smoothed[i] << std::endl;
    }
    LOG_DEBUG << "Maximum at index " << max_index << std::endl;
    height_ = smoothed[max_index] - traces.baseline;
    LOG_DEBUG << "height: " << height_ << std::endl;
    std::list<std::pair<double, double> >::iterator it = total_intensities.begin();
    std::advance(it, max_index);
    apex_rt_ = it->first;
    LOG_DEBUG << "apex_rt: " << apex_rt_ << std::endl;
    region_rt_span_ = (total_intensities.rbegin()->first -
                       total_intensities.begin()->first);
    LOG_DEBUG << "region_rt_span: " << region_rt_span_ << std::endl;

    // find RT values where intensity is at half-maximum:
    index = static_cast<Int>(max_index);
    while ((index > 0) && (smoothed[index] > height_ * 0.5))
      --index;
    double left_height = smoothed[index];
    it = total_intensities.begin();
    std::advance(it, index);
    double left_rt = it->first;
    LOG_DEBUG << "Left half-maximum at index " << index << ", RT " << left_rt
              << std::endl;
    index = static_cast<Int>(max_index);
    while ((index < Int(N - 1)) && (smoothed[index] > height_ * 0.5))
      ++index;
    double right_height = smoothed[index];
    it = total_intensities.end();
    std::advance(it, index - Int(N));
    double right_rt = it->first;
    LOG_DEBUG << "Right half-maximum at index " << index << ", RT "
              << right_rt << std::endl;

    double A = apex_rt_ - left_rt;
    double B = right_rt - apex_rt_;
    //LOG_DEBUG << "A: " << A << std::endl;
    //LOG_DEBUG << "B: " << B << std::endl;

    // compute estimates for tau / sigma based on A and B:
    double alpha = (left_height + right_height) * 0.5 / height_;   // ~0.5
    double log_alpha = log(alpha);

    tau_ = -1 / log_alpha * (B - A);
    //EGH function fails when tau==0
    if (tau_ == 0) tau_ = std::numeric_limits<double>::epsilon();

    LOG_DEBUG << "tau: " << tau_ << std::endl;
    sigma_ = sqrt(-0.5 / log_alpha * B * A);
    LOG_DEBUG << "sigma: " << sigma_ << std::endl;
  }
Beispiel #17
0
void dspTimePhasedBookingsByProductCategory::sFillList()
{
  if (!_periods->isPeriodSelected())
  {
    if (isVisible())
      QMessageBox::warning( this, tr("Select Calendar Periods"),
                            tr("Please select one or more Calendar Periods") );
    return;
  }

  _soitem->clear();
  while (_soitem->columns() > 3)
    _soitem->removeColumn(3);

  _columnDates.clear();

  QString sql("SELECT prodcat_id, warehous_id, prodcat_code, warehous_code");

  if (_salesDollars->isChecked())
    sql += ", TEXT('$') AS uom";
  
  else if (_inventoryUnits->isChecked())
    sql += ", item_invuom AS uom";

  else if (_capacityUnits->isChecked())
    sql += ", item_capuom AS uom";

  else if (_altCapacityUnits->isChecked())
    sql += ", item_altcapuom AS uom";

  int columns = 1;
  XListViewItem *cursor = _periods->firstChild();
  if (cursor != 0)
  {
    do
    {
      if (_periods->isSelected(cursor))
      {
        if (_salesDollars->isChecked())
          sql += QString(", SUM(bookingsByItemValue(itemsite_id, %2)) AS bucket%1")
                 .arg(columns++)
                 .arg(cursor->id());
  
        else if (_inventoryUnits->isChecked())
          sql += QString(", SUM(bookingsByItemQty(itemsite_id, %2)) AS bucket%1")
                 .arg(columns++)
                 .arg(cursor->id());
  
        else if (_capacityUnits->isChecked())
          sql += QString(", SUM(bookingsByItemQty(itemsite_id, %2) * item_capinvrat) AS bucket%1")
                 .arg(columns++)
                 .arg(cursor->id());
  
        else if (_altCapacityUnits->isChecked())
          sql += QString(", SUM(bookingsByItemQty(itemsite_id, %2) * item_altcapinvrat) AS bucket%1")
                 .arg(columns++)
                 .arg(cursor->id());
  
        _soitem->addColumn(formatDate(((PeriodListViewItem *)cursor)->startDate()), _qtyColumn, Qt::AlignRight);

        _columnDates.append(DatePair(((PeriodListViewItem *)cursor)->startDate(), ((PeriodListViewItem *)cursor)->endDate()));
      }
    }
    while ((cursor = cursor->nextSibling()) != 0);
  }

  sql += " FROM itemsite, item, warehous, prodcat "
         "WHERE ( (itemsite_item_id=item_id)"
         " AND (itemsite_warehous_id=warehous_id)"
         " AND (item_prodcat_id=prodcat_id)";

  if (_warehouse->isSelected())
    sql += " AND (itemsite_warehous_id=:warehous_id) ";

  if (_productCategory->isSelected())
    sql += "AND (prodcat_id=:prodcat_id) ";
  else if (_productCategory->isPattern())
    sql += "AND (prodcat_code ~ :prodcat_pattern) ";

  sql += ") "
         "GROUP BY prodcat_id, warehous_id, prodcat_code, uom, warehous_code;";

  q.prepare(sql);
  _warehouse->bindValue(q);
  _productCategory->bindValue(q);
  q.exec();
  if (q.first())
  {
    Q3ValueVector<Numeric> totals(columns);;

    do
    {
      XListViewItem *item = new XListViewItem( _soitem, _soitem->lastItem(),
                                               q.value("prodcat_id").toInt(), q.value("warehous_id").toInt(),
                                               q.value("prodcat_code"), q.value("warehous_code"),
                                               q.value("uom") );

      for (int column = 1; column < columns; column++)
      {
        QString bucketName = QString("bucket%1").arg(column);
        totals[column] += q.value(bucketName).toDouble();

        if ( (_inventoryUnits->isChecked()) || (_capacityUnits->isChecked()) || (_altCapacityUnits->isChecked()) )
          item->setText((column + 2), formatQty(q.value(bucketName).toDouble()));
        else if (_salesDollars->isChecked())
          item->setText((column + 2), formatMoney(q.value(bucketName).toDouble()));
      }
    }
    while (q.next());

    XListViewItem *total = new XListViewItem(_soitem, _soitem->lastItem(), -1, QVariant(tr("Totals:")));
    for (int column = 1; column < columns; column++)
    {
      if ( (_inventoryUnits->isChecked()) || (_capacityUnits->isChecked()) || (_altCapacityUnits->isChecked()) )
        total->setText((column + 2), formatQty(totals[column].toDouble()));
      else if (_salesDollars->isChecked())
        total->setText((column + 2), formatMoney(totals[column].toDouble()));
    }
  }
}
Beispiel #18
0
char editcell(celltype cell)
{
int x,y;
long z;
char ch;
char sharestring[12];
int  pageint;
if (page == PAGEUP || sys.screen == SCREEN2 || cell.row < 8) pageint = 0;
else pageint = 15;
x = endcell(cell.col)-1;
y = cell.row - pageint ;

   switch (cell.col)
       {case MONTH :  entercell(sys.cell);
		     if (status.data[cell.row-8].month == -1 &&
			 cell.row != 8 )
			 status.data[cell.row-8].month =
			inputmonth(x-2,y,(status.data[cell.row-9].month)-1);
			else
			 status.data[cell.row-8].month =
			inputmonth(x-2,y,status.data[cell.row-8].month);
		     wait();
		     if (sys.screen == SCREEN3) calcvolrow(cell.row);
                     calcrow(cell.row);
		     showrow(cell.row);
		     if ( cell.row != 22 && cell.row != 37)
		     {
		     cell.row += 1;
		     showcell(cell);
		     cell.row = cell.row -1;
		     }
		      /* show date of line below if it
			    had been hidden by showall suppression */
		     break;
	case STRIKE : entercell(sys.cell);
		      if (status.stockprice != 4.0) exit(0);
		      status.data[cell.row-8].strike =
		      inputreal(x,y,status.data[cell.row-8].strike,8,sys.decimal);
		      wait();
		     if (sys.screen == SCREEN3) calcvolrow(cell.row);
		      calcrow(cell.row);
                      showrow(cell.row);
		      break;
	case VALUEC : getch();break;
	case VALUEP : getch();break;
	case HELDC : entercell(sys.cell);
		     if (status.stockprice != 4.0) exit(0);
		     status.data[cell.row-8].heldc =
		     inputinteger(x,y,status.data[cell.row-8].heldc,4);
		     wait();
		     showcell(sys.cell);
		     break;
	case HELDP : entercell(sys.cell);
		     if (status.stockprice != 4.0) exit(0);
		     status.data[cell.row-8].heldp =
		     inputinteger(x,y,status.data[cell.row-8].heldp,4);
		     wait();
		     showcell(sys.cell);
		     break;
	case STOCKHELD :
			entercell(sys.cell);
			z = status.stockheld;
		     z =
		     inputlint(x,y,&z,8);
		     wait();
		     break;
	case SHAREPRICE : entercell(sys.cell);
			status.stockprice = 4.0;
			getch();
			demo();
			getch();
			break;
        case VOLATILITY : entercell(sys.cell);
			status.volatility =
			inputreal(x,y,status.volatility,5,2);
			wait();
			calcall();
			calcalloverval();
			showall();
			break;
        case INTEREST : entercell(sys.cell);
			status.interest=
			inputreal(x,y,status.interest,5,2);
			wait();
			initdivmtx(0);
			calcall();
			if (sys.screen == SCREEN3) calcallvol();
			else recalcvolvalues = TRUE;
			showall();
			break;
        case DATE    : 	entercell(sys.cell);
			inputdate(x,y,sys.date);
			wait();
			initdates();
			initsizepay();
			calcdays();
			initdivmtx(0);
			calcall();
			if (sys.screen == SCREEN3) calcallvol();
			else recalcvolvalues = TRUE;
			showall();
			break;
	case SHARESPER : entercell(sys.cell);
			status.sizepay[y].sharesper=
			inputinteger(x,y,status.sizepay[y].sharesper,4);
                        if (status.sizepay[y].sharesper < 1)
			status.sizepay[y].sharesper = 1;
			wait();
                        break;
	case EXPIRYDAY : entercell(sys.cell);
			sys.expiry[y].eday =inputinteger(x,y,sys.expiry[y].eday,2);
			if (sys.expiry[y].eday < 1) sys.expiry[y].eday = 1;
			else if (sys.expiry[y].eday > 31) sys.expiry[y].eday = 28;
			wait();
			initdates();
			calcdays();
			initdivmtx(0);
			calcall();
			tosavesys = TRUE;
		      	showall();
			break;
	case DIVIDENDDAY : entercell(sys.cell);
			status.sizepay[y].dday=inputinteger(x,y,status.sizepay[y].dday,2);
			if (status.sizepay[y].dday < 0)
			status.sizepay[y].dday = 0;
			else if (status.sizepay[y].dday > 31)
			status.sizepay[y].dday = 28;
			wait();
			calcdays();
			initdivmtx(0);
                        calcall();
			showrow(cell.row);
                        break;
	case DIVIDENDCENTS : entercell(sys.cell);
			status.sizepay[y].payout
			= inputinteger(x,y,status.sizepay[y].payout,3);
			if (status.sizepay[y].payout < 0)
			status.sizepay[y].payout = 0;
			wait();
			initdivmtx(0);
                        calcall();
			showrow(cell.row);
			break;
	case VOLC :     getch();
			break;
	case VOLP :     getch();
			break;
	case MARKETC : entercell(sys.cell);
			if (status.stockprice != 4.0) exit(0);
		      status.data[cell.row-8].marketc =
		      inputreal(x,y,status.data[cell.row-8].marketc,8,sys.decimal);
		      if (status.data[cell.row-8].marketc < 0)
		      status.data[cell.row-8].marketc = 0;
			wait();
			status.data[cell.row-8].volc = invertvolc(cell.row);
			calcoverval(cell.row);
			showrow(cell.row);
			break;
	case MARKETP : entercell(sys.cell);
		      if (status.stockprice != 4.0) exit(0);
		      status.data[cell.row-8].marketp =
		      inputreal(x,y,status.data[cell.row-8].marketp,8,sys.decimal);
		      if (status.data[cell.row-8].marketp < 0)
		      status.data[cell.row-8].marketp = 0;
			wait();
			status.data[cell.row-8].volp = invertvolp(cell.row);
			calcoverval(cell.row);
			showrow(cell.row);
			break;
       }
       entercell(cell);
       totals();
       showtotals();
       if (status.stockprice != 4.0) exit(0);
       ready();
       ch = getch();
       return(ch);
}
Beispiel #19
0
int
main(int argc, char *argv[])
{
	note("Testing static decl");
	{
		bitstr_t bit_decl(bs, 65);
		/*bitstr_t *bsp = bs;*/

		bit_set(bs,9);
		bit_set(bs,14);
		TEST(bit_test(bs,9), "bit 9 set"); 
		TEST(!bit_test(bs,12), "bit 12 not set");
		TEST(bit_test(bs,14), "bit 14 set" );
		/*bit_free(bsp);*/	/* triggers TEST in bit_free - OK */
	}
	note("Testing basic vixie functions");
	{
		bitstr_t *bs = bit_alloc(16), *bs2;


		/*bit_set(bs, 42);*/ 	/* triggers TEST in bit_set - OK */
		bit_set(bs,9);
		bit_set(bs,14);
		TEST(bit_test(bs,9), "bit 9 set"); 
		TEST(!bit_test(bs,12), "bit 12 not set" );
		TEST(bit_test(bs,14), "bit 14 set");

		bs2 = bit_copy(bs);
		bit_fill_gaps(bs2);
		TEST(bit_ffs(bs2) == 9, "first bit set = 9 ");
		TEST(bit_fls(bs2) == 14, "last bit set = 14");
		TEST(bit_set_count(bs2) == 6, "bitstring");
		TEST(bit_test(bs2,12), "bitstring");
		TEST(bit_super_set(bs,bs2) == 1, "bitstring");
		TEST(bit_super_set(bs2,bs) == 0, "bitstring");

		bit_clear(bs,14);
		TEST(!bit_test(bs,14), "bitstring");

		bit_nclear(bs,9,14);
		TEST(!bit_test(bs,9), "bitstring");
		TEST(!bit_test(bs,12), "bitstring");
		TEST(!bit_test(bs,14), "bitstring");

		bit_nset(bs,9,14);
		TEST(bit_test(bs,9), "bitstring");
		TEST(bit_test(bs,12), "bitstring");
		TEST(bit_test(bs,14), "bitstring");

		TEST(bit_ffs(bs) == 9, "ffs");
		TEST(bit_ffc(bs) == 0, "ffc");
		bit_nset(bs,0,8);
		TEST(bit_ffc(bs) == 15, "ffc");

		bit_free(bs);
		/*bit_set(bs,9); */	/* triggers TEST in bit_set - OK */
	}
	note("Testing and/or/not");
	{
		bitstr_t *bs1 = bit_alloc(128);
		bitstr_t *bs2 = bit_alloc(128);

		bit_set(bs1, 100);
		bit_set(bs1, 104);
		bit_set(bs2, 100);

		bit_and(bs1, bs2);
		TEST(bit_test(bs1, 100), "and");
		TEST(!bit_test(bs1, 104), "and");

		bit_set(bs2, 110);
		bit_set(bs2, 111);
		bit_set(bs2, 112);
		bit_or(bs1, bs2);
		TEST(bit_test(bs1, 100), "or");
		TEST(bit_test(bs1, 110), "or");
		TEST(bit_test(bs1, 111), "or");
		TEST(bit_test(bs1, 112), "or");

		bit_not(bs1);
		TEST(!bit_test(bs1, 100), "not");
		TEST(bit_test(bs1, 12), "not");

		bit_free(bs1);
		bit_free(bs2);
	}

	note("testing bit selection");
	{
		bitstr_t *bs1 = bit_alloc(128), *bs2;
		bit_set(bs1, 21);
		bit_set(bs1, 100);
		bit_fill_gaps(bs1);
		bs2 = bit_pick_cnt(bs1,20);

		if (bs2) {
			TEST(bit_set_count(bs2) == 20, "pick");
			TEST(bit_ffs(bs2) == 21, "pick");
			TEST(bit_fls(bs2) == 40, "pick");
			bit_free(bs2);
		}
		else
			TEST(0, "alloc fail");

		bit_free(bs1);
	}
	note("Testing realloc");
	{
		bitstr_t *bs = bit_alloc(1);

		TEST(bit_ffs(bs) == -1, "bitstring");
		bit_set(bs,0);
		/*bit_set(bs, 1000);*/	/* triggers TEST in bit_set - OK */
		bs = bit_realloc(bs,1048576);
		bit_set(bs,1000);
		bit_set(bs,1048575);
		TEST(bit_test(bs, 0), "bitstring");
		TEST(bit_test(bs, 1000), "bitstring");
		TEST(bit_test(bs, 1048575), "bitstring");
		TEST(bit_set_count(bs) == 3, "bitstring");
		bit_clear(bs,0);
		bit_clear(bs,1000);
		TEST(bit_set_count(bs) == 1, "bitstring");
		TEST(bit_ffs(bs) == 1048575, "bitstring");
		bit_free(bs);
	}
	note("Testing bit_fmt");
	{
		char tmpstr[1024];
		bitstr_t *bs = bit_alloc(1024);

		TEST(!strcmp(bit_fmt(tmpstr,sizeof(tmpstr),bs), ""), "bitstring");
		bit_set(bs,42);
		TEST(!strcmp(bit_fmt(tmpstr,sizeof(tmpstr),bs), "42"), "bitstring");
		bit_set(bs,102);
		TEST(!strcmp(bit_fmt(tmpstr,sizeof(tmpstr),bs), "42,102"), "bitstring");
		bit_nset(bs,9,14);
		TEST(!strcmp(bit_fmt(tmpstr,sizeof(tmpstr), bs), 
					"9-14,42,102"), "bitstring");
	}

	note("Testing bit_nffc/bit_nffs");
	{
		bitstr_t *bs = bit_alloc(1024);

		bit_set(bs, 2);
		bit_set(bs, 6);
		bit_set(bs, 7);
		bit_nset(bs,12,1018); 

		TEST(bit_nffc(bs, 2) == 0, "bitstring");
		TEST(bit_nffc(bs, 3) == 3, "bitstring");
		TEST(bit_nffc(bs, 4) == 8, "bitstring");
		TEST(bit_nffc(bs, 5) == 1019, "bitstring");
		TEST(bit_nffc(bs, 6) == -1, "bitstring");

		TEST(bit_nffs(bs, 1) == 2, "bitstring");
		TEST(bit_nffs(bs, 2) == 6, "bitstring");
		TEST(bit_nffs(bs, 100) == 12, "bitstring");
		TEST(bit_nffs(bs, 1023) == -1, "bitstring");

		bit_free(bs);
	}

	note("Testing bit_unfmt");
	{
		bitstr_t *bs = bit_alloc(1024);
		bitstr_t *bs2 = bit_alloc(1024);
		char tmpstr[4096];

		bit_set(bs,1);
		bit_set(bs,3);
		bit_set(bs,30);
		bit_nset(bs,42,64);
		bit_nset(bs,97,1000);

		bit_fmt(tmpstr, sizeof(tmpstr), bs);
		TEST(bit_unfmt(bs2, tmpstr) != -1, "bitstring");
		TEST(bit_equal(bs, bs2), "bitstring");
	}

	totals();
	return failed;
}
void RunKMedoids(const leveldb::Slice& begin,
                 const leveldb::Slice& end,
                 int K, leveldb::DB* db,
                 leveldb::DB* work_db, int concurrency,
                 std::ostream& ivar_out, std::ostream& cent_out) {
  auto very_start = std::chrono::system_clock::now();
  auto key_centroids = uniform_init(begin, end, K);
  std::vector<GDELTMini> val_centroids(K);
  {
    auto it = iter(db);
    for (int i = 0; i < K; ++i) {
      it->Seek(key_centroids[i]);
      CHECK(it->Valid());
      read(it->value(), val_centroids[i]);
    }
  }

  std::cout << "Divying up range among threads... " << std::flush;
  auto parvec = get_par_ranges(uniform_init(begin, end, concurrency), db, end);
  std::cout << "DONE" << std::endl;

  int i = 0;
  bool centers_changed = true;
  vuad totals(K);
  vuai cluster_sizes(K);
  for (int i = 0; i < K; ++i) {
    cluster_sizes[i].reset(new std::atomic<int>);
    totals[i].reset(new std::atomic<double>);
  }

  while (centers_changed) {
    auto start = std::chrono::system_clock::now();
    assign_closest(parvec, totals, K, work_db, val_centroids, concurrency,
                   cluster_sizes);
    auto tot = std::accumulate(totals.begin(), totals.end(), 0.0,
                               [](double sum, typename vuad::value_type& d) {
                                 return sum + d->load();
                               });
    auto end = std::chrono::system_clock::now();
    std::cout << "Iteration " << ++i << " total intravariance " << tot;
    std::cout << "\n    Assigning medoids took " << secs(start, end)
              << "s" << std::endl;

    start = std::chrono::system_clock::now();
    for (auto& d : totals) {
      ivar_out << d->load() << " ";
    }
    ivar_out << std::endl;
    cent_out << key_centroids << std::endl;
    end = std::chrono::system_clock::now();
    std::cout << "    Saving medoids took " << secs(start, end)
              << " s" << std::endl;

    start = std::chrono::system_clock::now();
    centers_changed = update_medoids(concurrency, K, db, work_db,
                                     val_centroids, key_centroids,
                                     totals, cluster_sizes);
    end = std::chrono::system_clock::now();
    std::cout << "    Medoid update took " << secs(start, end)
              << " s" << std::endl;
    start = end;
  }
  auto very_end = std::chrono::system_clock::now();
  std::cout << "K-medoid clustering COMPLETE in "
            << secs(very_start, very_end) << " s" << std::endl;
}
Beispiel #21
0
int
main (int argc, char **argv)
{
  int i, j, k;
  const int NUM_TOP_ITERATIONS = 2;
  const int NUM_MIDDLE_ITERATIONS = 2;
  const int NUM_BOTTOM_ITERATIONS = 2;

  /* We do the whole thing multiple times to shake out state-management
     issues in the underlying code.  */

  for (i = 1; i <= NUM_TOP_ITERATIONS; i++)
    {
      /* Create the top-level context.  */
      snprintf (test, sizeof (test),
		"%s iteration %d of %d of top level",
		extract_progname (argv[0]),
		i, NUM_TOP_ITERATIONS);

      struct top_level top_level;
      memset (&top_level, 0, sizeof (top_level));

      top_level.ctxt = gcc_jit_context_acquire ();
      set_options (top_level.ctxt, argv[0]);

      make_types (&top_level);
      make_sqrt (&top_level);

      /* No errors should have occurred.  */
      CHECK_VALUE (gcc_jit_context_get_first_error (top_level.ctxt), NULL);

      gcc_jit_context_dump_to_file (top_level.ctxt,
				    "dump-of-test-nested-contexts-top.c",
				    1);

      for (j = 1; j <= NUM_MIDDLE_ITERATIONS; j++)
	{
	  /* Create and populate the middle-level context, using
	     objects from the top-level context.  */
	  snprintf (test, sizeof (test),
		    ("%s iteration %d of %d of top level;"
		     " %d of %d of middle level"),
		    extract_progname (argv[0]),
		    i, NUM_TOP_ITERATIONS,
		    j, NUM_MIDDLE_ITERATIONS);

	  struct middle_level middle_level;
	  memset (&middle_level, 0, sizeof (middle_level));

	  middle_level.ctxt =
	    gcc_jit_context_new_child_context (top_level.ctxt);
	  make_calc_discriminant (&top_level,
				  &middle_level);

	  /* No errors should have occurred.  */
	  CHECK_VALUE (gcc_jit_context_get_first_error (middle_level.ctxt),
		       NULL);

	  gcc_jit_context_dump_to_file (middle_level.ctxt,
					"dump-of-test-nested-contexts-middle.c",
					1);

	  gcc_jit_result *middle_result =
	    gcc_jit_context_compile (middle_level.ctxt);
	  CHECK_NON_NULL (middle_result);

	  verify_middle_code (middle_level.ctxt, middle_result);

	  for (k = 1; k <= NUM_BOTTOM_ITERATIONS; k++)
	    {
	      /* Create and populate the innermost context, using
		 objects from the top-level and middle-level contexts.  */
	      snprintf (test, sizeof (test),
			("%s iteration %d of %d of top level;"
			 " %d of %d of middle level;"
			 " %d of %d of bottom level"),
			extract_progname (argv[0]),
			i, NUM_TOP_ITERATIONS,
			j, NUM_MIDDLE_ITERATIONS,
			k, NUM_BOTTOM_ITERATIONS);

	      struct bottom_level bottom_level;
	      memset (&bottom_level, 0, sizeof (bottom_level));

	      bottom_level.ctxt =
		gcc_jit_context_new_child_context (middle_level.ctxt);
	      make_test_quadratic (&top_level,
				   &middle_level,
				   &bottom_level);

	      /* No errors should have occurred.  */
	      CHECK_VALUE (gcc_jit_context_get_first_error (bottom_level.ctxt),
			   NULL);

	      gcc_jit_context_dump_to_file (bottom_level.ctxt,
					    "dump-of-test-nested-contexts-bottom.c",
					    1);

	      gcc_jit_result *bottom_result =
		gcc_jit_context_compile (bottom_level.ctxt);
	      verify_bottom_code (bottom_level.ctxt, bottom_result);
	      gcc_jit_result_release (bottom_result);
	      gcc_jit_context_release (bottom_level.ctxt);

	    }

	  gcc_jit_result_release (middle_result);
	  gcc_jit_context_release (middle_level.ctxt);

	}

      gcc_jit_context_release (top_level.ctxt);
   }

  totals ();

  return 0;
}
Beispiel #22
0
void  StatisticsBasedScorer::score(const candidates_t& candidates, const diffs_t& diffs,
                                   statscores_t& scores) const
{
  if (!m_score_data) {
    throw runtime_error("Score data not loaded");
  }
  // calculate the score for the candidates
  if (m_score_data->size() == 0) {
    throw runtime_error("Score data is empty");
  }
  if (candidates.size() == 0) {
    throw runtime_error("No candidates supplied");
  }
  int numCounts = m_score_data->get(0,candidates[0]).size();
  vector<int> totals(numCounts);
  for (size_t i = 0; i < candidates.size(); ++i) {
    ScoreStats stats = m_score_data->get(i,candidates[i]);
    if (stats.size() != totals.size()) {
      stringstream msg;
      msg << "Statistics for (" << "," << candidates[i] << ") have incorrect "
          << "number of fields. Found: " << stats.size() << " Expected: "
          << totals.size();
      throw runtime_error(msg.str());
    }
    for (size_t k = 0; k < totals.size(); ++k) {
      totals[k] += stats.get(k);
    }
  }
  scores.push_back(calculateScore(totals));

  candidates_t last_candidates(candidates);
  // apply each of the diffs, and get new scores
  for (size_t i = 0; i < diffs.size(); ++i) {
    for (size_t j = 0; j < diffs[i].size(); ++j) {
      size_t sid = diffs[i][j].first;
      size_t nid = diffs[i][j].second;
      size_t last_nid = last_candidates[sid];
      for (size_t k  = 0; k < totals.size(); ++k) {
        int diff = m_score_data->get(sid,nid).get(k)
                   - m_score_data->get(sid,last_nid).get(k);
        totals[k] += diff;
      }
      last_candidates[sid] = nid;
    }
    scores.push_back(calculateScore(totals));
  }

  // Regularisation. This can either be none, or the min or average as described in
  // Cer, Jurafsky and Manning at WMT08.
  if (m_regularization_type == NONE || m_regularization_window <= 0) {
    // no regularisation
    return;
  }

  // window size specifies the +/- in each direction
  statscores_t raw_scores(scores);      // copy scores
  for (size_t i = 0; i < scores.size(); ++i) {
    size_t start = 0;
    if (i >= m_regularization_window) {
      start = i - m_regularization_window;
    }
    const size_t end = min(scores.size(), i + m_regularization_window + 1);
    if (m_regularization_type == AVERAGE) {
      scores[i] = score_average(raw_scores,start,end);
    } else {
      scores[i] = score_min(raw_scores,start,end);
    }
  }
}
Beispiel #23
0
void dspTimePhasedSalesByCustomerByItem::sFillList()
{
  _sohist->clear();

  if (!_periods->isPeriodSelected())
    return;

  _sohist->clear();
  _sohist->setColumnCount(2);

  QString sql("SELECT cust_id, cust_number, cust_name");

  int columns = 1;
  QList<QTreeWidgetItem*> selected = _periods->selectedItems();
  for (int i = 0; i < selected.size(); i++)
  {
    PeriodListViewItem *cursor = (PeriodListViewItem*)selected[i];
    if (_productCategory->isSelected())
      sql += QString(", shipmentsByCustomerValue(cust_id, %1, :prodcat_id) AS bucket%3")
	     .arg(cursor->id())
	     .arg(columns++);
    else if (_productCategory->isPattern())
      sql += QString(", shipmentsByCustomerValue(cust_id, %1, :prodcat_pattern) AS bucket%3")
	     .arg(cursor->id())
	     .arg(columns++);
    else
      sql += QString(", shipmentsByCustomerValue(cust_id, %1) AS bucket%2")
	     .arg(cursor->id())
	     .arg(columns++);

    _sohist->addColumn(formatDate(cursor->startDate()), _qtyColumn, Qt::AlignRight);
    _columnDates.append(DatePair(cursor->startDate(), cursor->endDate()));
  }

  sql += " FROM cust ";

  if (_customerType->isSelected())
    sql += "WHERE (cust_custtype_id=:custtype_id)";
  else if (_customerType->isPattern())
    sql += "WHERE (cust_custtype_id IN (SELECT custtype_id FROM custtype WHERE (custtype_code ~ :custtype_pattern))) ";

  if (_byCustomer->isChecked())
    sql += "ORDER BY cust_number;";
  else if (_bySales->isChecked())
    sql += "ORDER BY bucket1 DESC;";

  q.prepare(sql);
  _customerType->bindValue(q);
  _productCategory->bindValue(q);
  q.exec();
  if (q.first())
  {
    Q3ValueVector<Numeric> totals(columns);;
    XTreeWidgetItem *last = 0;

    do
    {
      last = new XTreeWidgetItem( _sohist, last, q.value("cust_id").toInt(),
				 q.value("cust_number"), q.value("cust_name") );

      for (int column = 1; column < columns; column++)
      {
        QString bucketName = QString("bucket%1").arg(column);
        last->setText((column + 1), formatMoney(q.value(bucketName).toDouble()));
        totals[column] += q.value(bucketName).toDouble();
      }
    }
    while (q.next());

//  Add the totals row
    XTreeWidgetItem *total = new XTreeWidgetItem(_sohist, last, -1, QVariant(tr("Totals:")));
    for (int column = 1; column < columns; column++)
      total->setText((column + 1), formatMoney(totals[column].toDouble()));
  }
}
Beispiel #24
0
void dspTimePhasedOpenAPItems::sFillCustom()
{
  if (!_periods->isPeriodSelected())
  {
    if (isVisible())
      QMessageBox::warning( this, tr("Select Calendar Periods"),
                            tr("Please select one or more Calendar Periods") );
    return;
  }

  _columnDates.clear();
  _apopen->clear();
  _apopen->setColumnCount(2);

  QString sql("SELECT vend_id, vend_number, vend_name");

  int columns = 1;
  QList<QTreeWidgetItem*> selected = _periods->selectedItems();
  for (int i = 0; i < selected.size(); i++)
  {
    PeriodListViewItem *cursor = (PeriodListViewItem*)selected[i];
    sql += QString(", openAPItemsValue(vend_id, %2) AS bucket%1")
          .arg(columns++)
          .arg(cursor->id());

    _apopen->addColumn(formatDate(cursor->startDate()), _bigMoneyColumn, Qt::AlignRight);
    _columnDates.append(DatePair(cursor->startDate(), cursor->endDate()));
  }

  sql += " FROM vend ";

  if (_selectedVendor->isChecked())
    sql += "WHERE (vend_id=:vend_id)";
  else if (_selectedVendorType->isChecked())
    sql += "WHERE (vend_vendtype_id=:vendtype_id)";
  else if (_vendorTypePattern->isChecked())
    sql += "WHERE (vend_vendtype_id IN (SELECT vendtype_id FROM vendtype WHERE (vendtype_code ~ :vendtype_code))) ";

  sql += "ORDER BY vend_number;";

  q.prepare(sql);
  q.bindValue(":vend_id", _vend->id());
  q.bindValue(":vendtype_id", _vendorTypes->id());
  q.bindValue(":vendtype_code", _vendorType->text().upper());
  q.exec();
  if (q.first())
  {
    Q3ValueVector<Numeric> totals(columns);;
    XTreeWidgetItem *last = 0;

    do
    {
      double lineTotal = 0.0;

      last = new XTreeWidgetItem( _apopen, last, q.value("vend_id").toInt(),
                                 q.value("vend_number"), q.value("vend_name") );

      for (int column = 1; column < columns; column++)
      {
        QString bucketName = QString("bucket%1").arg(column);
        last->setText((column + 1), formatMoney(q.value(bucketName).toDouble()));
        totals[column] += q.value(bucketName).toDouble();
        lineTotal += q.value(bucketName).toDouble();
      }

      if (lineTotal == 0.0)
      {
        delete last;
        last = _apopen->topLevelItem(_apopen->topLevelItemCount() - 1);
      }
    }
    while (q.next());

//  Add the totals row
    XTreeWidgetItem *total = new XTreeWidgetItem(_apopen, last, -1, QVariant(tr("Totals:")));
    for (int column = 1; column < columns; column++)
      total->setText((column + 1), formatMoney(totals[column].toDouble()));
  }
}
Beispiel #25
0
int main (int argc, char *argv[])
{
	Buf buffer;
	uint16_t test16 = 1234, out16;
	uint32_t test32 = 5678, out32, byte_cnt;
	char testbytes[] = "TEST BYTES", *outbytes;
	char teststring[] = "TEST STRING",  *outstring = NULL;
	char *nullstr = NULL;
	char *data;
	int data_size;
	long double test_double = 1340664754944.2132312, test_double2;
	uint64_t test64;

	buffer = init_buf (0);
        pack16(test16, buffer);
        pack32(test32, buffer);
	pack64((uint64_t)test_double, buffer);

        packstr(testbytes, buffer);
        packstr(teststring, buffer);
	packstr(nullstr, buffer);

	packstr("literal", buffer);
	packstr("", buffer);

        data_size = get_buf_offset(buffer);
        printf("wrote %d bytes\n", data_size);

	/* Pull data off old buffer, destroy it, and create a new one */
	data = xfer_buf_data(buffer);
	buffer = create_buf(data, data_size);

        unpack16(&out16, buffer);
	TEST(out16 != test16, "un/pack16");

        unpack32(&out32, buffer);
	TEST(out32 != test32, "un/pack32");

  	unpack64(&test64, buffer);
	test_double2 = (long double)test64;
	TEST((uint64_t)test_double2 != (uint64_t)test_double, "un/pack double as a uint64");
	/* info("Original\t %Lf", test_double); */
	/* info("uint64\t %ld", test64); */
	/* info("converted LD\t %Lf", test_double2); */

	unpackstr_ptr(&outbytes, &byte_cnt, buffer);
	TEST( ( strcmp(testbytes, outbytes) != 0 ) , "un/packstr_ptr");

	unpackstr_xmalloc(&outstring, &byte_cnt, buffer);
	TEST(strcmp(teststring, outstring) != 0, "un/packstr_xmalloc");
	xfree(outstring);

	unpackstr_xmalloc(&nullstr, &byte_cnt, buffer);
	TEST(nullstr != NULL, "un/packstr of null string.");

	unpackstr_xmalloc(&outstring, &byte_cnt, buffer);
	TEST(strcmp("literal", outstring) != 0, 
			"un/packstr of string literal");
	xfree(outstring);

	unpackstr_xmalloc(&outstring, &byte_cnt, buffer);
	TEST(strcmp("", outstring) != 0, "un/packstr of string \"\" ");

	xfree(outstring);

	free_buf(buffer);
	totals();
	return failed;

}