Example #1
0
void callFunc(AstNode* ast) {
	FuncObject* func = null;
	for (list<FuncObject*>::reverse_iterator i = funcs.rbegin(); i != funcs.rend(); i++) {
		FuncObject *obj = *i;

		if (strcmp(obj->name, (char*) ast->value) == 0) {
			func = obj;
			break;
		}
	}

	if (func == null) {
		printf("Unknown variable %s", (char*) ast->value);
		exit(1);
	}

	AstNode* node = func->value->left;
	AstNode* valNode = ast->left;
	while (node != null && node->left != null && valNode != null && valNode->left != null) {
		DefObject *object = (DefObject*) node->left->left->value;
		defineVar(object->name, calc(valNode->left));

		node = node->right;
		valNode = valNode->right;
	}

	_interpretate(func->value->right);
}
Example #2
0
int find_match(unsigned long src, unsigned long dst, double ts, double interval)
{
  list<ts_src_dst>::reverse_iterator it;
  for(it=interval_packets.rbegin(); it!= interval_packets.rend(); ++it)
  {
    if(src == it->_dst && dst == it->_src)
    {
      /*
      memset(srcip_buf, 0, 256);
      memset(dstip_buf, 0, 256);
      strcpy(srcip_buf, inet_ntoa(src_ip));
      strcpy(dstip_buf, inet_ntoa(dst_ip));

      src_ip1.s_addr = it->_src;
      dst_ip1.s_addr = it->_dst;
      memset(srcip_buf1, 0, 256);
      memset(dstip_buf1, 0, 256);
      strcpy(srcip_buf1, inet_ntoa(src_ip1));
      strcpy(dstip_buf1, inet_ntoa(dst_ip1));
      printf("%f\t%s\t%s\t%f\t%s\t%s\n",it->_ts, srcip_buf1, dstip_buf1, ts, srcip_buf, dstip_buf);
      */
      if(ts-it->_ts <= interval)
	return 1;
    }
  }
  return 0;
}
Example #3
0
//display in rorder
void display_all_r(const list<int> &li)
{
	list<int>::const_reverse_iterator riter;
	for(riter = li.rbegin(); riter!= li.rend(); riter++)
		cout << *riter << " , ";
	cout << "\n";	
}
Example #4
0
void checkdumpnesting(string &s, unsigned int team, list< vector<fixture> > &prevgames, unsigned int n) {
	char buffer[100];
	list< vector<fixture> >::reverse_iterator rit;
	bool stop=false;
	vector<unsigned int> teamssincelast(n,0);
	for( rit=prevgames.rbegin() ; rit != prevgames.rend(); rit++ ) {
		vector<fixture>::iterator fx;
		for(fx=rit->begin() ; fx != rit->end(); fx++ ) {
			if(fx->team1==team || fx->team2==team) {
				stop=true;
				break;
			}
		}
		if(stop) break;
		for(fx=rit->begin() ; fx != rit->end(); fx++ ) {
			teamssincelast[fx->team1]++;
			teamssincelast[fx->team2]++;
		}
	}
	string cat;
	for(unsigned int i=0; i<n; i++) {
		if(teamssincelast[i]>=2) {
			snprintf(buffer, sizeof(buffer), " %d,", i+1);
			cat+=buffer;
		}
	}
	if(cat.size()) {
		snprintf(buffer, sizeof(buffer), "\t%d:", team+1);
		s+=buffer;
		s+=cat;
	}
}
Example #5
0
	bool is_erased(sc_addr val)
	{
		list::reverse_iterator iter = erased->rbegin();
		while (iter != erased->rend())
			if (*iter++ == val)
				return true;
		return false;
	}
Example #6
0
int main() {
  int cpt = 1;
  bool Uvide,Lvide;
  flott x,y,per;
  list<point>::iterator it;
  list<point>::reverse_iterator rit;
  point a;

  while (cin >> n) {
    if (n==0) return 0;
    pts.clear();
    for (int i=0; i<n; i++) {
      cin >> x >> y;
      pts.push_back(point(x,y));
    }
    Andrew();
    
    cout << "Region #" << cpt++ << ":\n";

    Uvide = U.empty();
    Lvide = L.empty();
    
    
    if (Uvide) per = dist(L.front(),L.back());
    else if (Lvide) per = dist(U.front(),U.back());
    else per = dist(L.front(),U.front())+dist(L.back(),U.back());

    if (!Uvide) printf("(%.1f,%.1f)-",round(10*U.back().first)/10,round(10*U.back().second)/10);
    else printf("(%.1f,%.1f)-",round(10*L.back().first)/10,round(10*L.back().second)/10);

    if (!Lvide) {
      a = L.back();
      rit = L.rbegin();
      while (rit!=L.rend()) {
	per += dist(a,*rit);
	printf("(%.1f,%.1f)-",round(10*(rit->first))/10,round(10*(rit->second))/10);
	a = *rit;
	rit++;
      }
    }
    if (!Uvide) {
    it = U.begin();
    a = *it;
    while (it!=U.end()) {
      per += dist(a,*it);
      printf("(%.1f,%.1f)",round(10*it->first)/10,round(10*it->second)/10);
      a = *it;
      it++;
      if (it!=U.end()) cout << '-';
      else cout << '\n';
    }
    }
    printf("Perimeter length = %.2f\n\n",round(100*per)/100);
  }

  return 0;
}
Example #7
0
void CRealTextParser::PopTag(list<Tag>& p_rlistTags, const wstring& p_crszTagName)
{
    for (list<Tag>::reverse_iterator riter = p_rlistTags.rbegin(); riter != p_rlistTags.rend(); ++riter) {
        if (riter->m_szName == p_crszTagName) {
            p_rlistTags.erase((++riter).base());
            return;
        }
    }
}
Example #8
0
void
process(vector<int> const v, list<int> &lst, unsigned int n)
{
    list<int>::iterator k = lst.begin();

    for (vector<int>::const_iterator i = v.begin(); i < v.end() && k != lst.end(); i += n, ++k){
            *k = *i;
    }
    copy(lst.rbegin(), lst.rend(), ostream_iterator<int>(cout, " "));
    return;
}
Example #9
0
void QueueWithPriority::print() {
    cout << "--- Print Queue ---" << endl;
    if ( qwp_list.empty() ) {
        cout << "Queue is empty" << endl;
    } else {
        cout << "Queue size: " << qwp_list.size() << endl;
    }
    // обратный итератор потому что наша очередь наоборот
    list<QueueElement>::reverse_iterator it;
    for (it=qwp_list.rbegin(); it!=qwp_list.rend(); ++it) {
        cout << "QueueElement: " << (*it).name << " - " << (*it).priority << endl;
    }
}
Example #10
0
list<char> mult(list<char> a, list<char> b) {
  //int ia, ib, ic(0), carry(0), c;
  int carry, c, ic;
  list<char>::reverse_iterator ia, ib;
  int lena = a.size();
  int lenb = b.size();
  char crev[ MAX_LEN_PROD * 2 + 3 ];
  memset(crev, '0', MAX_LEN_PROD * 2 + 3);
  for(ib = b.rbegin(); ib != b.rend(); ++ib) {    
    ic = distance(b.rbegin(),ib);
    carry = 0;
    for(ia = a.rbegin(); ia != a.rend(); ++ia) {      
      c = (*ib - '0') * (*ia - '0') + carry + crev[ic] - '0';
      carry = c / 10;
      crev[ ic++ ] = c % 10 + '0';
    }
    crev[ ic ] = carry + '0';
  }
  list<char> ret(crev, crev + ic + (carry > 0 ? 1 : 0));
  ret.reverse();
  return ret;
}
Example #11
0
	bool satisfiable() {
		for (size_t i = 1; i < size; i++)
			if (!visited[i])
				dfs(i);

		for (auto it = post_order.rbegin(); it != post_order.rend(); it++)
			if (visited[*it] && visited[not_(*it)])
				dfsr(*it);

		for (size_t i = 1; i <= atoms; i++)
			if (solution[i] && solution[not_(i)])
				return false;
		return true;
	}
Example #12
0
VarObject* findVar(char* name) {
	for (list<VarObject*>::reverse_iterator i = vars.rbegin(); i != vars.rend(); i++) {
		VarObject *obj = *i;

		if (strcmp(obj->name, name) == 0) {
			return obj;
		}
	}

	printf("Unknown variable %s", name);
	exit(1);

	return null;
}
void InterpreterDBG::sendStackInfo(list<pair<string, int> >& stk) {
  if(clientsock < 0) return;

  stringstream s;
  s << "<stackinfo>";
  int id = 0;
  for(list<pair<string, int> >::reverse_iterator it = stk.rbegin(); it != stk.rend(); ++it) {
    s << "<entry id=\"" << id++
      << "\" function=\"" << (*it).first
      << "\" line=\"" << (*it).second << "\"/>";
  }
  s << "</stackinfo>";

  sendData(s);
}
long long decode(list<int> &number,int base)
{

	long long num=0;
	long long power=1;
	for(list<int>::reverse_iterator i=number.rbegin();i!=number.rend();i++)
	{
		if(*i>0)
		{
			num+=power*(*i);
		}
		power*=base;
	}
	return num;
}
void SipCtrlInterface::prepare_routes_uac(const list<sip_header*>& routes, string& route_field)
{
    if(!routes.empty()){
	
	list<sip_header*>::const_reverse_iterator it = routes.rbegin();

	route_field = c2stlstr((*it)->value);
	++it;

	for(; it != routes.rend(); ++it) {
		
	    route_field += ", " + c2stlstr((*it)->value);
	}
    }
}
Example #16
0
void g(list<int>& l) {
    list<int> tmp;
    list<int>::iterator it;
    list<int>::reverse_iterator rt;
    for (it = l.begin(); it != l.end(); it++)
        tmp.push_back(*it);
    l.clear();
    for (it = tmp.begin(); it != tmp.end(); it++) {
        l.push_back(*it);
        l.push_back(*it);
    }
    for (rt = l.rbegin(); rt != l.rend(); rt++)
        cout << *rt << " ";
    cout << endl;
}
// Formats the mapping of the ConfigurableElements
string CSubsystem::formatMappingDataList(
        const list<const CConfigurableElement*>& configurableElementPath) const
{
    // The list is parsed in reverse order because it has been filled from the leaf to the trunk
    // of the tree. When formatting the mapping, we want to start from the subsystem level
    ostringstream ossStream;
    list<const CConfigurableElement*>::const_reverse_iterator it;
    for (it = configurableElementPath.rbegin(); it != configurableElementPath.rend(); ++it) {

        const CInstanceConfigurableElement* pInstanceConfigurableElement =
                static_cast<const CInstanceConfigurableElement*>(*it);

        ossStream << pInstanceConfigurableElement->getFormattedMapping() << ", ";
    }
    return ossStream.str();
}
Example #18
0
void ReadTriMesh(){
  if (surface!=0){
    MovedTris.sort();
    int CheckSurface=0;
    for(list<int>::const_reverse_iterator it = MovedTris.rbegin(); it != MovedTris.rend(); it++){
      surface->RemoveTri(*it);
      CheckSurface=1;
    }
    MovedTris.clear();
    if (surface->no_tris==0 && CheckSurface !=0) {
      delete surface;
      mesh->surf_list.remove(surface);
      mesh->no_surfs=mesh->no_surfs-1;
    }
  }
  surface = mesh->CreateSurface();
}
vector<pair<int,double>> PastPricesTrendLine::findLocalOptima(list<double>& pastPrices, bool max)
{
	vector<pair<int,double>> result;

	bool previousAscending = false;
	bool previousDescending = false;
	bool ascending = false;
	bool descending = false;
	double lastPrice;

	list<double>::reverse_iterator rit;
	rit = pastPrices.rbegin();
	int position = 0;
	while (result.size() < 2 && rit != pastPrices.rend())
	{
		previousAscending = ascending;
		previousDescending = descending;
		if (rit != pastPrices.rbegin())
		{
			ascending = *rit - lastPrice > 0;
			descending = *rit - lastPrice < 0;
		}
		if (position > 2)
		{
			if (max)
			{
				if (descending && previousAscending || (!ascending && !descending && !previousAscending && !previousDescending))
				{
					result.emplace_back(position, *rit);
				}
			}
			else
				if (ascending && !previousAscending || (!ascending && !descending && !previousAscending && !previousDescending))
				{
					result.emplace_back(position, *rit);
				}

		}
		lastPrice = *rit;
		rit++;
		position++;;
	}
	return result;
}
Example #20
0
RObject *get_variable(const char *name){
  list<unordered_map<string, RObject*>*>::reverse_iterator rit;
  //unordered_map<string, Instruccion*>* stack;
  rit = scope_stack.rbegin();
  RObject *object=NULL;
  do {
    if ((*rit)->find(name) != (*rit)->end())
      object = (**rit)[name];
    rit++;
  } while (object == NULL && rit != scope_stack.rend());
  if (name[0] == '@' && object == NULL && excecuting_current_class != NULL)
    object = excecuting_current_class->get_instance_variable(name);
  if (object == NULL && global_variables->find(name) != global_variables->end())
    object = (*global_variables)[name];
  if (object == NULL){
    object = new RObject(true);
  }
  return object;
}
Example #21
0
static void cb_mouse(double mx, double my, int flags)
{
	if (flags & MOUSE_RELEASE)
	{
		points.push_back(new Point(mx,my));
		if(points.size() > 1)
		{
			auto ip(points.rbegin());
			auto jp(points.rbegin());
			ip++;
			Point p3 = **jp;
			for(; ip!=points.rend(); ip++)
			{
				Point p4 = **ip;
				edges.push_back(new Edge(p3,p4));
            }
		}
	}
};
Example #22
0
void Skel_Set::sort_culled_skels( Skel_Ali* sa, list<Skel_Ali*>& skel_list, int max )
{

  list<Skel_Ali*>::reverse_iterator rit = skel_list.rbegin();

  while( ( rit != skel_list.rend() ) && ( (*rit)->get_param() > sa->get_param() ) ) {
    rit++;
  }
  skel_list.insert( rit.base(), sa );

  if( (int)skel_list.size() > max ) {

    // can assume tracking_mode is true (wouldn't call this function otherwise)
    delete skel_list.back(); // free up the memory from this alignment
    skel_list.pop_back();    // erase from the list of top alignments
    skels_deleted++;

  }

}
Example #23
0
int sumowanie(list<proces> lista)
{
	unsigned int suma=0, suma_tmp=0;
	for(list<proces>::iterator it=lista.begin();it!=lista.end();it++)
	{
		if(it->r>=suma)
			suma=it->r;
		suma+=it->p;
	}
	for(list<proces>::reverse_iterator it=lista.rbegin();it!=lista.rend();it++)
	{
		if(it->q>=suma_tmp)
			suma_tmp=it->q;
		suma_tmp+=it->p;
	}
	suma+=suma_tmp;
	for(list<proces>::iterator it=lista.begin();it!=lista.end();it++)
		suma-=it->p;
	return suma;
}
Example #24
0
inline unsigned int getcost(unsigned int i, unsigned int j, list< vector<fixture> > &prevgames, unsigned int n, const costfuncparams &cfp) {
	if(i==j) return INT_MAX;
	unsigned int tcost=0;
	unsigned int tcost2=0;
	bool gotprevi=false;
	bool gotprevj=false;
	unsigned int lastcircdisti=0;
	unsigned int lastcircdistj=0;
	list< vector<fixture> >::reverse_iterator rit;
	unsigned int iternum=1;
	for( rit=prevgames.rbegin() ; rit != prevgames.rend(); rit++ ) {
		unsigned int cost=0;
		unsigned int dist=(cfp.circular)?min(iternum, cfp.circle_length-iternum):iternum;
		vector<fixture>::iterator fx;
		for(fx=rit->begin() ; fx != rit->end(); fx++ ) {
			if(fx->team1==i && fx->team2==j) tcost2+=100000;
			if(fx->team1==i || fx->team2==i) {
				cost+=1;
				if(!gotprevi) tcost2+=max(5000.0-50.0*pow((dist-cfp.targetgap),3),0.0);
				else lastcircdisti=dist;
				gotprevi=true;
			}
			if(fx->team1==j || fx->team2==j) {
				cost+=1;
				if(!gotprevj) tcost2+=max(5000.0-50.0*pow((dist-cfp.targetgap),3),0.0);
				else lastcircdistj=dist;
				gotprevj=true;
			}
		}
		if(cost) tcost+=(((double) cost)*(100.0+(250.0*exp(-sqrt(dist)))));
		if((debug>=DEBUG_TCOSTCOND && cost) || debug>=DEBUG_TCOSTALL ) printf("%d v %d, tcost: %d, tcost2: %d, iternum: %d, dist: %d, cost: %d\n", i+1, j+1, tcost, tcost2, iternum, dist, cost);
		iternum++;
	}
	if(cfp.circular && iternum+cfp.targetgap>=cfp.circle_length) {
		if(lastcircdisti) tcost2+=max(5000.0-50.0*pow((lastcircdisti-cfp.targetgap),3),0.0);
		if(lastcircdistj) tcost2+=max(5000.0-50.0*pow((lastcircdistj-cfp.targetgap),3),0.0);
	}
	return tcost+tcost2;
}
Example #25
0
/**
 * Fill a vector with x highest FunThings contained in a supplied STL container.
 * A string exception must be thrown if the number of highest elements sought (x)
 * is greater than the number of elements in the container or if that number is
 * less-than 1.
 * @param collection    An STL container list<FunThing*> used as data source.
 * @param highestThings An STL container list<FunThing*> to store the result.
 * @param howMany       Specifies how many items to obtain from the highest.
 */
void getHighest( list<FunThing*> &collection,
                 list<FunThing*> &highestThings,
                 int howMany ) {

    // A string exception must be thrown if the number of highest elements
    // sought (x) is greater than the number of elements in the container or if
    // that number is less-than 1.
    if ( howMany < 1 ) {
        // throw new out_of_range();
        throw("Error: the number of highest elements sought must be greater than 1");

    } else if ( howMany > collection.size() ) {
        // throw new out_of_range();
        throw( "Error: the number of highest elements sought must not be greater than the number of elements in the container" );
    }

    collection.sort( compareFunThingPointers );

    // Create a reverse-iterator of list<FunThing*> type.
    list<FunThing*>::reverse_iterator iterator;

    // An temp variable to make the code easier to understand.
    FunThing* currentElement;

    // Iterate over the list using that iterator.
    int count = 0;
    for ( iterator  = collection.rbegin() ;
          iterator != collection.rend() && count < howMany ;
          iterator++, count++ ) {

        // Retrieve the current element.
        currentElement = *iterator;

        // Push the element to the highestThings list.
        highestThings.push_back( currentElement );
    }
}
Example #26
0
Mesh* Load3ds(string URL, Entity* parent_ent){
  int Size;
  //Local OldDir:String
  unsigned char Red, Green, Blue;
  //unsigned char Percent;
  //Local Pixmap:TPixmap
  Stream = File::ReadResourceFile(URL);
  if (Stream == 0) return 0;

  //Size = Stream.Size()
  fseek(Stream->pFile, 0, SEEK_END); // seek to end of file
  Size = ftell(Stream->pFile); // get current file pointer
  fseek(Stream->pFile, 0, SEEK_SET);

  // Read Main-Chunk
  ReadChunk();
  if (ChunkID != M3D_3DS_MAIN || ChunkSize != Size) {
    Stream->CloseFile();
    //Print "No 3DS File"
    return 0;
  }
  // Find 3DEditor-Chunk
  while (Stream->Eof()==0){
    ReadChunk();
    if (ChunkID == M3D_3DS_3DEDITOR){
      break;
    }else{
      SkipChunk();
    }
  }

  //OldDir = CurrentDir()
  //If String(URL) <> "" Then ChangeDir(ExtractDir(String(URL)))
  mesh = Mesh::CreateMesh();
  while (Stream->Eof()==0){
    ReadChunk();
    switch (ChunkID){
    case M3D_3DS_OBJECTBLOCK:
      ReadCString(); // ' ObjectName
      break;
    case M3D_3DS_BrushBLOCK:
      ReadBrushBlock();
      break;
    case M3D_3DS_TRIMESH:
      ReadTriMesh();
      break;
    case M3D_3DS_VERTEXLIST:
      ReadVertexList();
      break;
    case M3D_3DS_FACELIST:
      ReadFaceList();
      break;
    case M3D_3DS_FACEMATLIST:
      ReadFaceMatList();
      break;
    case M3D_3DS_TEXCOORDS:
      ReadTexCoords();
      break;
    case M3D_3DS_BrushNAME:
      //Loader.Brush = CreateBrush()
      brush->name = ReadCString();
      break;
    case M3D_3DS_BrushAMBIENT:
      //ReadChunk();
      //ReadRGB(ChunkID, Red, Green, Blue);
      //brush->SetAmbientColor(Red, Green, Blue);
      break;
    case M3D_3DS_BrushDIFFUSE:
      ReadChunk();
      ReadRGB(ChunkID, Red, Green, Blue);
      brush->BrushColor(Red, Green, Blue);
      break;
    case M3D_3DS_BrushSPECULAR:
      //'Loader.ReadChunk()
      //'Loader.ReadRGB(Loader.ChunkID, Red, Green, Blue)
      //'Loader.Brush.SetSpecularColor(Red, Green, Blue)
      break;
    case M3D_3DS_BrushSHININESS:
      //'Loader.ReadChunk()
      //'Percent = Loader.ReadPercent(Loader.ChunkID)
      //'Loader.Brush.BrushShininess(Percent)
      break;
    case M3D_3DS_MAPFILENAME:
      LoadMap();
      break;
    case M3D_3DS_MAPVSCALE:
      texture->v_scale = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPUSCALE:
      texture->u_scale = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPUOFFSET:
      texture->u_pos = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPVOFFSET:
      texture->v_pos = Stream->ReadFloat();
      break;
    case M3D_3DS_MAPROTATION:
      texture->angle = Stream->ReadFloat();
      break;
    default:
      if ((ChunkID == M3D_3DS_TEXTUREMAP1) || (ChunkID == M3D_3DS_TEXTUREMAP2)) {
        ReadMap(ChunkID);
      }else{
        SkipChunk();
      }
    }
  }
  Stream->CloseFile();

  if (surface!=0){
    MovedTris.sort();
    int CheckSurface=0;
    for(list<int>::const_reverse_iterator it = MovedTris.rbegin(); it != MovedTris.rend(); it++){
      surface->RemoveTri(*it);
      CheckSurface=1;
    }
    MovedTris.clear();

    if (surface->no_tris==0 && CheckSurface !=0) {
      delete surface;
      mesh->surf_list.remove(surface);
      mesh->no_surfs=mesh->no_surfs-1;
    }
  }


//    ChangeDir(OldDir)
//    Loader.Surface.UpdateVertices()
//    Loader.Surface.UpdateTriangles()
  mesh->UpdateNormals();
  /*Loader.Mesh.UpdateBuffer()
  Print Loader.Surface.Tris.Length
  Print Loader.Surface.no_verts
  'Loader.Mesh.FlipMesh()*/

  mesh->class_name="Mesh";
  mesh->AddParent(*parent_ent);
  Entity::entity_list.push_back(mesh);
  if(mesh->parent!=0){
    mesh->mat.Overwrite(mesh->parent->mat);
    mesh->UpdateMat();
  }else{
    mesh->UpdateMat(true);
  }
  return mesh;
}
    void onReceivingMessage(string sender,vector<string>& msgs) {

        for(vector<string>::iterator i=msgs.begin(); i!=msgs.end(); i++)
            cerr<<sender<<":"<<(*i)<<endl;

        int mode;
        if(sender.substr(0,2)=="fg") {
            mode=UPDATE_FG;
        } else if(sender.substr(0,2)=="bg") {
            mode=UPDATE_BG;
        } else {
            //unknown sender. Do nothing
            return;
        }

        vector<string> splits;

        for(vector<string>::iterator i=msgs.begin(); i!=msgs.end(); i++)
        {
            string& msg=*i;
            StringUtil::split(msg,"\t",splits);
            int msgCycleNumber=StringUtil::atoi(splits[0]);
            if(splits[1]=="Error") {
                cerr<<"Error occured at "<<sender<<" : "<<splits[2]<<endl;
                cerr<<"Abort"<<endl;
                cerr<<"Sending all slaves !TERMINATE"<<endl;
                terminateAllSlaves();
                terminate(); //terminate myself too
            } else if(splits[1]=="Hi") {
                hirespondents++;
            } else if(splits[1]=="KmerCountUpdate") {

                if(msgCycleNumber!=cycle) {
                    cerr<<"Inconsistent cycle number from slave "<<sender<<" msgCycleNumber="<<msgCycleNumber<<" cycleHere="<<cycle<<endl;
                    cerr<<"Abort"<<endl;
                    cerr<<"Sending all slaves !TERMINATE"<<endl;
                    terminateAllSlaves();
                    terminate();
                } else {
                    cerr<<"loadKmerUpdate from "<<sender<<" at cycle "<<cycle<<"…";
                    loadKmerUpdateFile(outDir+DS+KMERUPDATEPATH+DS+sender+".txt",mode,cycle==1); //only at cycle one allowing new kmer to be added.
                    cerr<<"done"<<endl;
                    respondents++;
                    if(respondents==totalSlaves) {
                        cerr<<"all slaves updated kmer counts at cycle "<<cycle<<endl;
                        cerr<<"now find top enriched kmer at cycle "<<cycle<<endl;

#ifdef USE_NUM_SEQS_FOR_NORMALIZATION
                        double normalizationFactor=double(this->bgTotalNumSeqs)/this->fgTotalNumSeqs;
                        cerr<<"fgTotalNumSeqs="<<this->fgTotalNumSeqs<<" bgTotalNumSeqs="<<this->bgTotalNumSeqs<<" normalization factor (*bt/ft)="<<normalizationFactor<<endl;
#else
                        double normalizationFactor=double(this->bgTotalKmerPositions)/this->fgTotalKmerPositions;
                        cerr<<"fgTotalKmerPositions="<<this->fgTotalKmerPositions<<" bgTotalKmerPositions="<<this->bgTotalKmerPositions<<" normalization factor (*bt/ft)="<<normalizationFactor<<endl;
#endif

                        //cerr<<"a"<<endl;
                        kmerRecord* topKmer=sortAndFindTopKmer();
                        if (!topKmer)
                        {
                            cerr<<"List exhausted. Abort"<<endl;
                            cerr<<"Sending all slaves !TERMINATE"<<endl;
                            terminateAllSlaves();
                            terminate();

                        }
                        //cerr<<"c"<<endl;
                        //output this topKmer
                        string kmerSeq = topKmer->kmerSeq;
                        //cerr<<"d"<<endl;
                        if(cycle==1) {
#ifdef USE_NUM_SEQS_FOR_NORMALIZATION
                            (*fout)<<"kmer\tenrichment\tcontrol_count\texperim_count\tcontrol_total_seqs\texperim_total_seqs\tnormalization_factor"<<endl;
#else
                            (*fout)<<"kmer\tenrichment\tcontrol_count\texperim_count\tcontrol_total_pos\texperim_total_pos\tnormalization_factor"<<endl;
#endif

                            //also out the enrichment without any subtraction
                            cerr<<"Output Kmer Unsubtracted Enrichment File"<<endl;
                            ofstream foutKmerUnsub((outDir+DS+"kmers_unsub.txt").c_str());
                            //top kmer first (because it has been poped from the list
#ifdef USE_NUM_SEQS_FOR_NORMALIZATION
                            foutKmerUnsub<<"kmer\tenrichment\tcontrol_count\texperim_count\tcontrol_total_seqs\texperim_total_seqs\tnormalization_factor"<<endl;
                            foutKmerUnsub<<kmerSeq<<"\t"<<topKmer->enrichment(normalizationFactor)<<"\t"<<topKmer->bgInstances<<"\t"<<topKmer->fgInstances<<"\t"<<this->bgTotalNumSeqs<<"\t"<<this->fgTotalNumSeqs<<"\t"<<normalizationFactor<<endl;
#else
                            foutKmerUnsub<<"kmer\tenrichment\tcontrol_count\texperim_count\tcontrol_total_pos\texperim_total_pos\tnormalization_factor"<<endl;
                            foutKmerUnsub<<kmerSeq<<"\t"<<topKmer->enrichment(normalizationFactor)<<"\t"<<topKmer->bgInstances<<"\t"<<topKmer->fgInstances<<"\t"<<this->bgTotalKmerPositions<<"\t"<<this->fgTotalKmerPositions<<"\t"<<normalizationFactor<<endl;
#endif

                            for(list< SmartPtr<kmerRecord> >::reverse_iterator ri=kmers.rbegin(); ri!=kmers.rend(); ri++) {
                                kmerRecord* curKmer=(*ri);

#ifdef USE_NUM_SEQS_FOR_NORMALIZATION
                                foutKmerUnsub<<curKmer->kmerSeq<<"\t"<<curKmer->enrichment(normalizationFactor)<<"\t"<<curKmer->bgInstances<<"\t"<<curKmer->fgInstances<<"\t"<<this->bgTotalNumSeqs<<"\t"<<this->fgTotalNumSeqs<<"\t"<<normalizationFactor<<endl;
#else
                                foutKmerUnsub<<curKmer->kmerSeq<<"\t"<<curKmer->enrichment(normalizationFactor)<<"\t"<<curKmer->bgInstances<<"\t"<<curKmer->fgInstances<<"\t"<<this->bgTotalKmerPositions<<"\t"<<this->fgTotalKmerPositions<<"\t"<<normalizationFactor<<endl;
#endif

                            }

                            foutKmerUnsub.close();
                        }

#ifdef USE_NUM_SEQS_FOR_NORMALIZATION
                        (*fout)<<kmerSeq<<"\t"<<topKmer->enrichment(normalizationFactor)<<"\t"<<topKmer->bgInstances<<"\t"<<topKmer->fgInstances<<"\t"<<this->bgTotalNumSeqs<<"\t"<<this->fgTotalNumSeqs<<"\t"<<normalizationFactor<<endl;
#else
                        (*fout)<<kmerSeq<<"\t"<<topKmer->enrichment(normalizationFactor)<<"\t"<<topKmer->bgInstances<<"\t"<<topKmer->fgInstances<<"\t"<<this->bgTotalKmerPositions<<"\t"<<this->fgTotalKmerPositions<<"\t"<<normalizationFactor<<endl;
#endif

                        delete topKmer; //free it from memory

                        if(topN > 0 && cycle==topN) {
                            //we are done
                            cerr<<topN<<" top kmer(s) have been outputted. End slaves and master"<<endl;
                            cerr<<"Sending all slaves !TERMINATE"<<endl;
                            terminateAllSlaves();
                            terminate();
                        } else {

                            //advance
                            cerr<<"top Kmer at cycle "<<cycle<<" is "<<kmerSeq<<endl;

                            //now subtract the total kmer counts from fg and bg
                            this->fgTotalKmerPositions-=topKmer->fgInstances;
                            this->bgTotalKmerPositions-=topKmer->bgInstances;

                            updateCycleAndResetRespondents();
                            askSlavesToRemoveAndUpdate(kmerSeq);
                        }


                    }
                }
            }
        }


    }
Example #28
0
void print_reverse(list<T> lst)
{
	for (auto iter = lst.rbegin(); iter != lst.rend(); ++iter)
		cout << *iter << " ";
	cout << endl;
}
Example #29
0
bool GPT::parse(list<pair<string,istream*> >& istream_list) {
  stringstream s;
  
  try {
    TokenStreamSelector*  selector = new TokenStreamSelector;
    
    //codigo desgracado, mas faz o que deve
    //1: controle de multiplos tokenStreams
    //2: utilizar o filename adequado para error reporting

    PortugolLexer* lexer;
    PortugolLexer* prev = 0;
    PortugolLexer* fst = 0;
    string firstFile;
    int c = 0;
    for(list<pair<string,istream*> >::reverse_iterator it = istream_list.rbegin(); 
           it != istream_list.rend(); 
           ++it, ++c) 
    {
      lexer = new PortugolLexer(*((*it).second), selector);
      
      selector->addInputStream(lexer, (*it).first);
      selector->select(lexer);
      selector->push((*it).first);
      if(!firstFile.empty()) {
        lexer->setNextFilename(firstFile);
      } 

      prev = lexer;
      GPTDisplay::self()->addFileName((*it).first);

      firstFile = (*it).first;
      fst = lexer;
    }

    selector->select(fst);
    
    PortugolParser parser(*selector);

    GPTDisplay::self()->setCurrentFile(firstFile);
    
    ASTFactory ast_factory(PortugolAST::TYPE_NAME,&PortugolAST::factory);
    parser.initializeASTFactory(ast_factory);
    parser.setASTFactory(&ast_factory);

    parser.algoritmo();
    if(_outputfile.empty()) {
      _outputfile = parser.nomeAlgoritmo();
    }

    if(GPTDisplay::self()->hasError()) {
      GPTDisplay::self()->showErrors();
      return false;
    }

    _astree = parser.getPortugolAST();

    if(!_astree) {
      s << PACKAGE << ": erro interno: no parse tree" << endl;
      GPTDisplay::self()->showError(s);
      return false;
    }

    if(_printParseTree) {
      std::cerr << _astree->toStringList() << std::endl << std::endl;
    }

    SemanticWalker semantic(_stable);
    semantic.algoritmo(_astree);

    if(GPTDisplay::self()->hasError()) {
      GPTDisplay::self()->showErrors();
      return false;
    }
    return true;
  }
  catch(ANTLRException& e) {
    s << PACKAGE << ": erro interno: " << e.toString() << endl;
    GPTDisplay::self()->showError(s);
    return false;
  }
  catch(exception& e) {
    s << PACKAGE << ": erro interno: " << e.what() << endl;
    GPTDisplay::self()->showError(s);
    return false;
  }

  s << "GPT::parse: bug, nao deveria executar essa linha!" << endl;
  GPTDisplay::self()->showError(s);
  return false;
}
Example #30
0
void Trajectory::integrateBackward(list<TrajectoryStep> &trajectory, list<TrajectoryStep> &startTrajectory, double acceleration) {
	list<TrajectoryStep>::reverse_iterator before = startTrajectory.rbegin();
	double pathPos = trajectory.front().pathPos;
	double pathVel = trajectory.front().pathVel;

	while(true)
	{
		//pathPos -= timeStep * pathVel;
		//pathVel -= timeStep * acceleration;

		double oldPathVel = pathVel;
		pathVel -= timeStep * acceleration;
		pathPos -= timeStep * 0.5 * (oldPathVel + pathVel);

		trajectory.push_front(TrajectoryStep(pathPos, pathVel));
		acceleration = getMinMaxPathAcceleration(pathPos, pathVel, false);

		if(pathVel < 0.0 || pathPos < 0.0) {
			valid = false;
			cout << "error " << pathPos << " " << pathVel << endl;
			return;
		}

		while(before != startTrajectory.rend() && before->pathPos > pathPos) {
			before++;
		}

		bool error = false;

		if(before != startTrajectory.rbegin() && pathVel >= before->pathVel + getSlope(before.base()) * (pathPos - before->pathPos)) {
			TrajectoryStep overshoot = trajectory.front();
			trajectory.pop_front();
			list<TrajectoryStep>::iterator after = before.base();
			TrajectoryStep intersection = getIntersection(startTrajectory, after, overshoot, trajectory.front());
			//cout << "set arrow from " << intersection.pathPos << ", " << intersection.pathVel - 0.8 << " to " << intersection.pathPos << ", " << intersection.pathVel - 0.3 << endl;
		
			if(after != startTrajectory.end()) {
				startTrajectory.erase(after, startTrajectory.end());
				startTrajectory.push_back(intersection);
			}
			startTrajectory.splice(startTrajectory.end(), trajectory);

			return;
		}
		else if(pathVel > getAccelerationMaxPathVelocity(pathPos) + eps || pathVel > getVelocityMaxPathVelocity(pathPos) + eps) {
			// find more accurate intersection with max-velocity curve using bisection
			TrajectoryStep overshoot = trajectory.front();
			trajectory.pop_front();
			double slope = getSlope(overshoot, trajectory.front());
			double before = overshoot.pathPos;
			double after = trajectory.front().pathPos;
			while(after - before > 0.00001) {
				const double midpoint = 0.5 * (before + after);
				double midpointPathVel = overshoot.pathVel + slope * (midpoint - overshoot.pathPos);

				if(midpointPathVel > getAccelerationMaxPathVelocity(midpoint) || midpointPathVel > getVelocityMaxPathVelocity(midpoint))
					before = midpoint;
				else
					after = midpoint;
			}
			trajectory.push_front(TrajectoryStep(after, overshoot.pathVel + slope * (after - overshoot.pathPos)));

			if(getAccelerationMaxPathVelocity(before) < getVelocityMaxPathVelocity(before)) {
				if(trajectory.front().pathVel > getAccelerationMaxPathVelocity(before) + 0.0001) {
					error = true;
				}
				else if(getMinMaxPhaseSlope(trajectory.front().pathPos, trajectory.front().pathVel, false) < getAccelerationMaxPathVelocityDeriv(trajectory.front().pathPos)) { 
					error = true;
				}
			}
			else {
				if(getMinMaxPhaseSlope(trajectory.back().pathPos, trajectory.back().pathVel, false) < getVelocityMaxPathVelocityDeriv(trajectory.back().pathPos)) {
					error = true;
				}
			}
			
		}

		if(error) {
			ofstream file("trajectory.txt");
			for(list<TrajectoryStep>::iterator it = startTrajectory.begin(); it != startTrajectory.end(); it++) {
				file << it->pathPos << "  " << it->pathVel << endl;
			}
			for(list<TrajectoryStep>::iterator it = trajectory.begin(); it != trajectory.end(); it++) {
				file << it->pathPos << "  " << it->pathVel << endl;
			}
			file.close();
			cout << "error" << endl;
			valid = false;
			return;
		}
	}
}