KListRef Win32UserWindow::SelectFile(bool saveDialog, bool multiple, std::string& title,
	std::string& path, std::string& defaultName, std::vector<std::string>& types,
	std::string& typesDescription)
{
	std::wstring filter;
	std::wstring typesDescriptionW = ::UTF8ToWide(typesDescription);
	if (types.size() > 0)
	{
		//"All\0*.*\0Test\0*.TXT\0";
		if (typesDescription.size() == 0)
		{
			// Reasonable default?
			typesDescriptionW = L"Selected Files";
		}
		filter.append(typesDescriptionW);
		filter.push_back(L'\0');
		
		for (int i = 0; i < types.size(); i++)
		{
			std::string type = types.at(i);
			std::wstring typeW = ::UTF8ToWide(type);
			//multiple filters: "*.TXT;*.DOC;*.BAK"
			size_t found = type.find("*.");
			if (found != 0)
			{
				filter.append(L"*.");
			}
			filter.append(typeW);
			filter.append(L";");
		}
		filter.push_back(L'\0');
	}

	OPENFILENAME ofn;

	std::wstring pathW = ::UTF8ToWide(path);
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = this->windowHandle;

	// Windows may not null-terminate the string it puts here, so we zero it.
	wchar_t filenameW[MAX_FILE_DIALOG_STRING];
	ZeroMemory(&filenameW, MAX_FILE_DIALOG_STRING * sizeof(wchar_t));
	wcscpy(filenameW, ::UTF8ToWide(defaultName).c_str());
	ofn.lpstrFile = filenameW;

	ofn.nMaxFile = MAX_FILE_DIALOG_STRING;
	ofn.lpstrFilter = (LPWSTR) (filter.size() == 0 ? 0 : filter.c_str());
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = 0;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = (LPWSTR) (pathW.length() == 0 ? 0 : pathW.c_str());
	ofn.Flags = OFN_EXPLORER;

	std::wstring titleW;
	if (!title.empty())
	{
		titleW = ::UTF8ToWide(title);
		ofn.lpstrTitle = titleW.c_str();
	}

	if (!saveDialog)
	{
		ofn.Flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
	}

	if (multiple)
	{
		ofn.Flags |= OFN_ALLOWMULTISELECT;
	}

	
	BOOL result;
	if (saveDialog)
	{
		result = ::GetSaveFileName(&ofn);
	}
	else
	{
		result = ::GetOpenFileName(&ofn);
	}

	// A zero-return value here indicates either an error or that the user
	// cancelled the action (CommDlgExtendedError returns 0). We should
	// return a helpful exception if it's an error.
	if (!result)
	{
		DWORD code = CommDlgExtendedError();
		if (code == 0)
			return new StaticBoundList();

		throw ValueException::FromFormat(
			"File dialog action failed with error code: %i", code);
	}

	// From:  http://msdn.microsoft.com/en-us/library/ms646839(VS.85).aspx
	// If multiple files have been selected there will be two '\0' characters
	// at the end of this array of characters, so if we enabled multiple file
	// selected, just check for that second '\0'.
	KListRef results = new StaticBoundList();
	if (multiple && ofn.lpstrFile[ofn.nFileOffset - 1] == L'\0')
	{
		std::vector<std::wstring> files;
		ParseMultipleSelectedFiles(&ofn, files);
		for (size_t i = 0; i < files.size(); i++)
		{
			results->Append(Value::NewString(
				::WideToUTF8(files[i])));
		}
	}
	else
	{
		results->Append(Value::NewString(::WideToUTF8(
			ofn.lpstrFile)));
	}

	return results;
}
Example #2
0
Argument Sphere_SDFOP::getArgument(unsigned int index)
{
    return args.at(index);
}
Example #3
0
long double* getVariable(long double variablePos) {
    return &variableMap[vecVariablesNames.at(variablePos)];
}
Example #4
0
static int completion_try_print(int cols,
                                const wchar_t *prefix,
                                int is_quoted,
                                std::vector<comp_t *> &lst)
{
    /*
      The calculated preferred width of each column
    */
    int pref_width[PAGER_MAX_COLS];
    /*
      The calculated minimum width of each column
    */
    int min_width[PAGER_MAX_COLS];
    /*
      If the list can be printed with this width, width will contain the width of each column
    */
    int *width=pref_width;
    /*
      Set to one if the list should be printed at this width
    */
    int print=0;

    long i, j;

    int rows = (int)((lst.size()-1)/cols+1);

    int pref_tot_width=0;
    int min_tot_width = 0;
    int res=PAGER_RETRY;
    /*
      Skip completions on tiny terminals
    */

    if (termsize.ws_col < PAGER_MIN_WIDTH)
        return PAGER_DONE;

    memset(pref_width, 0, sizeof(pref_width));
    memset(min_width, 0, sizeof(min_width));

    /* Calculate how wide the list would be */
    for (j = 0; j < cols; j++)
    {
        for (i = 0; i<rows; i++)
        {
            int pref,min;
            comp_t *c;
            if (lst.size() <= j*rows + i)
                continue;

            c = lst.at(j*rows + i);
            pref = c->pref_width;
            min = c->min_width;

            if (j != cols-1)
            {
                pref += 2;
                min += 2;
            }
            min_width[j] = maxi(min_width[j],
                                min);
            pref_width[j] = maxi(pref_width[j],
                                 pref);
        }
        min_tot_width += min_width[j];
        pref_tot_width += pref_width[j];
    }
    /*
      Force fit if one column
    */
    if (cols == 1)
    {
        if (pref_tot_width > termsize.ws_col)
        {
            pref_width[0] = termsize.ws_col;
        }
        width = pref_width;
        print=1;
    }
    else if (pref_tot_width <= termsize.ws_col)
    {
        /* Terminal is wide enough. Print the list! */
        width = pref_width;
        print=1;
    }
    else
    {
        long next_rows = (lst.size()-1)/(cols-1)+1;
        /*    fwprintf( stderr,
          L"cols %d, min_tot %d, term %d, rows=%d, nextrows %d, termrows %d, diff %d\n",
          cols,
          min_tot_width, termsize.ws_col,
          rows, next_rows, termsize.ws_row,
          pref_tot_width-termsize.ws_col );
        */
        if (min_tot_width < termsize.ws_col &&
                (((rows < termsize.ws_row) && (next_rows >= termsize.ws_row)) ||
                 (pref_tot_width-termsize.ws_col< 4 && cols < 3)))
        {
            /*
              Terminal almost wide enough, or squeezing makes the
              whole list fit on-screen.

              This part of the code is really important. People hate
              having to scroll through the completion list. In cases
              where there are a huge number of completions, it can't
              be helped, but it is not uncommon for the completions to
              _almost_ fit on one screen. In those cases, it is almost
              always desirable to 'squeeze' the completions into a
              single page.

              If we are using N columns and can get everything to
              fit using squeezing, but everything would also fit
              using N-1 columns, don't try.
            */

            int tot_width = min_tot_width;
            width = min_width;

            while (tot_width < termsize.ws_col)
            {
                for (i=0; (i<cols) && (tot_width < termsize.ws_col); i++)
                {
                    if (width[i] < pref_width[i])
                    {
                        width[i]++;
                        tot_width++;
                    }
                }
            }
            print=1;
        }
    }

    if (print)
    {
        res=PAGER_DONE;
        if (rows < termsize.ws_row)
        {
            /* List fits on screen. Print it and leave */
            if (is_ca_mode)
            {
                is_ca_mode = 0;
                writembs(exit_ca_mode);
            }

            completion_print(cols, width, 0, rows, prefix, is_quoted, lst);
            pager_flush();
        }
        else
        {
            int npos, pos = 0;
            int do_loop = 1;

            /*
              Enter ca_mode, which means that the terminal
              content will be restored to the current
              state on exit.
            */
            if (enter_ca_mode && exit_ca_mode)
            {
                is_ca_mode=1;
                writembs(enter_ca_mode);
            }


            completion_print(cols,
                             width,
                             0,
                             termsize.ws_row-1,
                             prefix,
                             is_quoted,
                             lst);
            /*
              List does not fit on screen. Print one screenfull and
              leave a scrollable interface
            */
            while (do_loop)
            {
                set_color(rgb_color_t::black(), get_color(HIGHLIGHT_PAGER_PROGRESS));
                wcstring msg = format_string(_(L" %d to %d of %d"), pos, pos+termsize.ws_row-1, rows);
                msg.append(L"   \r");

                writestr(msg.c_str());
                set_color(rgb_color_t::normal(), rgb_color_t::normal());
                pager_flush();
                int c = readch();

                switch (c)
                {
                    case LINE_UP:
                    {
                        if (pos > 0)
                        {
                            pos--;
                            writembs(tparm(cursor_address, 0, 0));
                            writembs(scroll_reverse);
                            completion_print(cols,
                                             width,
                                             pos,
                                             pos+1,
                                             prefix,
                                             is_quoted,
                                             lst);
                            writembs(tparm(cursor_address,
                                           termsize.ws_row-1, 0));
                            writembs(clr_eol);

                        }

                        break;
                    }

                    case LINE_DOWN:
                    {
                        if (pos <= (rows - termsize.ws_row))
                        {
                            pos++;
                            completion_print(cols,
                                             width,
                                             pos+termsize.ws_row-2,
                                             pos+termsize.ws_row-1,
                                             prefix,
                                             is_quoted,
                                             lst);
                        }
                        break;
                    }

                    case PAGE_DOWN:
                    {

                        npos = mini((int)(rows - termsize.ws_row+1), (int)(pos + termsize.ws_row-1));
                        if (npos != pos)
                        {
                            pos = npos;
                            completion_print(cols,
                                             width,
                                             pos,
                                             pos+termsize.ws_row-1,
                                             prefix,
                                             is_quoted,
                                             lst);
                        }
                        else
                        {
                            if (flash_screen)
                                writembs(flash_screen);
                        }

                        break;
                    }

                    case PAGE_UP:
                    {
                        npos = maxi(0,
                                    pos - termsize.ws_row+1);

                        if (npos != pos)
                        {
                            pos = npos;
                            completion_print(cols,
                                             width,
                                             pos,
                                             pos+termsize.ws_row-1,
                                             prefix,
                                             is_quoted,
                                             lst);
                        }
                        else
                        {
                            if (flash_screen)
                                writembs(flash_screen);
                        }
                        break;
                    }

                    case R_NULL:
                    {
                        do_loop=0;
                        res=PAGER_RESIZE;
                        break;

                    }

                    default:
                    {
                        out_buff.push_back(c);
                        do_loop = 0;
                        break;
                    }
                }
            }
            writembs(clr_eol);
        }
    }
    return res;
}
Example #5
0
std::vector<gmtl::Point3f> nPoints(std::vector<gmtl::Point3f> verts, char shape)
{
	std::vector<gmtl::Point3f> _normals;
	switch (shape)
	{

	case 's':
		for (GLuint i = 0; i < verts.size();)
		{
			gmtl::Point3f oldP = verts.at(i);
			//magnitude given by a^2 + b^2 + c^2
			GLfloat oldX = oldP[0];
			GLfloat oldY = oldP[1];
			GLfloat oldZ = oldP[2];
			GLfloat magnitude = sqrt(oldX * oldX + oldY * oldY + oldZ * oldZ);
			//normalized value given by vert/magnitude
			GLfloat newX = oldX / magnitude;
			GLfloat newY = oldY / magnitude;
			GLfloat newZ = oldZ / magnitude;

			gmtl::Point3f newP(newX, newY, newZ);
			_normals.push_back(newP);
			i++;
		}
		break;
	case 'c':
		for (GLuint i = 0; i < verts.size();)
		{
			gmtl::Point3f oldP = verts.at(i);
			//magnitude given by a^2 + b^2 + c^2
			GLfloat oldX = oldP[0];
			GLfloat oldY = oldP[1];
			GLfloat oldZ = oldP[2];
			GLfloat magnitude = sqrt(oldX * oldX + oldY * oldY + oldZ * oldZ);
			//normalized value given by vert/magnitude
			GLfloat newX = oldX / magnitude;
			GLfloat newY = oldY / magnitude;
			GLfloat newZ = oldZ / magnitude;

			gmtl::Point3f newP(newX, newY, newZ);
			_normals.push_back(newP);
			i++;
		}
		break;
	case 'a':
		for (GLuint i = 0; i < verts.size();)
		{
			gmtl::Point3f oldP = verts.at(i);
			//magnitude given by a^2 + b^2 + c^2
			GLfloat oldX = oldP[0];
			GLfloat oldY = oldP[1];
			GLfloat oldZ = oldP[2];
			GLfloat magnitude = sqrt(oldX * oldX + oldY * oldY + oldZ * oldZ);
			//normalized value given by vert/magnitude
			GLfloat newX = oldX / magnitude;
			GLfloat newY = oldY / magnitude;
			GLfloat newZ = oldZ / magnitude;

			gmtl::Point3f newP(newX, newY, newZ);
			_normals.push_back(newP);
			i++;
		}
		break;
	case 'b':
		for (GLuint i = 0; i < verts.size();)
		{
			gmtl::Point3f oldP = verts.at(i);
			//magnitude given by a^2 + b^2 + c^2
			GLfloat oldX = oldP[0];
			GLfloat oldY = oldP[1];
			GLfloat oldZ = oldP[2];
			GLfloat magnitude = sqrt(oldX * oldX + oldY * oldY + oldZ * oldZ);
			//normalized value given by vert/magnitude
			GLfloat newX = oldX / magnitude;
			GLfloat newY = oldY / magnitude;
			GLfloat newZ = oldZ / magnitude;

			gmtl::Point3f newP(newX, newY, newZ);
			_normals.push_back(newP);
			i++;
		}
		break;
	}


	return _normals;
}
Example #6
0
inline void Maxscoreqi::evaluate(lptrArray& lps, QpResult* res, const float& threshold, const int topK, const int& num_of_essential_lists, int& smallest_did, std::vector <float>& lists_maxscore, const float& current_prefix_sum_max_score, bool& check_for_new_essential_list, const int& threshold_unknown, const int& comparison, int& next_smallest_did) {
    bool failure = false;
    float final_score = 0.0f;
    next_smallest_did = CONSTS::MAXD + 1;

    string terms[2];
    float scores[2];
    int freq[2];

    scores[0] = 0;
    scores[1] = 0;
    freq[0] = 0;
    freq[1] = 0;

    float frequency = 0;
    float score = 0;

    // evaluate dids == to smallest_did in the essential lists
    //for (int i=num_of_essential_lists; i<lps.size(); i++) {         // In order version
    for (int i = lps.size()-1; i>=num_of_essential_lists; --i) {      // Reverse order version

        terms[i] = lps[i]->term;

        if (smallest_did == lps[i]->did) {
            //PROFILER(CONSTS::EVAL);
            //PROFILER(CONSTS::GETFREQ);
            //PROFILER(CONSTS::ESSENTIAL);
            const float frequency = lps[i]->getFreq();
            const float score = lps[i]->calcScore(frequency,pages[smallest_did]);
            scores[i] = score;
            freq[i] = frequency;
            final_score += score;
            lps[i]->did = lps[i]->nextGEQ( smallest_did + 1 );
            //PROFILER(CONSTS::NEXTGEQ);
        }

        // pick next smallest did
        if (lps[i]->did < next_smallest_did)
            next_smallest_did = lps[i]->did;
    }

    // early termination = prefix + final score of essential lists
    float early_termination = current_prefix_sum_max_score + final_score;

    // if early termination check is passed, evaluate smallest did in the non-essential set
    if (! (Fcompare(early_termination, threshold) <= comparison)) {
        // evaluate dids == to smallest_did in the non essential lists
        //for (int i = 0; i < num_of_essential_lists; ++i)	{       // In order version
        for (int i=num_of_essential_lists-1; i>=0; --i)	{           // Reverse order version

            terms[i] = lps[i]->term;

            // move pointers if needed
            if (lps[i]->did < smallest_did) {
                //PROFILER(CONSTS::NEXTGEQ1);
                lps[i]->did = lps[i]->nextGEQ(smallest_did);
                //PROFILER(CONSTS::NEXTGEQ);
            }

            // check if evaluation is needed
            if (smallest_did == lps[i]->did) {
                //PROFILER(CONSTS::EVAL);
                //PROFILER(CONSTS::GETFREQ);
                //PROFILER(CONSTS::NONESSENTIAL);
                const float frequency = lps[i]->getFreq();
                const float score = lps[i]->calcScore(frequency,pages[smallest_did]);
                scores[i] = score;
                freq[i] = frequency;
                final_score += score;
                early_termination -= (lists_maxscore.at(i) - score);
            } else
                early_termination -= lists_maxscore.at(i);

            // early termination
            if (Fcompare(early_termination, threshold) <= comparison) {
                failure = true;
                //PROFILER(CONSTS::EARLYTERMINATION2);
                break;
            }
        }

        // if not failure, heapify new result
        if ((!failure) && (Fcompare(final_score, threshold) >= threshold_unknown)) {
            //PROFILER(CONSTS::HEAPIFY);
            check_for_new_essential_list = true;
            int j;
            for (j = topK-2; (j >= 0) && (Fcompare(final_score, res[j].score)==1); j--)
                res[j+1]=res[j];
            // res[j+1].setR(smallest_did,final_score);
            res[j+1].setRQi(smallest_did,final_score,terms,scores,freq);
        }
    } else {  // togo
        //PROFILER(CONSTS::EARLYTERMINATION1);
    }
}
 int& operator()(size_t x, size_t y, size_t z) {
     return m_data.at(x + y * m_width + z * m_width * m_height);
 }
Example #8
0
  const CPASAnimState* GetAnimStateByIndex(s32 index) const {
    if (index < 0 || index >= x0_states.size())
      return nullptr;

    return &x0_states.at(index);
  }
Example #9
0
void XMLUtils::SetStringArray(TiXmlNode* pRootNode, const char *strTag, const std::vector<std::string>& arrayValue)
{
  for (unsigned int i = 0; i < arrayValue.size(); i++)
    SetString(pRootNode, strTag, arrayValue.at(i));
}
Example #10
0
/***********************************************************************
 * Structors
 **********************************************************************/
dbsrx::dbsrx(ctor_args_t args) : rx_dboard_base(args){
    //warn user about incorrect DBID on USRP1, requires R193 populated
    if (this->get_iface()->get_special_props().soft_clock_divider and this->get_rx_id() == 0x000D)
        UHD_LOGGER_WARNING("DBSRX") << boost::format(
                "DBSRX: incorrect dbid\n"
                "Expected dbid 0x0002 and R193\n"
                "found dbid == %d\n"
                "Please see the daughterboard app notes"
                ) % this->get_rx_id().to_pp_string();

    //warn user about incorrect DBID on non-USRP1, requires R194 populated
    if (not this->get_iface()->get_special_props().soft_clock_divider and this->get_rx_id() == 0x0002)
        UHD_LOGGER_WARNING("DBSRX") << boost::format(
                "DBSRX: incorrect dbid\n"
                "Expected dbid 0x000D and R194\n"
                "found dbid == %d\n"
                "Please see the daughterboard app notes"
                ) % this->get_rx_id().to_pp_string();

    //send initial register settings
    this->send_reg(0x0, 0x5);

    //set defaults for LO, gains, and filter bandwidth
    double codec_rate = this->get_iface()->get_codec_rate(dboard_iface::UNIT_RX);
    _bandwidth = 0.8*codec_rate/2.0; // default to anti-alias at different codec_rate

    ////////////////////////////////////////////////////////////////////
    // Register properties
    ////////////////////////////////////////////////////////////////////
    this->get_rx_subtree()->create<std::string>("name")
        .set("DBSRX");
    this->get_rx_subtree()->create<sensor_value_t>("sensors/lo_locked")
        .set_publisher(boost::bind(&dbsrx::get_locked, this));
    for(const std::string &name:  dbsrx_gain_ranges.keys()){
        this->get_rx_subtree()->create<double>("gains/"+name+"/value")
            .set_coercer(boost::bind(&dbsrx::set_gain, this, _1, name))
            .set(dbsrx_gain_ranges[name].start());
        this->get_rx_subtree()->create<meta_range_t>("gains/"+name+"/range")
            .set(dbsrx_gain_ranges[name]);
    }
    this->get_rx_subtree()->create<double>("freq/value")
        .set_coercer(boost::bind(&dbsrx::set_lo_freq, this, _1));
    this->get_rx_subtree()->create<meta_range_t>("freq/range")
        .set(dbsrx_freq_range);
    this->get_rx_subtree()->create<std::string>("antenna/value")
        .set(dbsrx_antennas.at(0));
    this->get_rx_subtree()->create<std::vector<std::string> >("antenna/options")
        .set(dbsrx_antennas);
    this->get_rx_subtree()->create<std::string>("connection")
        .set("IQ");
    this->get_rx_subtree()->create<bool>("enabled")
        .set(true); //always enabled
    this->get_rx_subtree()->create<bool>("use_lo_offset")
        .set(false);
    this->get_rx_subtree()->create<double>("bandwidth/value")
        .set_coercer(boost::bind(&dbsrx::set_bandwidth, this, _1));
    this->get_rx_subtree()->create<meta_range_t>("bandwidth/range")
        .set(dbsrx_bandwidth_range);

    //enable only the clocks we need
    this->get_iface()->set_clock_enabled(dboard_iface::UNIT_RX, true);

    //set the gpio directions and atr controls (identically)
    this->get_iface()->set_pin_ctrl(dboard_iface::UNIT_RX, 0x0); // All unused in atr
    if (this->get_iface()->get_special_props().soft_clock_divider){
        this->get_iface()->set_gpio_ddr(dboard_iface::UNIT_RX, 0x1); // GPIO0 is clock when on USRP1
    }
    else{
        this->get_iface()->set_gpio_ddr(dboard_iface::UNIT_RX, 0x0); // All Inputs
    }

    //now its safe to set inital freq and bw
    this->get_rx_subtree()->access<double>("freq/value")
        .set(dbsrx_freq_range.start());
    this->get_rx_subtree()->access<double>("bandwidth/value")
        .set(2.0*_bandwidth); //_bandwidth in lowpass, convert to complex bandpass
}
Example #11
0
int main(int argc, char* argv[])
{
    char* infile = argv[1];

    if (argc < 2)
    {
        std::cerr << "Usage:" << argv[0] << " INPUT" << std::endl;
        return 1;
    }

    FileBuffer data(infile);
    NCFile<FileBuffer> file(data);

    std::vector<Dimension> const dims  = file.dimensions();
    std::vector<Variable>  const vars  = file.variables();
    Attributes const attrs = file.attributes();
    size_t i;

    std::cout << "netcdf " << stripname(infile) << " {" << std::endl;

    std::cout << "dimensions:" << std::endl;
    for (i = 0; i < dims.size(); ++i)
    {
        Dimension d = dims.at(i);
        std::cout << "\t" << d.name << " = " << d.size
                  << " ;" << std::endl;
    }
    std::cout << std::endl;

    std::cout << "variables:" << std::endl;
    for (i = 0; i < vars.size(); ++i)
    {
        Variable v = vars.at(i);
        std::cout << "\t" << tname(v.type()) << " " << v.name()
                  << "(" << toString(v.dimensionNames())
                  << ") ;" << std::endl;

        Attributes const attrs = v.attributes();
        for (size_t j = 0; j < attrs.size(); ++j)
        {
            Attribute a = attrs.at(j);
            std::cout << "\t\t" << v.name() << ":" << attrs.keyAt(j) << " = "
                      << formatString(a.valuesAsString())
                      << " ;" << std::endl;
        }
    }
    std::cout << std::endl;

    std::cout << "// global attributes:" << std::endl;
    for (i = 0; i < attrs.size(); ++i)
    {
        Attribute a = attrs.at(i);
        std::cout << "\t\t:" << attrs.keyAt(i) << " = "
                  << formatString(a.valuesAsString())
                  << " ;" << std::endl;
    }
    std::cout << std::endl;

    std::cout << "data:" << std::endl;
    for (i = 0; i < vars.size(); ++i)
    {
        Variable v = vars.at(i);
        std::cout << std::endl << " " << v.name() << " =" << std::endl;
        std::cout << "  " << file.valueAsString(v, 0, 0, 0)
                  << ", " << file.valueAsString(v, 1, 0, 0)
                  << ", " << file.valueAsString(v, 2, 0, 0)
                  << ", " << file.valueAsString(v, 3, 0, 0)
                  << ", " << file.valueAsString(v, 4, 0, 0)
                  << ", ... ;"
                  << std::endl;
    }

    std::cout << "}" << std::endl;
}
 void update(Cell const v)
 {
     _nrPairableFacets.at(v) = 0;
     for (size_t i = 0; i < _coI.count(v); ++i)
         --_nrPairableFacets.at(_coI(v, i));
 }
Example #13
0
 explicit Replayer(std::vector<std::string> args)
 {
   const char* actor_name     = args.at(0).c_str();
   const char* trace_filename = args.size() > 1 ? args[1].c_str() : nullptr;
   simgrid::xbt::replay_runner(actor_name, trace_filename);
 }
Example #14
0
 std::string DumpToHexString(const std::vector<Platform::byte> &data)
 {
     return DumpToHexString(&data.at(0), data.size());
 }
Example #15
0
  void stat_report_global(FILE* output) {
    assert(GLOBAL_STATS.initialized);
    stat_finish_thread();

    std::unique_lock<std::mutex> global_lock(GLOBAL_STATS_MUTEX);
    std::fprintf(output, "# Dort statistics\n");

    std::fprintf(output, "## Counters\n");
    for(uint32_t i = 0; i < _COUNTER_END; ++i) {
      std::fprintf(output, "- %-30s  %10" PRIu64 "\n", 
          STAT_COUNTER_DEFS.at(i).name,
          GLOBAL_STATS.counters.at(i));
    }

    std::fprintf(output, "## Integer distributions\n");
    for(uint32_t i = 0; i < _DISTRIB_INT_END; ++i) {
      const auto& distrib = GLOBAL_STATS.distrib_ints.at(i);
      std::fprintf(output, "- %-30s  ", STAT_DISTRIB_INT_DEFS.at(i).name);
      if(distrib.count == 0) {
        std::fprintf(output, "(no samples)\n");
        continue;
      }

      float average = float(distrib.sum) / float(distrib.count);
      float average_square = float(distrib.sum_squares) / float(distrib.count);
      float variance = abs(average_square - average * average);
      float stddev = sqrt(variance);
      std::fprintf(output, "avg %g, sd %g, min %" PRIi64 ", max %" PRIi64
          ", n %" PRIu64 "\n", average, stddev, distrib.min, distrib.max,
          distrib.count);
    }

    std::fprintf(output, "## Time distributions\n");
    for(uint32_t i = 0; i < _TIMER_END; ++i) {
      const auto& distrib = GLOBAL_STATS.distrib_times.at(i);
      std::fprintf(output, "- %-30s  ", STAT_DISTRIB_TIME_DEFS.at(i).name);
      if(distrib.sampled_count == 0) {
        std::fprintf(output, "(no samples)\n");
        continue;
      }

      float average_ns = float(distrib.sum_ns) 
        / float(distrib.sampled_count);
      float average_square_ns = float(distrib.sum_squares_ns) 
        / float(distrib.sampled_count);
      float average_overhead_ns = float(distrib.sum_overhead_ns) 
        / float(distrib.sampled_count);
      float estimate_total_ns = average_ns * float(distrib.total_count);
      float variance = abs(average_square_ns - average_ns * average_ns);
      float stddev_ns = sqrt(variance);
      std::fprintf(output, "avg %g ns, sd %g ns, n %" PRIu64 "/%" PRIu64 ",",
          average_ns, stddev_ns, distrib.sampled_count, distrib.total_count);

      if(abs(estimate_total_ns) < 20e3f) {
        std::fprintf(output, " total ~%3g ns", estimate_total_ns);
      } else if(abs(estimate_total_ns) < 20e6f) {
        std::fprintf(output, " total ~%3g us", estimate_total_ns * 1e-3f);
      } else if(abs(estimate_total_ns) < 20e9f) {
        std::fprintf(output, " total ~%3g ms", estimate_total_ns * 1e-6f);
      } else if(abs(estimate_total_ns) < 2000e12f) {
        std::fprintf(output, " total ~%3g s", estimate_total_ns * 1e-9f);
      } else {
        std::fprintf(output, " total ~%3g min", estimate_total_ns * 1e-9f / 60.f);
      }

      std::fprintf(output, "\n                                  ");
      std::fprintf(output, "min %" PRIi64 " ns, max %" PRIi64 " ns, avg ohead %g ns\n",
          distrib.min_ns, distrib.max_ns, average_overhead_ns);
    }
  }
int main (int argc, char **argv) {
	using std::string;
	using std::cout;
	using std::cerr;
	using std::endl;

	using normal_dist = std::normal_distribution<double>;
	using uniform_int_dist = std::uniform_int_distribution<int>;

	if (3 != argc ) {
		cerr << "usage <zeroMQurl> <topic>" << endl;
		return 1;
	}

	const std::chrono::milliseconds update_delay(400);
	const std::vector<StockData> stocks = {
			{1,   50.0,  0.30},
			{2,   70.0,  0.35},
			{3,    4.5,  0.60},
			{4,  102.2,  0.40} };

	std::default_random_engine choose_stock_generator;
	uniform_int_dist choose_stock_distribution(0, stocks.size() - 1);

	std::default_random_engine stock_price_generator;

	const string url(argv[1]);
	const string topic(argv[2]);

	cout << "zmq url:" << url << endl;
	cout << "topic:" << topic << endl;

    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_PUB);
    socket.bind(url.c_str());

    while (true) {

    	const StockData& stock =
    			stocks.at(choose_stock_distribution(choose_stock_generator));
    	normal_dist price_distribution(stock.mean, stock.std_deviation);

        std::stringstream id_and_price;
    	id_and_price << stock.id << "," <<
    			price_distribution(stock_price_generator);

        zmq::message_t topic_msg(topic.size());
        memcpy(topic_msg.data(), topic.data(), topic.size());
        const bool topic_send_rv = socket.send(topic_msg, ZMQ_SNDMORE);


        const auto& id_and_price_str = id_and_price.str();
        zmq::message_t id_and_price_msg(id_and_price_str.size());

        memcpy(id_and_price_msg.data(), id_and_price_str.data(),
        	   id_and_price_str.size());
        const bool price_send_rv = socket.send(id_and_price_msg);

        cout << "sent: " << id_and_price_str << endl;
        cout << "send statuses: " << topic_send_rv <<  " " << price_send_rv << endl;

    	std::this_thread::sleep_for(update_delay);
    }

    return 0;
}
Example #17
0
// Callback to found resources
void onFoundCandidateResource(std::vector< std::shared_ptr< OCResource > > resources)
{
    std::string resourceURI;
    std::string hostAddress;

    try
    {
        // Do some operations with resource object.
        for (unsigned int i = 0; i < resources.size(); ++i)
        {
            std::shared_ptr< OCResource > resource = resources.at(i);

            if (resource)
            {
                // Check if the resource is new one. If so, store it.

                std::map< std::string, std::shared_ptr< OCResource > >::iterator iter =
                        resourceTable.find(resource->host() + resource->uri());

                if (iter == resourceTable.end()) // new one
                {
                    resourceTable[resource->host() + resource->uri()] = resource;

                    OCResourceHandle foundResourceHandle;
                    OCStackResult result = OCPlatform::registerResource(foundResourceHandle,
                            resource);
                    std::cout << "\tResource ( " << resource->host() << " ) is registed!\t"
                            << std::endl;
                    if (result == OC_STACK_OK)
                    {
                        if (resource->uri() == "/oic/con")
                        {
                            OCPlatform::bindResource(configurationCollectionHandle,
                                    foundResourceHandle);
                            if (g_configurationResource == NULL)
                                g_configurationResource = resource;
                        }
                        else if (resource->uri() == "/oic/diag")
                        {
                            OCPlatform::bindResource(diagnosticsCollectionHandle,
                                    foundResourceHandle);
                            if (g_diagnosticsResource == NULL)
                                g_diagnosticsResource = resource;
                        }
                        else if (resource->uri() == "/factorySet")
                        {
                            OCPlatform::bindResource(setCollectionHandle, foundResourceHandle);
                            if (g_setResource == NULL)
                                g_setResource = resource;
                        }

                        resourceHandleVector.push_back(foundResourceHandle);
                    }
                    else
                    {
                        cout << "\tresource Error!" << endl;
                    }

                }

            }
            else
            {
                // Resource is invalid
                std::cout << "Resource is invalid" << std::endl;
            }
        }

    }
    catch (std::exception& e)
    {
        std::cout << "Exception: " << e.what() << std::endl;
    }

    pthread_mutex_lock(&mutex_lock);
    isWaiting = 0;
    pthread_mutex_unlock(&mutex_lock);
}
Example #18
0
    ShaderTechnique::ShaderTechnique(Shader::ShaderManager& shaderManager, bool forcePerPixelLighting, bool clampLighting, const std::vector<TextureLayer>& layers,
                                                   const std::vector<osg::ref_ptr<osg::Texture2D> >& blendmaps, int blendmapScale, float layerTileSize)
    {
        bool firstLayer = true;
        int i=0;
        for (std::vector<TextureLayer>::const_iterator it = layers.begin(); it != layers.end(); ++it)
        {
            osg::ref_ptr<osg::StateSet> stateset (new osg::StateSet);

            if (!firstLayer)
            {
                stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
                stateset->setAttributeAndModes(getEqualDepth(), osg::StateAttribute::ON);
            }

            int texunit = 0;

            stateset->setTextureAttributeAndModes(texunit, it->mDiffuseMap);

            stateset->setTextureAttributeAndModes(texunit, getLayerTexMat(layerTileSize), osg::StateAttribute::ON);

            stateset->addUniform(new osg::Uniform("diffuseMap", texunit));

            if(!firstLayer)
            {
                ++texunit;
                osg::ref_ptr<osg::Texture2D> blendmap = blendmaps.at(i++);

                stateset->setTextureAttributeAndModes(texunit, blendmap.get());

                stateset->setTextureAttributeAndModes(texunit, getBlendmapTexMat(blendmapScale));
                stateset->addUniform(new osg::Uniform("blendMap", texunit));
            }

            if (it->mNormalMap)
            {
                ++texunit;
                stateset->setTextureAttributeAndModes(texunit, it->mNormalMap);
                stateset->addUniform(new osg::Uniform("normalMap", texunit));
            }

            Shader::ShaderManager::DefineMap defineMap;
            defineMap["forcePPL"] = forcePerPixelLighting ? "1" : "0";
            defineMap["clamp"] = clampLighting ? "1" : "0";
            defineMap["normalMap"] = (it->mNormalMap) ? "1" : "0";
            defineMap["blendMap"] = !firstLayer ? "1" : "0";
            defineMap["colorMode"] = "2";
            defineMap["specularMap"] = it->mSpecular ? "1" : "0";
            defineMap["parallax"] = (it->mNormalMap && it->mParallax) ? "1" : "0";

            osg::ref_ptr<osg::Shader> vertexShader = shaderManager.getShader("terrain_vertex.glsl", defineMap, osg::Shader::VERTEX);
            osg::ref_ptr<osg::Shader> fragmentShader = shaderManager.getShader("terrain_fragment.glsl", defineMap, osg::Shader::FRAGMENT);
            if (!vertexShader || !fragmentShader)
                throw std::runtime_error("Unable to create shader");

            stateset->setAttributeAndModes(shaderManager.getProgram(vertexShader, fragmentShader));

            firstLayer = false;

            addPass(stateset);
        }
    }
Example #19
0
int
MaxEntropy::SolverHook(std::vector<int>& vecSupport, Eigen::MatrixXd& matSigma)
{
  Eigen::IOFormat CleanFmt(2, 0, " ", "\n", "", ";");
  Index numVariables = m_numNodes;
  Index numConstraints = 2 * m_numMaxHeads;
  Index numNz_jac_g = 2 * m_numMaxHeads * m_numNodes;
  Index numNz_h_lag = 0;
  
  SmartPtr<TMINLP> tminlp = 
    new MyIP( 
        numVariables, 
        numConstraints, 
        numNz_jac_g, 
        numNz_h_lag, 
        matSigma,
        (m_A+m_B-m_C), 
        m_ptrCS, 
        m_ptrMap,
        m_epsilon
        );
  MyIP* rawPtr = dynamic_cast<MyIP*>(GetRawPtr(tminlp));
  std::vector<int> tmp(m_ptrMap->GetNumNodes(), 0);
  rawPtr->SetExtraConstraints(tmp);
  //rawPtr->SetExtraConstraints(m_vecSched);

  FILE * fp = fopen("log.out","w");
  CoinMessageHandler handler(fp);
  BonminSetup bonmin(&handler);
  bonmin.initializeOptionsAndJournalist();
  // Here we can change the default value of some Bonmin or Ipopt option
  bonmin.options()->SetNumericValue("bonmin.time_limit", 1000); //changes bonmin's time limit
  bonmin.options()->SetStringValue("mu_oracle","loqo");
  //Here we read several option files
  bonmin.readOptionsFile("Mybonmin.opt");
  bonmin.readOptionsFile();// This reads the default file "bonmin.opt"
  // Options can also be set by using a string with a format similar to the bonmin.opt file
  bonmin.readOptionsString("bonmin.algorithm B-BB\n");

  //Now initialize from tminlp
  bonmin.initialize(GetRawPtr(tminlp));
  //Set up done, now let's branch and bound
  try {
    Bab bb;
    bb(bonmin);//process parameter file using Ipopt and do branch and bound using Cbc
  }
  catch(TNLPSolver::UnsolvedError *E) {
    //There has been a failure to solve a problem with Ipopt.
    std::cerr<<"Ipopt has failed to solve a problem"<<std::endl;
  }
  catch(OsiTMINLPInterface::SimpleError &E) {
    std::cerr << E.className() << "::" << E.methodName()
	      << std::endl
	      << E.message() << std::endl;
  }
  catch(CoinError &E) {
    std::cerr << E.className() << "::" << E.methodName()
	      << std::endl
	      << E.message() << std::endl;
  }

  vecSupport.assign(rawPtr->GetVecSolution().begin(), rawPtr->GetVecSolution().end());
  for (int i = 0; i < m_vecSched.size(); ++i) {
    m_vecSched.at(i) = m_vecSched.at(i) + vecSupport.at(i);
  }

  int activeNodes = 0;
  for (int i = 0; i < m_numNodes; i++) {
    if (vecSupport[i] == 1) ++activeNodes;
  }
  return activeNodes;
}
Example #20
0
 void operator() (tbb::flow::continue_msg) const {
     ++nExceptions;
     m_vec->at(m_vec->size()); // Will throw out_of_range exception
     ASSERT(false, "Exception not thrown by invalid access");
 }
Example #21
0
bool sendPush(std::vector<Value> registrationIds, std::vector<Value> changeList, Value className)
{
	std::string jsonString = getJson(changeList, registrationIds, className);
	CURL *curl;
	CURLcode res;
	std::string buffer;
	struct curl_slist *chunk = NULL;
	chunk = curl_slist_append(chunk, GCM_AUTH_KEY_HEADER);
	chunk = curl_slist_append(chunk, "Content-Type: application/json");
	curl = curl_easy_init(); // share accross 1 thread
	curl_easy_setopt(curl, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
	curl_easy_setopt(curl, CURLOPT_POST, true);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
	//curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonString.c_str());
	res = curl_easy_perform(curl);
	if (res == CURLE_OK)
	{
		std::cout << "Push packet sent" << std::endl;
		std::cout << "Result: " << buffer << std::endl;
		mValue val;
		auto succes = read(buffer, val);
		if (succes){
			try{
				auto obj = val.get_obj().find("results")->second.get_array();
				int n = 0;
				for (auto object : obj){
					mObject field = object.get_obj();
					try{
						std::string errorMessage = field["error"].get_str();
						if (errorMessage == "MissingRegistration" || errorMessage == "InvalidRegistration" || errorMessage == "NotRegistered"){
							std::cout << "GCM ERROR: " << errorMessage << " on registration id: " << registrationIds.at(n).get_str() << std::endl;
						}
						else{
							std::cout << "Recoverable GCM ERROR: " << errorMessage << " on registration id: " << registrationIds.at(n).get_str() << std::endl;
							// TODO: Retry send attempt on all recoverable failed clients
						}
					}
					catch (...){ // if item does not exist it will throw an exception  TODO: Lookup the json_spirit exceptions
						// message_id item can be extracted from the object here, but we do not need it, everything has been sent succesfully
					}
					n++;
				}
			}
			catch (...){ // TODO: Lookup the json_spirit exceptions
				std::cout << "Exception thrown when parsing GCM json response" << std::endl;
			}
		}
		else{
			std::cout << "Failed reading json response" << std::endl;
		}
	}
	else
	{
		fprintf(stderr,
			"curl_easy_perform() failed: %s\n",
			curl_easy_strerror(res));
	}
	curl_easy_cleanup(curl);
	curl_slist_free_all(chunk);
	return (res == CURLE_OK);
}
Example #22
0
 std::string Dot::print(const std::vector<std::string>& arg) const {
   return "dot(" + arg.at(0) + ", " + arg.at(1) + ")";
 }
Example #23
0
void Model::SetColors(const std::vector<Color> &colors)
{
	assert(colors.size() == 3); //primary, seconday, trim
	m_colorMap.Generate(GetRenderer(), colors.at(0), colors.at(1), colors.at(2));
}
Example #24
0
double LLFunc(const double *xx ){
 const Double_t scale = xx[0];

 ///==== Likelihood ==== 
 fileInMC->cd();
 TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str());
 TString NameMCGr = Form("grMC_%.5f",scale);
 TString NameMC = Form("hMC_%.5f",scale);
 TH1F* hMC;
// TGraphErrors* tempGrLL;
 if (!gROOT->FindObject(NameMC.Data())){
  hMC = new TH1F(NameMC,NameMC,NBINTemplate,MinTemplate,MaxTemplate);
  hMC->Reset();
  
  MyTreeMC->SetEntryList(0); 
  MyTreeMC->Draw(">> myListMCTot",(AdditionalCut + Form(" && (ET * (1+(%f)))>%f",scale,minET)).Data(),"entrylist");
  TEntryList *mylistMCTot = (TEntryList*)gDirectory->Get("myListMCTot");
  MyTreeMC->SetEntryList(mylistMCTot);
  
  TString DrawMC = Form("(%s * (1+(%f)))>>%s",variableName.c_str(),scale,NameMC.Data());
  std::cerr << " DrawMC = " << DrawMC.Data() << std::endl;
//   std::cerr << " LL CUT = " << (AdditionalCut+Form("&& (ET * (1+(%f)))>%f",scale,minET)).Data() << std::endl;
// MyTreeMC->Draw(DrawMC,(AdditionalCut+Form("&& (ET * (1+(%f)))>%f",scale,minET)).Data());
  MyTreeMC->Draw(DrawMC);
  hMC->Scale(10./numEvents);
  outFile->cd();
  hMC->Write();
//  tempGrLL = new TGraphErrors(buildGEfromH (*hMC));
//  tempGrLL->SetName(NameMCGr);
//  tempGrLL->Write();
 }
 else {
  std::cerr << " LL old " << NameMC.Data() << std::endl;
  hMC = (TH1F*) outFile->Get(NameMC.Data());
//  tempGrLL = (TGraphErrors*) outFile->Get(NameMCGr.Data());
 }
 numberDATA = vET_data.size();
 double result = 1.;
 
 std::cerr << " numberDATA = " << numberDATA << " hMC->GetEntries() = " << hMC->GetEntries() << std::endl;
 for (int iEvt = 0; iEvt < numberDATA; iEvt ++){
  double ET = vET_data.at(iEvt);
  int bin = ( ET - MinTemplate ) / Delta;
  if (bin > 0 && bin <= NBINTemplate){
  std::cerr << " ok here " << std::endl;
//   result *= (tempGrLL->Eval(hMC->GetBinCenter(bin)));
//    std::cerr << " hMC->GetBinContent(" << bin << ") = " << hMC->GetBinContent(bin) << " result = " << result << std::endl;
   if (hMC->GetBinContent(bin) != 0) {
    result -= log(hMC->GetBinContent(bin));
   }
   else {
    result = numberDATA * numEvents;
    std::cerr << " >>>>>>>>>>>>>>>> it's ZERO !!!! " << std::endl; //====== > too verbose!
    return result;
   }
//    if (hMC->GetBinContent(bin) == 0) {
//     std::cerr << " result = " << result << " hMC.GetBinContent(" << bin << ":" << NBINTemplate << ") = " << hMC.GetBinContent(bin) << " scale = " << scale << std::endl;
//    }
  }
 }
//  outFile->cd();
//  hMC.Write();
 
//  if (result != 0) result = -log(result);
//  else {
//   result = numberDATA * numEvents;
//   std::cerr << " it's ZERO !!!! " << std::endl;
//  }
 
 ///==== end Likelihood ====    

 return result;
}
bool is_extra_enabled(std::vector<int> extras)
{
	Vehicle veh = PED::GET_VEHICLE_PED_IS_USING(PLAYER::PLAYER_PED_ID());
	int extraIndex = extras.at(0);
	return VEHICLE::IS_VEHICLE_EXTRA_TURNED_ON(veh, extraIndex) ? true : false;
}
Example #26
0
/**
 * Main function
 */
int main(int argc, char** argv){
    ros::init(argc, argv, "simple_navigation_goals"); // init and set name

    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("goals",10,PathCallback);


    MoveBaseClient ac("move_base", true); // action client to spin a thread by default




    ros::Rate loop_rate(50);


    while(ros::ok())
    {
        // If the waypoint buffer does not contain waypoints wait until waypoints arrive.
        if(waypoints.size() != 0)
        {
            
            // Execute the buffered waypoints using the Action API provided Move Base


            for(int i = 0; i < waypoints.size(); ++i)
            {
                //std::cout << "Waypoint"<< i << "[" <<waypoints[i].position.x << ", " << waypoints[i].position.y << "]" << std::endl;

            }
                while (!ac.waitForServer(ros::Duration(5.0))) { // wait for the action server to come up
                ROS_INFO("Waiting for the move_base action server to come up");
            }

            move_base_msgs::MoveBaseGoal goal;
            goal.target_pose.header.frame_id = "map"; // set target pose frame of coordinates

            for(int i = 0; i < waypoints.size(); ++i) { // loop over all goal points, point by point
                goal.target_pose.header.stamp = ros::Time::now(); // set current time
                goal.target_pose.pose = waypoints.at(i);
                ROS_INFO("Sending goal");
                ac.sendGoal(goal, &doneCb, &activeCb, &feedbackCb); // send goal and register callback handler
                ac.waitForResult(); // wait for goal result

                if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) {
                    ROS_INFO("The base moved to %d goal", i);
                } else {
                    ROS_INFO("The base failed to move to %d goal for some reason", i);
                }
            }
        }



        ros::spinOnce();
        //loop_rate.sleep();

    }


    return 0;
}
Example #27
0
int convertStringToTokens(string sInput, stTokens &tokenList, long double previousAnswer = 0) {

    sInput = stripSpaces(sInput);

    bool blNumberString = false;
    bool blFoundDecimal = false;
    string stNumber;

    unsigned int i = 0;
    while(i < sInput.length()) {

        if(isdigit(sInput.at(i))) { //We've found a number, keep adding the current char to a string til we find a non-digit

            if(blNumberString) {
                stNumber += sInput.at(i);
            } else {
                stNumber = sInput.at(i);
                blNumberString = true;
            }

        }
        else if(sInput.at(i) == '.') { //Account for decimal places in numbers
            if(blNumberString) {
                if(blFoundDecimal) {
                    return ERROR_SECOND_DECIMAL;
                } else {
                    blFoundDecimal = true;
                    stNumber += sInput.at(i);
                }
            } else {
                return ERROR_UNEXPECTED_DECIMAL;
            }
        }
        else {
            //We've found a letter, it could be part of a function. Find the whole word, and then see if it's an allowed word.
            addDoubleFromString(tokenList, blNumberString,blFoundDecimal,stNumber);

            string stWordBuffer;
            while( (i < sInput.length()) ) {
                if( operatorMap.find(sInput.at(i)) != operatorMap.end() ) {
                    if(stWordBuffer.empty() == true){ //If we find a single operator, then it's definitely not part of a function or variable
                        stWordBuffer = sInput.at(i); //So set the wordBuffer to that operator, then perform the standard checks
                        ++i;
                    }
                    break;
                }

                if( !isdigit(sInput.at(i)) ) { //Otherwise, if it's still not a number, continue adding characters to the buffer
                    stWordBuffer += tolower(sInput.at(i));
                    ++i;
                } else {
                    break;
                }

            }
            //cout << stWordBuffer << endl;

            if(stWordBuffer == "ans") { //Special override keywords first
                tokenList.addData(TOKEN_DOUBLE, previousAnswer);
            }
            else if(operatorMap.find(stWordBuffer.at(0)) != operatorMap.end()) { //Check if it's an operator
                tokenList.addData(operatorMap[stWordBuffer.at(0)]); //Use the first character of the string
            }
            else if(tokenMap.find(stWordBuffer) != tokenMap.end()) { //Now see if it's a predefined function
                tokenList.addData(tokenMap[stWordBuffer]);
            }
            else if(constMap.find(stWordBuffer) != constMap.end()) { //Or a constant value
                tokenList.addData(TOKEN_DOUBLE,constMap[stWordBuffer]);
            }
            else if(variableMap.find(stWordBuffer) != variableMap.end()) { //And then check if it's a variable
                unsigned int i = 0;//distance(variableMap.begin(), variableMap.find(stWordBuffer));
                for(; i != vecVariablesNames.size(); ++i) {
                    if(vecVariablesNames.at(i) == stWordBuffer) {
                        break;
                    }
                }
                tokenList.addData(TOKEN_VARIABLE_ESTABLISHED,i);
            }
            else {
                tokenList.addData(TOKEN_VARIABLE_NEW,vecVariablesNames.size());
                vecVariablesNames.push_back(stWordBuffer);
                variableMap[stWordBuffer] = 0;
            }

            continue;
        }

        ++i;
    }
    if(blNumberString) {
        addDoubleFromString(tokenList, blNumberString,blFoundDecimal,stNumber);
    }

    //Remove spaces
    unsigned int count = 0, deleted = 0;
    while(count - deleted < tokenList.types.size()) {
        if(tokenList.types.at(count-deleted) == TOKEN_SPACE) {
            //cout << "DELETING SPACE\n";
            tokenList.removePos(count-deleted);
            ++deleted;
        }
        ++count;
    }

    //Perform various checks to ensure we don't have faulty token data that could mess up our calculation later

    //Check for mismatched brackets
    int lBrackets = 0, rBrackets = 0;
    for (unsigned int i = 0; i != tokenList.types.size(); ++i) {
        if(tokenList.types.at(i) == TOKEN_LEFTBRACKET) ++lBrackets;
        if(tokenList.types.at(i) == TOKEN_RIGHTBRACKET) ++rBrackets;
    }
    if(lBrackets != rBrackets) {
        return ERROR_MISMATCHED_BRACKETS;
    }

#ifdef ALLOW_FOR_IMPLIED_MULTIPLICATION
    //Insert * between brackets and numbers (or brackets)
    for (unsigned int i = 1; i < tokenList.types.size(); ++i) {
        if( (tokenList.types.at(i-1) == TOKEN_DOUBLE) && (tokenList.types.at(i) == TOKEN_LEFTBRACKET) ) tokenList.insertData(i,TOKEN_MULTIPLY);
        if( (tokenList.types.at(i-1) == TOKEN_RIGHTBRACKET) && (tokenList.types.at(i) == TOKEN_DOUBLE) ) tokenList.insertData(i,TOKEN_MULTIPLY);
        if( (tokenList.types.at(i-1) == TOKEN_RIGHTBRACKET) && (tokenList.types.at(i) == TOKEN_LEFTBRACKET) ) tokenList.insertData(i,TOKEN_MULTIPLY);
    }
#else
    //Throw an error
    for (unsigned int i = 1; i < tokenList.types.size(); ++i) {
        if( (tokenList.types.at(i-1) == TOKEN_DOUBLE) && (tokenList.types.at(i) == TOKEN_LEFTBRACKET) ) { cout << "Implied multiplication of brackets is disallowed.\n"; return ERROR_IMPLIED_MULTIPLICATION; }
        if( (tokenList.types.at(i-1) == TOKEN_RIGHTBRACKET) && (tokenList.types.at(i) == TOKEN_DOUBLE) ) { cout << "Implied multiplication of brackets is disallowed.\n"; return ERROR_IMPLIED_MULTIPLICATION; }
        if( (tokenList.types.at(i-1) == TOKEN_RIGHTBRACKET) && (tokenList.types.at(i) == TOKEN_LEFTBRACKET) ) { cout << "Implied multiplication of brackets is disallowed.\n"; return ERROR_IMPLIED_MULTIPLICATION; }
    }
#endif

    //tokenList.dumpData();
    //cout << "Converted string '" << sInput << "' to tokens successfully.\n";
    return NO_ERROR;
}
Example #28
0
int generateLevels(std::vector< std::vector<sbfSElement *> >  & selements, std::vector<int> & numTargetByLayers, std::vector<double> &maxImbalance, bool verbouse){

	sbfMesh * mesh = selements[0][0]->mesh();
	if(!mesh) return 1;
	int numRegElems = selements[0].size();
    std::vector <double> facesWeigth;
	std::vector <int> facesOwners;
	std::vector <double> randoms;
	randoms.resize(50);
	for(size_t ct = 0; ct < randoms.size(); ct++) randoms[ct] = ((double)rand())/RAND_MAX;

	facesWeigth.reserve(numRegElems*50);
	facesOwners.reserve(numRegElems*50);

	for(int elemID = 0; elemID < numRegElems; elemID++){//Loop on elements
        sbfElement *elem = mesh->elemPtr(elemID);

		double faceWeigth;
		int facesOwner = elemID;
		std::list<int> inds;
		int count;

		std::vector< std::vector<int> > facesNodesIndexes = elem->facesNodesIndexes();
        for(auto itFace = facesNodesIndexes.begin(); itFace != facesNodesIndexes.end(); itFace++){//Loop on faces
			inds.clear();
            for(auto itIndex = (*itFace).begin(); itIndex != (*itFace).end(); itIndex++)
				inds.push_back(*itIndex);
			inds.sort();
            count = 0; faceWeigth = 0; for(auto it = inds.begin(); it != inds.end(); it++) {faceWeigth += *it*randoms[count++];}
			facesWeigth.push_back(faceWeigth);
			facesOwners.push_back(facesOwner);
		}//Loop on faces

	}//Loop on elements

	quickAssociatedSort<double, int>(&facesWeigth[0], &facesOwners[0], 0, facesWeigth.size()-1);

    if ( verbouse ) std::cout << "sort done" << std::endl;

	for(size_t ctLevel = 0; ctLevel < numTargetByLayers.size(); ctLevel++){//Loop on levels
		int numTargetSE = numTargetByLayers[ctLevel];
		int numSElems = selements[ctLevel].size();

		int vertnbr, edgenbr;
        vertnbr = numSElems;
        edgenbr = 0;

		std::vector< std::list <int> > elemNeibour;
        elemNeibour.resize(vertnbr);

		int founded = 0, unfounded = 0;

		std::vector <double> facesWeigthNextLevel;
		std::vector <int> facesOwnersNextLevel;
		facesWeigthNextLevel.reserve(facesWeigth.size());
		facesOwnersNextLevel.reserve(facesOwners.size());
        auto facesWeigthIt = facesWeigth.begin();
        auto facesOwnersIt = facesOwners.begin();
        auto facesWeigthEndM1 = facesWeigth.end() - 1;
		for(; facesWeigthIt < facesWeigthEndM1; facesWeigthIt++, facesOwnersIt++){
			if(*facesWeigthIt == *(facesWeigthIt+1)){
				//Check if *facesOwnersIt and *(facesOwnersIt+1) are in one SE
				int owner0, owner1;
				owner0 = *facesOwnersIt; owner1 = *(facesOwnersIt+1);
				int ownerSE0 = -1, ownerSE1 = -1;
				bool inSame = false;
				if(ctLevel == 0){ownerSE0 = owner0; ownerSE1 = owner1;}
                else{
					sbfSElement * se = selements[0][owner0];
                    for(size_t ct = 0; ct < ctLevel; ct++) se = se->parent();
					ownerSE0 = se->index();
					se = selements[0][owner1];
                    for(size_t ct = 0; ct < ctLevel; ct++) se = se->parent();
					ownerSE1 = se->index();
                    if(ownerSE0 == ownerSE1) inSame = true;
				}
				if (inSame){ facesWeigthIt++; facesOwnersIt++; continue; }
				elemNeibour[ownerSE1].push_back(ownerSE0);
				elemNeibour[ownerSE0].push_back(ownerSE1);
				facesWeigthNextLevel.push_back(*facesWeigthIt);
				facesWeigthNextLevel.push_back(*facesWeigthIt);
				facesOwnersNextLevel.push_back(*facesOwnersIt);
				facesOwnersNextLevel.push_back(*(facesOwnersIt+1));
				facesWeigthIt++; facesOwnersIt++;
				founded++;
			}
            else unfounded++;
		}

        std::vector<idx_t> verttab, edgetab, edlotab, parttab;
		verttab.resize(vertnbr+1);
        parttab.resize(vertnbr);
		int count = 0;
		verttab[0] = count;
		for(size_t ct = 0; ct < elemNeibour.size(); ct++){
            std::list<int> elemNeibourAll, elemNeibourUnique;
            for(auto it = elemNeibour[ct].begin(); it != elemNeibour[ct].end(); it++)
				elemNeibourAll.push_back(*it);
			elemNeibourAll.sort();
			elemNeibourUnique = elemNeibourAll;
			elemNeibourUnique.unique();
            auto elemNeibourUniqueBegin = elemNeibourUnique.begin();
            auto elemNeibourUniqueEnd = elemNeibourUnique.end();
            auto elemNeibourAllBegin = elemNeibourAll.begin();
            auto elemNeibourAllEnd = elemNeibourAll.end();
            auto itA = elemNeibourAllBegin;
            for(auto itU = elemNeibourUniqueBegin; itU != elemNeibourUniqueEnd; itU++)
			{
                if(static_cast<int>(ct) != *itU){
                    int numAcuarence = 0;
                    while(*itA == *itU && itA != elemNeibourAllEnd){
                        numAcuarence++;
                        itA++;
                    }
                    edgetab.push_back(*itU);
                    edlotab.push_back(numAcuarence);
                    count++;
                    edgenbr++;
                }
			}
			verttab[ct+1] = count;
		}

        idx_t nvtxs = vertnbr, ncon = 1, nparts = numTargetSE, objval;
        idx_t options[METIS_NOPTIONS];
        METIS_SetDefaultOptions(options);
        options[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_VOL;
        options[METIS_OPTION_NUMBERING] = 0;
        options[METIS_OPTION_NITER] = 600;
        double maxLayerImbalance = maxImbalance.back();
        if( ctLevel < maxImbalance.size() ) maxLayerImbalance = maxImbalance.at(ctLevel);
        options[METIS_OPTION_UFACTOR] = static_cast<int>((maxLayerImbalance-1)*1000);
        options[METIS_OPTION_CONTIG] = 1; //Force contiguous partitions
//        options[METIS_OPTION_DBGLVL] = 1;
        int rez = METIS_PartGraphKway(&nvtxs,
                                      &ncon,
                                      verttab.data(),
                                      edgetab.data(),
                                      /*idx_t *vwgt*/nullptr,
                                      /*idx_t *vsize*/nullptr,
                                      /*idx_t *adjwgt*/nullptr,
                                      &nparts,
                                      /*real_t *tpwgts*/nullptr,
                                      /*real_t *ubvec*/nullptr,
                                      options,
                                      &objval,
                                      parttab.data()
                                      );
        if ( rez != METIS_OK ) throw std::runtime_error("Metis runtime failed :(");

		for(int ct = 0; ct < numSElems; ct++){
			selements[ctLevel][ct]->setParent(selements[ctLevel+1][parttab[ct]]);
            selements[ctLevel+1][parttab[ct]]->addChildren(selements[ctLevel][ct]);
		}

        //Metis solves following problem, but still it should be checked
		//There are SElements with some disconnected clusters of elements.
		//For such SE split them to several SEs

        for(auto seIT = selements[ctLevel+1].begin(); seIT != selements[ctLevel+1].end(); seIT++){//Loop on SElements including new ones
			std::set<int> allElemIndexes;//Indexes of all elements in this SE
			for(int ct = 0; ct < (*seIT)->numSElements(); ct++) allElemIndexes.insert((*seIT)->children(ct)->index());
			std::set<int> inOneSE;
			inOneSE.insert(*(allElemIndexes.begin()));
			bool flagChanges = true;
			while(flagChanges){
				flagChanges = false;
                for(auto it = inOneSE.begin(); it != inOneSE.end(); it++){
                    for(auto itN = elemNeibour[*it].begin(); itN != elemNeibour[*it].end(); itN++){
						if(allElemIndexes.count(*itN) && !inOneSE.count(*itN)){
							inOneSE.insert(*itN);
							flagChanges = true;
						}
					}
				}
			}
			if(allElemIndexes.size() != inOneSE.size()){
				std::set<int> inOtherSE;
				(*seIT)->setChildrens(std::vector<sbfSElement *>{});
				(*seIT)->numSElements();
                for(auto it = inOneSE.begin(); it != inOneSE.end(); it++){
					(*seIT)->addChildren(selements[ctLevel][*it]);
					selements[ctLevel][*it]->setParent(*seIT);
				}
                for(auto it = allElemIndexes.begin(); it != allElemIndexes.end(); it++){
					if(!inOneSE.count(*it))
						inOtherSE.insert(*it);
				}
                sbfSElement *additionalSE = new sbfSElement((*seIT)->mesh(), selements[ctLevel+1].size());
                for(auto it = inOtherSE.begin(); it != inOtherSE.end(); it++){
                    additionalSE->addChildren(selements[ctLevel][*it]);
                    selements[ctLevel][*it]->setParent(additionalSE);
				}
                selements[ctLevel+1].push_back(additionalSE);
                if ( verbouse ) std::cout << "Split disconnected SE to two of sizes: " << inOneSE.size() << ", " << inOtherSE.size() << std::endl;
			}
		}//Loop on SElements including new ones

		facesWeigth = facesWeigthNextLevel;
		facesOwners = facesOwnersNextLevel;

        std::cout << "level " << ctLevel << " done" << std::endl;

        //get statistics
        std::list<int> selems;
        int numAll = 0;
        for(auto se : selements[ctLevel+1]){
            selems.push_back(se->numSElements());
            numAll += se->numSElements();
        }
        if(numAll != numSElems)
            throw std::runtime_error("SElements contain not all elements of previous layer");
        selems.sort();
        selems.reverse();
        if ( verbouse ) { for (auto se : selems ) std::cout << se << "\t"; std::cout << "Imbalance is " << (1.0*selems.front())/selems.back() << std::endl; }
	}//Loop on levels

	return 0;
}
Example #29
0
int evaluateTokens_rc(stTokens &tokens, long double &result) {

    //tokens.dumpData();

    if(tokens.values.size() == 0) { result = 0; return EMPTY_BRACKETS; }

    //First let's see whether we're going to be performing a maths equation or a programming construct - like assigning a variable
    if( tokens.types.front() == TOKEN_LET) {
        //Assigning a variable, tokens should be in the form <assignment> ::= <variable> <equals> <number>|<variable>
        if (tokens.types.size() == 4) {

            if( ( (tokens.types.at(1) == TOKEN_VARIABLE_NEW) || (tokens.types.at(1) == TOKEN_VARIABLE_ESTABLISHED) ) && (tokens.types.at(2) == TOKEN_BECOMES) ) {

                if(tokens.types.at(3) == TOKEN_DOUBLE) {
                    *getVariable(tokens.values.at(1)) = tokens.values.at(3);
                    return NO_ERROR_VAR_ASSIGNMENT;
                }
                else if(tokens.types.at(3) == TOKEN_VARIABLE_ESTABLISHED) {
                    *getVariable(tokens.values.at(1)) = *getVariable(tokens.values.at(3));
                    return NO_ERROR_VAR_ASSIGNMENT;
                }
                else {
                    return ERROR_BAD_ASSIGNMENT;
                }

            } else {
                return ERROR_BAD_LET_USAGE;
            }
        }
        else {
            return ERROR_BAD_LET_USAGE;
        }
    }
    else if( tokens.types.front() == TOKEN_IS) {
        //Comparing values, tokens should be in the form <comparison> ::= <number>|<variable> <equals> <number>|<variable>
        if (tokens.types.size() == 4) {
            if( tokens.types.at(1) == TOKEN_VARIABLE_ESTABLISHED ) { tokens.setData(1,TOKEN_DOUBLE,*getVariable(tokens.values.at(1))); }
            if( tokens.types.at(3) == TOKEN_VARIABLE_ESTABLISHED ) { tokens.setData(3,TOKEN_DOUBLE,*getVariable(tokens.values.at(1))); }

            if (!( (tokens.types.at(1) == TOKEN_DOUBLE) && (tokens.types.at(3) == TOKEN_DOUBLE) )) {
                return ERROR_BAD_IS_USAGE;
            }

            switch(tokens.types.at(2)) {
            case TOKEN_EQUIVALENT: if(tokens.values.at(1) == tokens.values.at(3)) { result = 1; } else { result = 0; } break;
            case TOKEN_GREATER: if(tokens.values.at(1) > tokens.values.at(3)) { result = 1; } else { result = 0; } break;
            case TOKEN_LESS: if(tokens.values.at(1) < tokens.values.at(3)) { result = 1; } else { result = 0; } break;
            case TOKEN_GREATER_EQ: if(tokens.values.at(1) >= tokens.values.at(3)) { result = 1; } else { result = 0; } break;
            case TOKEN_LESS_EQ: if(tokens.values.at(1) <= tokens.values.at(3)) { result = 1; } else { result = 0; } break;
            }

            return NO_ERROR_COMPARISON;
        }
        else {
            return ERROR_BAD_IS_USAGE;
        }
    }
    else {

        //Add a leading 0 to starting + or - tokens
        if( (tokens.types.front() == TOKEN_PLUS) || (tokens.types.front() == TOKEN_MINUS) ) {
            tokens.insertData(0,TOKEN_DOUBLE,0);
        }

        //Replace all variables with their values
        int unknownCount = 0;
        for (unsigned int i = 0; i < tokens.types.size(); ++i) {
            if(tokens.types.at(i) == TOKEN_VARIABLE_ESTABLISHED) {
                if(variableMap.find(vecVariablesNames.at(tokens.values.at(i))) != variableMap.end()) {
                    tokens.setData(i,TOKEN_DOUBLE,variableMap[vecVariablesNames.at(tokens.values.at(i))]);
                }
            }
            else if(tokens.types.at(i) == TOKEN_VARIABLE_NEW) {
                //Just clear out this variable's place in the variableNames and variableMap lists
                string tempName = vecVariablesNames.at(tokens.values.at(i-unknownCount));
                vecVariablesNames.erase(vecVariablesNames.begin()+ tokens.values.at(i-unknownCount));
                variableMap.erase(tempName);
                ++unknownCount;
            }
        }
        if(unknownCount != 0) return ERROR_UNKNOWN_VARIABLE;

        //Check we don't have any TOKEN_EQUALS without a starting TOKEN_LET
        if(tokens.types.front() != TOKEN_LET) {
            for (unsigned int i = 0; i != tokens.types.size(); ++i) {
                if(tokens.types.at(i) == TOKEN_EQUALS) return ERROR_EQUALS_WITHOUT_LET;
            }
        }

        if (! ((tokens.types.back() == TOKEN_DOUBLE) || (tokens.types.back() == TOKEN_RIGHTBRACKET) || (tokens.types.back() == TOKEN_FACTORIAL)) ) {
            result = 0;
            return ERROR_FAULTY_END;
        }
        if (! ((tokens.types.front() == TOKEN_DOUBLE) || (tokens.types.front() == TOKEN_LEFTBRACKET) || (tokens.types.front() == TOKEN_SIN) || (tokens.types.front() == TOKEN_COS)
               || (tokens.types.front() == TOKEN_TAN) || (tokens.types.front() == TOKEN_ABS)
               ) ) {
            result = 0;
            return ERROR_FAULTY_START;
        }

        //Check for brackets, and recursively evaluate anything inside them
        int leftBracketsFound = 0;
        int rightBracketsFound = 0;
        stTokens smallerEvaluation;
        int posLeftBracket = 0, posRightBracket = 0;
        for (unsigned int i = 0; i < tokens.types.size(); ++i) {

            if(leftBracketsFound > 0) {
                smallerEvaluation.types.push_back(tokens.types.at(i));
                smallerEvaluation.values.push_back(tokens.values.at(i));
            }

            if(tokens.types.at(i) == TOKEN_LEFTBRACKET) {
                ++leftBracketsFound;
                if(leftBracketsFound == 1)
                    posLeftBracket = i;
            }
            else if(tokens.types.at(i) == TOKEN_RIGHTBRACKET) {
                ++rightBracketsFound;
                if( (leftBracketsFound == rightBracketsFound) && (rightBracketsFound > 0) ) {
                    posRightBracket = i;
                    //Remove the brackets and contents
                    tokens.removePos(posLeftBracket, posRightBracket);
                    smallerEvaluation.removePos(smallerEvaluation.types.size()-1);
                    //Evaluate the brackets and insert that into the tokens
                    long double dblSmallerEvaluate;
                    int rsltSmallerEvaluate = evaluateTokens_rc(smallerEvaluation, dblSmallerEvaluate);
                    if(rsltSmallerEvaluate != NO_ERROR) {
                        //There was an error found, so return that error code.
                        return rsltSmallerEvaluate;
                    }

                    tokens.types.at(posLeftBracket) = TOKEN_DOUBLE;
                    tokens.values.at(posLeftBracket) = dblSmallerEvaluate;

                    i = 0;
                    smallerEvaluation.values.clear();
                    smallerEvaluation.types.clear();

                    leftBracketsFound = 0;
                    rightBracketsFound = 0;
                }
            }

        }

        //Now run functions, like sin, cos
        for (unsigned int i = 0; i < tokens.types.size(); ++i) {
            int changeMade = 0;
            switch(tokens.types.at(i)) {
            case TOKEN_SIN: tokens.setData(i,TOKEN_DOUBLE,sin(tokens.values.at(i+1))); changeMade = 1; break;
            case TOKEN_COS: tokens.setData(i,TOKEN_DOUBLE,cos(tokens.values.at(i+1))); changeMade = 1; break;
            case TOKEN_TAN: tokens.setData(i,TOKEN_DOUBLE,tan(tokens.values.at(i+1))); changeMade = 1; break;
            case TOKEN_ABS: tokens.setData(i,TOKEN_DOUBLE,abs(tokens.values.at(i+1))); changeMade = 1; break;
            case TOKEN_FACTORIAL:
                if( (static_cast<int>(tokens.values.at(i-1))) != tokens.values.at(i-1) ) {
                    return ERROR_FACTORIAL_NON_INTEGER;
                }
                tokens.setData(i,TOKEN_DOUBLE,factorial(static_cast<int>(tokens.values.at(i-1)))); changeMade = 2; break;
            }
            if(changeMade == 1) {
                if(tokens.types.at(i+1) != TOKEN_DOUBLE) {
                    return ERROR_INVALID_DATA_TO_FUNCTION;
                }
                tokens.removePos(i+1);
                --i;
            }
            else if(changeMade == 2) {
                if(tokens.types.at(i-1) != TOKEN_DOUBLE) {
                    return ERROR_INVALID_DATA_TO_FUNCTION;
                }
                tokens.removePos(i-1);
                --i;
            }
        }

        //Find carets for exponents evaluation
        for (int i = tokens.types.size() - 1; i >= 0; --i) {
            switch(tokens.types.at(i)) {
            case TOKEN_POWER:
                long double base = tokens.values.at(i-1);
                long double exp = tokens.values.at(i+1);
#ifndef ALLOW_ZERO_TO_POWER_ZERO
                if ((base == exp) && (base == 0)) {
                    return ERROR_ZERO_TO_POWER_ZERO;
                }
#endif
                tokens.setData(i,TOKEN_DOUBLE,pow(base,exp)); tokens.removePos(i-1); tokens.removePos(i); --i; break;
            }
        }

        //Find multiplications and divisions
        for (unsigned int i = 0; i < tokens.types.size(); ++i) {
            bool changeMade = false;
            switch(tokens.types.at(i)) {
            case TOKEN_MULTIPLY: tokens.setData(i,TOKEN_DOUBLE,tokens.values.at(i-1) * tokens.values.at(i+1)); changeMade = true; break;
            case TOKEN_DIVIDE_FLOAT: tokens.setData(i,TOKEN_DOUBLE,tokens.values.at(i-1) / tokens.values.at(i+1)); changeMade = true; break;
            case TOKEN_DIVIDE_INT: tokens.setData(i,TOKEN_DOUBLE,static_cast<int>(tokens.values.at(i-1)) / static_cast<int>(tokens.values.at(i+1))); changeMade = true; break;
            case TOKEN_MODULO:
                if( (static_cast<int>(tokens.values.at(i+1))) == 0) {
                    return ERROR_MOD_BY_ZERO;
                }
                tokens.setData(i,TOKEN_DOUBLE,static_cast<int>(tokens.values.at(i-1)) % static_cast<int>(tokens.values.at(i+1))); changeMade = true;
                break;
            }
            if(changeMade) {
                tokens.removePos(i-1);
                tokens.removePos(i);
                --i;
            }
        }

        //And finally addition and subtraction
        for (unsigned int i = 0; i < tokens.types.size(); ++i) {
            bool changeMade = false;
            switch(tokens.types.at(i)) {
            case TOKEN_PLUS: tokens.setData(i,TOKEN_DOUBLE,tokens.values.at(i-1) + tokens.values.at(i+1)); changeMade = true; break;
            case TOKEN_MINUS: tokens.setData(i,TOKEN_DOUBLE,tokens.values.at(i-1) - tokens.values.at(i+1)); changeMade = true; break;
            }
            if(changeMade) {
                tokens.removePos(i-1);
                tokens.removePos(i);
                --i;
            }
        }

        result = tokens.values.at(0);
        return NO_ERROR_MATH_FUNCTION;
    }

}
Example #30
0
void AccountHandler::handleCharacterCreateMessage(AccountClient &client,
                                                  MessageIn &msg)
{
    std::string name = msg.readString();
    int hairStyle = msg.readInt8();
    int hairColor = msg.readInt8();
    int gender = msg.readInt8();

    // Avoid creation of character from old clients.
    int slot = -1;
    if (msg.getUnreadLength() > 7)
        slot = msg.readInt8();

    MessageOut reply(APMSG_CHAR_CREATE_RESPONSE);

    Account *acc = client.getAccount();
    if (!acc)
    {
        reply.writeInt8(ERRMSG_NO_LOGIN);
    }
    else if (!stringFilter->filterContent(name))
    {
        reply.writeInt8(ERRMSG_INVALID_ARGUMENT);
    }
    else if (stringFilter->findDoubleQuotes(name))
    {
        reply.writeInt8(ERRMSG_INVALID_ARGUMENT);
    }
    else if (hairStyle > mNumHairStyles)
    {
        reply.writeInt8(CREATE_INVALID_HAIRSTYLE);
    }
    else if (hairColor > mNumHairColors)
    {
        reply.writeInt8(CREATE_INVALID_HAIRCOLOR);
    }
    else if (gender > mNumGenders)
    {
        reply.writeInt8(CREATE_INVALID_GENDER);
    }
    else if ((name.length() < mMinNameLength) ||
             (name.length() > mMaxNameLength))
    {
        reply.writeInt8(ERRMSG_INVALID_ARGUMENT);
    }
    else
    {
        if (storage->doesCharacterNameExist(name))
        {
            reply.writeInt8(CREATE_EXISTS_NAME);
            client.send(reply);
            return;
        }

        // An account shouldn't have more
        // than <account_maxCharacters> characters.
        Characters &chars = acc->getCharacters();
        if (slot < 1 || slot > mMaxCharacters
            || !acc->isSlotEmpty((unsigned int) slot))
        {
            reply.writeInt8(CREATE_INVALID_SLOT);
            client.send(reply);
            return;
        }

        if ((int)chars.size() >= mMaxCharacters)
        {
            reply.writeInt8(CREATE_TOO_MUCH_CHARACTERS);
            client.send(reply);
            return;
        }

        // TODO: Add race, face and maybe special attributes.

        // Customization of character's attributes...
        std::vector<int> attributes = std::vector<int>(mModifiableAttributes.size(), 0);
        for (unsigned int i = 0; i < mModifiableAttributes.size(); ++i)
            attributes[i] = msg.readInt16();

        int totalAttributes = 0;
        for (unsigned int i = 0; i < mModifiableAttributes.size(); ++i)
        {
            // For good total attributes check.
            totalAttributes += attributes.at(i);

            // For checking if all stats are >= min and <= max.
            if (attributes.at(i) < mAttributeMinimum
                || attributes.at(i) > mAttributeMaximum)
            {
                reply.writeInt8(CREATE_ATTRIBUTES_OUT_OF_RANGE);
                client.send(reply);
                return;
            }
        }

        if (totalAttributes > mStartingPoints)
        {
            reply.writeInt8(CREATE_ATTRIBUTES_TOO_HIGH);
        }
        else if (totalAttributes < mStartingPoints)
        {
            reply.writeInt8(CREATE_ATTRIBUTES_TOO_LOW);
        }
        else
        {
            Character *newCharacter = new Character(name);

            // Set the initial attributes provided by the client
            for (unsigned int i = 0; i < mModifiableAttributes.size(); ++i)
            {
                newCharacter->mAttributes.insert(
                            std::make_pair(mModifiableAttributes.at(i), attributes[i]));
            }

            newCharacter->mAttributes.insert(mDefaultAttributes.begin(),
                                             mDefaultAttributes.end());
            newCharacter->setAccount(acc);
            newCharacter->setCharacterSlot(slot);
            newCharacter->setLevel(1);

            // Init GP value to avoid flawed ones.
            AttributeMap::iterator itr =
                newCharacter->mAttributes.find(ATTR_GP);
            if (itr != newCharacter->mAttributes.end())
            {
                itr->second.base = 0;
                itr->second.modified = 0;
            }

            newCharacter->setCharacterPoints(0);
            newCharacter->setCorrectionPoints(0);
            newCharacter->setGender(gender);
            newCharacter->setHairStyle(hairStyle);
            newCharacter->setHairColor(hairColor);
            newCharacter->setMapId(Configuration::getValue("char_startMap", 1));
            Point startingPos(Configuration::getValue("char_startX", 1024),
                              Configuration::getValue("char_startY", 1024));
            newCharacter->setPosition(startingPos);
            acc->addCharacter(newCharacter);

            LOG_INFO("Character " << name << " was created for "
                     << acc->getName() << "'s account.");

            storage->flush(acc); // flush changes

            // log transaction
            Transaction trans;
            trans.mCharacterId = newCharacter->getDatabaseID();
            trans.mAction = TRANS_CHAR_CREATE;
            trans.mMessage = acc->getName() + " created character ";
            trans.mMessage.append("called " + name);
            storage->addTransaction(trans);

            reply.writeInt8(ERRMSG_OK);
            client.send(reply);

            // Send new characters infos back to client
            sendCharacterData(client, *chars[slot]);
            return;
        }
    }

    client.send(reply);
}