Example #1
0
void TestExprDiff::vec01() {

	Variable x(4,"x");
	Function f(x,x[0]+x[3]);
	Function df(f,Function::DIFF);
	const ExprConstant* c=dynamic_cast<const ExprConstant*>(&df.expr());
	TEST_ASSERT(c);
	TEST_ASSERT(c->dim.type()==Dim::ROW_VECTOR);
	double _grad[][2] = {{1,1},{0,0},{0,0},{1,1}};
	IntervalVector grad(4,_grad);

	TEST_ASSERT(c->get_vector_value()==grad);
}
Example #2
0
File: vector.c Project: bendst/cu
void vector_remove(vector_t *v, size_t index, void df(void *)) {
    assert(v);
    size_t i = index;
    if (v->count <= index) {
        i = v->count - 1;
    }
    void *to_delete = v->data[i];
    if (df != NULL) {
        df(to_delete);
    }
    size_t diff = v->count - i + 1;
    memmove(v->data + i, v->data + i + 1, sizeof(void *) * diff);
    v->count--;
}
Example #3
0
int main(int argc, char **argv)
{
	// open the file passed in on the command-line
	assert(argc > 1);
	FILE* f = fopen(argv[1], "r");
	
	// construct a dwarf::file
	dwarf::lib::file df(fileno(f));
    
    // encapsulate the DIEs
    dwarf::encap::file def(fileno(f));
    
    std::cout << def.ds();
}
Example #4
0
void main()
{
    double  eps, fopt, x[3], xm[3], g[3];
    int itmax = 50, n = 3, it;
    double f();
    void df();
    eps = 1e-7;
    x[0] = x[1] = x[2] = 0.0;
    it = bfgs(x, xm, n, &fopt, f, df, eps, itmax);
    printf("iterations = %d:\nx0=%f,x1=%f,x2=%f\nfopt=%f\n", it, xm[0], xm[1],
           xm[2], fopt);
    df(xm, g, 3);
    printf("df[0]=%f, df[1]=%f, df[2]=%f\n", g[0], g[1], g[2]);
}
/**
 *  Initialize the applet.
 *
 *  Only called when we create a new applet. Asks the user for an URL and
 *  creates a .desktop file...
 */
bool LauncherApplet::init()
{
    //    
    // Get an url...
    //
    KFileDialog fileDlg(0, 0, 0, 0, true);
    fileDlg.exec();
    _url = fileDlg.selectedURL();
    
    if (!_url.isValid()) {
        return false;
    }
    
    //
    // Create a .desktop file
    //
    QString file = newDesktopFile(_url);
    
    if (KDesktopFile::isDesktopFile(_url.path())) {
        // Copy existing file...
        KURL dest;
        dest.setPath(file);
        KIO::NetAccess::upload(_url.path(), dest, 0);
    } else {
        // Create new file...
        KDesktopFile df(file);
        
        df.writeEntry("Encoding", "UTF-8");
        df.writeEntry("Type","Link");
        df.writeEntry("Name", _url.prettyURL());
        
        if (_url.isLocalFile()) {
            KFileItem item( KFileItem::Unknown, KFileItem::Unknown, _url );
            df.writeEntry("Icon", item.iconName() );
        } else {
            df.writeEntry("Icon", KMimeType::favIconForURL(_url));
        }
        df.writeEntry("URL", _url.url());
        df.sync();
    }
    
    // Use the .desktop file as URL
    _url = KURL();
    _url.setPath(file);
    
    // Update everything...
    slotSettingsChanged();
    
    return true;
}
Example #6
0
int df_main(int argc, char *argv[]) {
    printf("Filesystem               Size     Used     Free   Blksize\n");
    if (argc == 1) {
        char s[2000];
        FILE *f = fopen("/proc/mounts", "r");

        while (fgets(s, 2000, f)) {
            char *c, *e = s;

            for (c = s; *c; c++) {
                if (*c == ' ') {
                    e = c + 1;
                    break;
                }
            }

            for (c = e; *c; c++) {
                if (*c == ' ') {
                    *c = '\0';
                    break;
                }
            }

            df(e, 0);
        }

        fclose(f);
    } else {
        int i;

        for (i = 1; i < argc; i++) {
            df(argv[i], 1);
        }
    }

    exit(ok);
}
void PlasmaThemeListModel::refresh()
{
    reset();
    clearThemeList();

    // get all desktop themes
    QStringList themes;
    const QStringList &packs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "plasma/desktoptheme", QStandardPaths::LocateDirectory);
    foreach (const QString &ppath, packs) {
        const QDir cd(ppath);
        const QStringList &entries = cd.entryList(QDir::Dirs | QDir::Hidden);
        foreach (const QString pack, entries) {
            const QString _metadata = ppath+QLatin1Char('/')+pack+QStringLiteral("/metadata.desktop");
            if ((pack != "." && pack != "..") &&
                (QFile::exists(_metadata))) {
                themes << _metadata;
            }
        }
    }

    foreach (const QString &theme, themes) {
        int themeSepIndex = theme.lastIndexOf('/', -1);
        QString themeRoot = theme.left(themeSepIndex);
        int themeNameSepIndex = themeRoot.lastIndexOf('/', -1);
        QString packageName = themeRoot.right(themeRoot.length() - themeNameSepIndex - 1);

        KDesktopFile df(theme);

        if (df.noDisplay()) {
            continue;
        }

        QString name = df.readName();
        if (name.isEmpty()) {
            name = packageName;
        }
        const QString comment = df.readComment();
        const QString author = df.desktopGroup().readEntry("X-KDE-PluginInfo-Author",QString());
        const QString version = df.desktopGroup().readEntry("X-KDE-PluginInfo-Version",QString());


        ThemeInfo info;
        info.package = packageName;
        info.description = comment;
        info.author = author;
        info.version = version;
        info.themeRoot = themeRoot;
        m_themes[name] = info;
    }
Example #8
0
    void LuaPath::_init(std::string const &arg0,
                        std::string const &vrjlua_base) {
        _valid = true;

        _initialPath = fs::initial_path().string();
        std::vector<std::string> startingPlaces;
        startingPlaces.push_back(_initialPath);
        if (!vrjlua_base.empty()) {
            startingPlaces.push_back(getAbsolute(vrjlua_base).string());
        }

        if (!arg0.empty()) {
            _exeDir = getAbsolute(arg0).remove_filename().string();
            startingPlaces.push_back(_exeDir);
        }

        _root = _findFilePath(startingPlaces,
                              "share/vrjugglua/lua/vrjlua-init.lua");
        if (!_root.empty()) {
            _luaDir = (fs::path(_root) / "share/vrjugglua/lua/").string();
            startingPlaces.push_back(
                (fs::path(_root) / "share/vrjugglua/").string());
        } else {
            _root = _findFilePath(startingPlaces, "vrjlua-init.lua");
            _luaDir = _root;
        }
        std::string sourceTreeIndicator =
            (fs::path(_luaDir) / "vrjlua-sourcetreeloc.lua").string();
        if (fs::exists(sourceTreeIndicator)) {
            std::ifstream df(sourceTreeIndicator.c_str());
            if (df.is_open()) {
                std::string line;
                std::getline(df, line);
                boost::algorithm::trim(line);
                if (!line.empty()) {
                    VRJLUA_MSG_START(dbgVRJLUA, MSG_STATUS)
                        << "LuaPath: Presence of file " << sourceTreeIndicator
                        << " indicated we are running from a build tree, "
                           "adding extra path hint " << line
                        << VRJLUA_MSG_END(dbgVRJLUA, MSG_STATUS);
                    startingPlaces.push_back(line);
                }
            }
        }
        _shareDir = _findFilePath(startingPlaces,
                                  "assets/fonts/droid-fonts/DroidSans.ttf");
        _jugglerRoot = _findJuggler();
        _setJugglerEnvironment();
    }
Example #9
0
void newton(double x,double eps){
  int num=0,i;
  double ax[MAX+1],dx;
  ax[0]=x;
  for(i=0;i<MAX;i++){
    dx=-1*f(ax[i])/df(ax[i]);
    ax[i+1]=ax[i]+dx;
    if(fabs(dx)<eps){
      num=i+1;
      break;
    }
  }
  if(num==0)printf("Over the limit of times\n");
  else printf("answer is:%lf at %d times\n",ax[num],num);
}
Example #10
0
void TestExprDiff::cst_grad() {
	Function f("x","y","z","10*(x-y)");
	Function df(f,Function::DIFF);
	const ExprNode& y=df.expr();
	const ExprConstant* c = dynamic_cast<const ExprConstant*>(&y);

	CPPUNIT_ASSERT(c);
	CPPUNIT_ASSERT(c->dim.is_vector());
	IntervalVector v(3);
	v[0]=Interval(10,10);
	v[1]=Interval(-10,-10);
	v[2]=Interval(0,0);
	check(c->get_vector_value(),v);
	CPPUNIT_ASSERT((c->get_vector_value()).is_superset(v));
}
Example #11
0
/* Function for passing over the network (backward pass) */
void backwardRun() {
    int from[2],to[2]; // declarations of auxiliary arrays
    
    /*      Compute deltas in output layers      */
    for (int i = FO, j = 0; i <= LO; i++, j++) { // from first to last neuron in output layer
        d(i) = (dv(j) - y(i)) * df(x(i));        // using formula to compute deltas on output layer
        //printf("\nd(%d) = (dv(%d) - y(%d)) * df(x(%d))",i,j,i,i);
    }
    //printf("\n---------");
    
    /* Compute deltas in first hidden layer  */
    from[0] = F1H; to[0] = L1H;              // definitions from-to for j (from first to last in first hidden layer)
    from[1] =  FO; to[1] =  LO;              // definitions from-to for i (from first to last in second hidden layer)
    deltaRun(from,to);                       // runs function
}
 void DBARS::add_point(double z){
   if(z > x.back()){
     throw_exception<std::runtime_error>("z out of bounds (too large) in DBARS::add_point");
   }
   if(z < x[0]){
     throw_exception<std::runtime_error>("z out of bounds (too small) in DBARS::add_point");
   }
   IT it = std::lower_bound(x.begin(), x.end(), z);
   int k = it - x.begin();
   x.insert(it, z);
   logf.insert(logf.begin()+k, f(z));
   dlogf.insert(dlogf.begin() + k, df(z));
   refresh_knots();
   update_cdf();
 }
Example #13
0
void IntlTestDecimalFormatSymbols::Verify(double value, const UnicodeString& pattern,
                                          const DecimalFormatSymbols &sym, const UnicodeString& expected){
    UErrorCode status = U_ZERO_ERROR;
    DecimalFormat df(pattern, sym, status);
    if(U_FAILURE(status)){
        errln("ERROR: construction of decimal format failed - %s", u_errorName(status));
    }
    UnicodeString buffer;
    FieldPosition pos(FieldPosition::DONT_CARE);
    buffer = df.format(value, buffer, pos);
    if(buffer != expected){
        errln((UnicodeString)"ERROR: format() returns wrong result\n Expected " +
            expected + ", Got " + buffer);
    }
}
Example #14
0
 void Tn2Sampler::add_point(double z){
   if(z > x.back()){
     report_error("z out of bounds (too large) in Tn2Sampler::add_point");
   }
   if(z < x[0]){
     report_error("z out of bounds (too small) in Tn2Sampler::add_point");
   }
   IT it = std::lower_bound(x.begin(), x.end(), z);
   int k = it - x.begin();
   x.insert(it, z);
   logf.insert(logf.begin()+k, f(z));
   dlogf.insert(dlogf.begin() + k, df(z));
   refresh_knots();
   update_cdf();
 }
bool write_bin_offset(const wchar_t *file, const void *buffer, int buflen, int offset)
// записывает кусок файла по текущему смещению из буфера, файл должен существовать!
// может писать в любую часть файла, в т.ч. с увеличением его первонач-го размера,
// пропущенные при этом куски заполняются нулями (если смещение больше длины файла)
{
  if ( buflen < 0 || offset < 0 ) return false;

  FILEopen df( file, L"r+b" ); // w+b работает не так как надо!
  if ( !df ) return false;

  if ( fseek(df, offset, SEEK_SET) != 0 ) return false;

  int wnum = (int)fwrite( buffer, 1, buflen, df );
  return wnum == buflen;
}
Example #16
0
bool df(int v,int col)
{
    if(!c[v])
    {
        c[v]=col;
        if(col==1)
            ++ans;
        for(int i=1;i<=n;++i)
            if(p[v][i] && !df(i,(col==1?2:1)))
                return 0;
    }
    else if(c[v]!=col)
        return 0;
    return 1;
}
Example #17
0
void KDesktopFileTest::testRead()
{
    const QString fileName = QFile::decodeName(KDESRCDIR "/../services/kplugininfo.desktop");
    QVERIFY(QFile::exists(fileName));
    QVERIFY(KDesktopFile::isDesktopFile(fileName));
    KDesktopFile df(fileName);
    QCOMPARE(df.readType(), QString::fromLatin1("ServiceType"));
    QCOMPARE(df.readIcon(), QString());
    QCOMPARE(df.readName(), QString::fromLatin1("KDE Plugin Information"));
    QCOMPARE(df.hasLinkType(), false);
    QCOMPARE(df.hasMimeTypeType(), false);
    QCOMPARE(df.hasApplicationType(), false);
    QCOMPARE(df.fileName(), KStandardDirs::realFilePath(fileName));
    QCOMPARE(df.resource(), "xdgdata-apps"); // default for .desktop files
}
void ToolsConfigWidget::fillListBox(QListBox *lb, const QDict<ToolsConfigEntry> &entryDict)
{
    lb->clear();

    QDictIterator<ToolsConfigEntry> it(entryDict);
    for (; it.current(); ++it) {
        ToolsConfigEntry *entry = it.current();
        if (entry->isdesktopfile) {
            KDesktopFile df(entry->cmdline);
            lb->insertItem(SmallIcon(df.readIcon()), entry->menutext);
        } else {
            lb->insertItem(entry->menutext);
        }
    }
}
Example #19
0
void df(int nod)
{
	lista *p;

	Flag[nod] = 1;

	for (p = L[nod]; p != NULL; p = p -> next)
		if (!Flag[p -> nod])
		{
			leaga2(nod, p -> nod);
			Tata[p -> nod] = nod;
			Grad[nod]++;
			df(p -> nod);
		}
	Flag[nod] = 0;
}
Example #20
0
void polynomialBasis::df(const fullMatrix<double> &coord,
                         fullMatrix<double> &dfm) const
{
  double dfv[1256][3];
  dfm.resize(coord.size1() * 3, coefficients.size1(), false);
  int dimCoord = coord.size2();
  for(int iPoint = 0; iPoint < coord.size1(); iPoint++) {
    df(coord(iPoint, 0), dimCoord > 1 ? coord(iPoint, 1) : 0.,
       dimCoord > 2 ? coord(iPoint, 2) : 0., dfv);
    for(int i = 0; i < coefficients.size1(); i++) {
      dfm(iPoint * 3 + 0, i) = dfv[i][0];
      dfm(iPoint * 3 + 1, i) = dfv[i][1];
      dfm(iPoint * 3 + 2, i) = dfv[i][2];
    }
  }
}
	/** Test {@link Minimizable::calculateFunctionAndDerivative} in 0-dimensional case. */
	void MinimizableTest::test0dim () {
		const AutoVector minVec( 0 );
		TestMinimizable minimizable( minVec );
		const AutoVector x( 0 );
		double f;
		AutoVector df( 0 );
		minimizable.calculateFunction( x, f );
		assert_eq( "function value", 0.0, f );

		minimizable.calculateDerivative( x, df );
		assert_eq( "derivative dimension", 0, df.countDimensions() );

		minimizable.calculateFunctionAndDerivative( x, f, df );
		assert_eq( "again function value", 0.0, f );
		assert_eq( "again derivative dimension", 0, df.countDimensions() );
	}
Example #22
0
/*
 * li_api_destroy - destroy value indexer
 *    return: void
 *    indexer(in): VALUE_INDEXER
 *    df(in): element destroy function
 */
static void
li_api_destroy (VALUE_INDEXER * indexer, void (*df) (VALUE_AREA * va, API_VALUE * db))
{
  LIST_INDEXER *li = (LIST_INDEXER *) indexer;

  assert (li != NULL);
  while (!dlisth_is_empty (&li->elems))
    {
      LIST_INDEXER_ELEM *e = (LIST_INDEXER_ELEM *) li->elems.next;
      if (df)
	df (e->va, e->value);
      dlisth_delete ((dlisth *) e);
      API_FREE (e);
    }
  API_FREE (li);
}
Example #23
0
void KDesktopFileTest::testUnsuccessfulTryExec()
{
    KTemporaryFile file;
    file.setPrefix("test1");
    QVERIFY( file.open() );
    const QString fileName = file.fileName();
    QTextStream ts( &file );
    ts <<
        "[Desktop Entry]\n"
        "TryExec=/does/not/exist\n"
        "\n";
    file.close();
    QVERIFY(QFile::exists(fileName));
    KDesktopFile df(fileName);
    QCOMPARE(df.tryExec(), false);
}
Example #24
0
        value_type operator()( pointer x_ ) const
        {
            value_type const orig_xn      = *(x_ + n);
            size_type const     cn        = n;
            pointer             cx        = x_;
            unary_function_type const& uf = [ cn, cx, this ]( value_type x ) { cx[cn] = x; return ((*this).func)(cx); };
            value_type const x            = *(x_+n);

            derivative<0, value_type(value_type)> const df( uf );

            value_type const ans = df(x);

            *(x_ + n) = orig_xn;

            return ans;
        }
Example #25
0
int main(int argc, char **argv)
{
	// open the file passed in on the command-line
	assert(argc > 1);
	FILE* f = fopen(argv[1], "r");
	
	// construct a dwarf::file
	dwarf::file df(fileno(f));

	dwarf::abi_information info(df);
	
	Dwarf_Off start_offset = info.get_dies().begin()->first;	
	dwarf::print_action action(info);
	namespace w = dwarf::walker;
	w::depthfirst_walker<dwarf::print_action> print_walk(action);
	
	// print out before
	print_walk(info.get_dies(), start_offset);
	
	// first first two structure types
	
	typedef w::func1_do_nothing<Dwarf_Half> do_nothing_t;
	
	typedef w::siblings_upward_walker<do_nothing_t, 
		w::tag_equal_to_matcher_t> first_walker_t;
		
	const w::tag_equal_to_matcher_t matcher = w::matcher_for_tag_equal_to(DW_TAG_structure_type);
	
	Dwarf_Off first_struct = *(w::find_first_match<w::tag_equal_to_matcher_t, first_walker_t>(
		info.get_dies(), 0UL, matcher));
	
	typedef w::siblings_upward_walker<w::capture_func<Dwarf_Off>, 
		w::tag_equal_to_matcher_t> second_walker_t;
		
	w::capture_func<Dwarf_Off> capture;
	w::select_until_captured until_captured(capture);
	second_walker_t second_find_walker(capture, matcher, until_captured);
	
	second_find_walker(info.get_dies(), first_struct);	
	Dwarf_Off second_struct = *(capture.captured);
	
	// swap them
	std::swap(info.get_dies()[first_struct], info.get_dies()[second_struct]);
	
	// print out now
	print_walk(info.get_dies(), start_offset);
}
Example #26
0
    Status MmapV1ExtentManager::init(OperationContext* txn) {
        verify( _files.size() == 0 );

        for ( int n = 0; n < DiskLoc::MaxFiles; n++ ) {
            boost::filesystem::path fullName = fileName( n );
            if ( !boost::filesystem::exists( fullName ) )
                break;

            string fullNameString = fullName.string();

            {
                // If the file is uninitialized we exit the loop because it is just prealloced. We
                // do this on a bare File object rather than using the DataFile because closing a
                // DataFile triggers dur::closingFileNotification() which is fatal if there are any
                // pending writes. Therefore we must only open files that we know we want to keep.
                File preview;
                preview.open(fullNameString.c_str(), /*readOnly*/ true);
                invariant(preview.is_open());
                if (preview.len() < sizeof(DataFileHeader))
                    break; // can't be initialized if too small.

                // This is the equivalent of DataFileHeader::uninitialized().
                int version;
                preview.read(0, reinterpret_cast<char*>(&version), sizeof(version));
                invariant(!preview.bad());
                if (version == 0)
                    break;

            }

            auto_ptr<DataFile> df( new DataFile(n) );

            Status s = df->openExisting( txn, fullNameString.c_str() );
            if ( !s.isOK() ) {
                return s;
            }

            invariant(!df->getHeader()->uninitialized());

            // We only checkUpgrade on files that we are keeping, not preallocs.
            df->getHeader()->checkUpgrade(txn);

            _files.push_back( df.release() );
        }

        return Status::OK();
    }
Example #27
0
/* Version with also sigma integration: returns a vector of dimension 5 */
struct vec6d rhoInteg_vec (const double vr, const double vphi, const double vz, void * params){

	struct IntegPar * par = (struct IntegPar*) params;
	double Ve = par->Ve;
	double *x = par->x;

	/* rescaling the integral to [0,1]x[-1,1]x[0,1] */
	double V[3] = {1e-6+Ve*vr, 1e-6+Ve*vphi, 1e-6+Ve*vz};
	double jacob = Ve*Ve*Ve;
	double DF = df(x,V);

	struct vec6d res = {jacob*DF,jacob*DF*V[1],jacob*DF*V[0]*V[0],
						jacob*DF*V[1]*V[1],jacob*DF*V[2]*V[2],
						jacob*DF*V[0]*V[2] };

	return res;
}
int read_bin_offset(const wchar_t *file, void *buffer, int maxbuflen, int offset)
// читает кусок файла по текущему смещению, возврящает число прочитанных байт
{
  if ( maxbuflen <= 0 || offset < 0 ) return 0;

  FILEopen df(file, L"rb");
  if ( !df ) return 0;

  if ( fseek(df, offset, SEEK_SET) != 0 ) return 0;

  maxbuflen = (int)fread(buffer, 1, maxbuflen, df);

  int err = ferror(df);
  if (err != 0) return 0;

  return maxbuflen;
}
Example #29
0
shared_ptr<DataFrame> RubberSheet::_buildDataFrame(Status s) const
{
  shared_ptr<DataFrame> df(new DataFrame());
  vector<string> labels;
  labels.push_back("x");
  labels.push_back("y");
  labels.push_back("dx");
  labels.push_back("dy");
  vector<int> types(4, DataFrame::Numerical);
  df->setFactorLabels(labels);
  df->setFactorTypes(types);

  vector<double> d(4);

  /// @todo This should be replaced with an circular error based method at some point.
  double multiplier;
  if (_ref)
  {
    multiplier = 1.0;
  }
  else
  {
    multiplier = 0.5;
  }

  for (size_t i = 0; i < _ties.size(); i++)
  {
    if (s == Status::Unknown1)
    {
      d[0] = _ties[i].c1.x;
      d[1] = _ties[i].c1.y;
      d[2] = -_ties[i].dx() * multiplier;
      d[3] = -_ties[i].dy() * multiplier;
    }
    else
    {
      d[0] = _ties[i].c2.x;
      d[1] = _ties[i].c2.y;
      d[2] = _ties[i].dx() * multiplier;
      d[3] = _ties[i].dy() * multiplier;
    }
    df->addDataVector("", d);
  }

  return df;
}
Example #30
0
int main()
{
	float aa,xn,x0;
	int i;
	clrscr();
	printf("function is x^2+6x+8") ;
	printf("\nenter the initial value: ");
	scanf("%f",&x0);
	xn=x0;
   while(f(xn)!=0)
   {
		xn=xn - (f(xn)/df(xn));
		printf("\n%f",xn) ;
   }
   getch();
   return 0;
}