void
setupNextSubsession(RTSPClient* rtspClient) {
	UsageEnvironment& env = rtspClient->envir(); // alias
	StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias
	bool rtpOverTCP = false;

	if(rtspconf->proto == IPPROTO_TCP) {
		rtpOverTCP = true;
	}

	scs.subsession = scs.iter->next();
	do if (scs.subsession != NULL) {
		if (!scs.subsession->initiate()) {
			env << *rtspClient << "Failed to initiate the \"" << *scs.subsession << "\" subsession: " << env.getResultMsg() << "\n";
			setupNextSubsession(rtspClient); // give up on this subsession; go to the next one
		} else {
			if(strcmp("video", scs.subsession->mediumName()) == 0) {
				video_sess_fmt = scs.subsession->rtpPayloadFormat();
				video_codec_name = strdup(scs.subsession->codecName());
				if(port2channel.find(scs.subsession->clientPortNum()) == port2channel.end()) {
					int cid = port2channel.size();
					port2channel[scs.subsession->clientPortNum()] = cid;
#ifdef ANDROID
					if(rtspconf->builtin_video_decoder != 0) {
						video_codec_id = ga_lookup_codec_id(video_codec_name);
					} else {
					////// Work with ffmpeg
#endif
					if(init_vdecoder(cid, scs.subsession->fmtp_spropparametersets()) < 0) {
						rtsperror("cannot initialize video decoder(%d)\n", cid);
						rtspParam->quitLive555 = 1;
						return;
					}
					rtsperror("video decoder(%d) initialized (client port %d)\n",
						cid, scs.subsession->clientPortNum());
#ifdef ANDROID
					////////////////////////
					}
#endif
				}
			} else if(strcmp("audio", scs.subsession->mediumName()) == 0) {
				const char *mime = NULL;
				audio_sess_fmt = scs.subsession->rtpPayloadFormat();
				audio_codec_name = strdup(scs.subsession->codecName());
#ifdef ANDROID
				if((mime = ga_lookup_mime(audio_codec_name)) == NULL) {
					showToast(rtspParam->jnienv, "codec %s not supported", audio_codec_name);
					rtsperror("rtspclient: unsupported audio codec: %s\n", audio_codec_name);
					usleep(300000);
					rtspParam->quitLive555 = 1;
					return;
				}
				audio_codec_id = ga_lookup_codec_id(audio_codec_name);
				if(android_prepare_audio(rtspParam, mime, rtspconf->builtin_audio_decoder != 0) < 0)
					return;
				if(rtspconf->builtin_audio_decoder == 0) {
				//////////////////////////////////////
				rtsperror("init software audio decoder.\n");
#endif
				if(adecoder == NULL) {
					if(init_adecoder() < 0) {
						rtsperror("cannot initialize audio decoder.\n");
						rtspParam->quitLive555 = 1;
						return;
					}
				}
#ifdef ANDROID
				//////////////////////////////////////
				}
#endif
				rtsperror("audio decoder initialized.\n");
			}
			env << *rtspClient << "Initiated the \"" << *scs.subsession
				<< "\" subsession (client ports " << scs.subsession->clientPortNum() << "-" << scs.subsession->clientPortNum()+1 << ")\n";

			// Continue setting up this subsession, by sending a RTSP "SETUP" command:
			rtspClient->sendSetupCommand(*scs.subsession, continueAfterSETUP, False, rtpOverTCP ? True : False/*TCP?*/, False, NULL);
		}
		return;
	} while(0);
	//

	// We've finished setting up all of the subsessions.  Now, send a RTSP "PLAY" command to start the streaming:
	scs.duration = scs.session->playEndTime() - scs.session->playStartTime();
	rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY);
}
Example #2
0
//------------------------------------------------------------------------------------
int AfterReadingFiles(int reading) throw(Exception)
{
try {
   int i,j,iret=0;

   if(reading == 1) {

         // compute data interval for this file
      for(j=0,i=1; i<9; i++) { if(PIC.ndt[i]>PIC.ndt[j]) j=i; }
      PIC.DT = PIC.estdt[j];
      PIC.oflog << endl;
      PIC.oflog << "Estimated data interval is " << PIC.DT << " seconds.\n";
      PIC.oflog << "Interpolate to " << PIC.irate << " times the input data rate\n";
      PIC.oflog << "Last data epoch is "
         << printTime(PIC.LastEpoch,"%04Y/%02m/%02d %02H:%02M:%06.3f = %4F %.3g") << endl;

      if(TimePositionMap.size() == 0) {
         cout << "No position information was found in the input file! Abort.\n";
         PIC.oflog << "No position information was found in the input file! Abort.\n";
         return -1;
      }
      PIC.oflog << endl;

         // dump the map of positions
      if(PIC.DumpMap) {
         PIC.oflog << "Here is all the Time/Position information:\n";
         map<CommonTime,PosInfo>::const_iterator itr;
         itr = TimePositionMap.begin();
         i = 0;
         while(itr != TimePositionMap.end()) {
            PIC.oflog << setw(4) << i << " "
               << printTime((itr->first),"%04Y/%02m/%02d %02H:%02M:%6.3f %4F %10.3g")
               << fixed << setprecision(3)
               << " " << setw(2) << itr->second.N
               << " " << setw(13) << itr->second.X
               << " " << setw(13) << itr->second.Y
               << " " << setw(13) << itr->second.Z
               << " " << setw(13) << itr->second.T
               << " " << setw(7) << itr->second.rms
               << endl;
            itr++;
            i++;
         }
         PIC.oflog << "End of the Time/Position information.\n\n";
      }

         // open output file
      if(!PIC.OutRinexObs.empty()) {
         ofstr.open(PIC.OutRinexObs.c_str(), ios::out);
         if(ofstr.fail()) {
            PIC.oflog << "Failed to open output file " << PIC.OutRinexObs
               << ". Abort.\n";
            return 1;
         }
         else PIC.oflog << "Opened output file " << PIC.OutRinexObs << endl;
         ofstr.exceptions(ios::failbit);
      }
   }
   else if(reading==2) {
      PIC.oflog << "Close the output file\n";
      ofstr.close();
   }

   return iret;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}
Example #3
0
CScript
ParseScript(string s)
{
    CScript result;

    static map<string, opcodetype> mapOpNames;

    if (mapOpNames.size() == 0)
    {
        for (int op = OP_NOP; op <= OP_NOP10; op++)
        {
            const char* name = GetOpName((opcodetype)op);
            if (strcmp(name, "OP_UNKNOWN") == 0)
                continue;
            string strName(name);
            mapOpNames[strName] = (opcodetype)op;
            // Convenience: OP_ADD and just ADD are both recognized:
            replace_first(strName, "OP_", "");
            mapOpNames[strName] = (opcodetype)op;
        }
    }

    vector<string> words;
    split(words, s, is_any_of(" \t\n"), token_compress_on);

    BOOST_FOREACH(string w, words)
    {
        if (all(w, is_digit()) ||
            (starts_with(w, "-") && all(string(w.begin()+1, w.end()), is_digit())))
        {
            // Number
            int64 n = atoi64(w);
            result << n;
        }
        else if (starts_with(w, "0x") && IsHex(string(w.begin()+2, w.end())))
        {
            // Raw hex data, inserted NOT pushed onto stack:
            std::vector<unsigned char> raw = ParseHex(string(w.begin()+2, w.end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w.size() >= 2 && starts_with(w, "'") && ends_with(w, "'"))
        {
            // Single-quoted string, pushed as data. NOTE: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w.begin()+1, w.end()-1);
            result << value;
        }
        else if (mapOpNames.count(w))
        {
            // opcode, e.g. OP_ADD or OP_1:
            result << mapOpNames[w];
        }
        else
        {
            BOOST_ERROR("Parse error: " << s);
            return CScript();
        }                        
    }

    return result;
}
void TestParallelThreads( map<int, string> &userspace_cpu, vector<string> &freq_event, int samplings, int thread_count ) {
    int rc;
    void *status;

    string err;

    if( userspace_cpu.size() < 1 ) {
        printf( "Insufficient CPUs available for threading test\n" );
        return;
    }

    printf( "Using %d processors\n", (int)userspace_cpu.size() );

    int node_count = 1000;
    map<int, string> cpu_avail_freq;
    map<int, string>::iterator cpu_it;

    map<int, string>::iterator freq_it;

    int max_threads = thread_count * userspace_cpu.size();

    pthread_t threads[max_threads];
    cpu_set_t cpus[max_threads];
    cpu_set_t check_cpu;
    pthread_attr_t thread_attrs[max_threads];

    throt_ctrl_t throts[max_threads];

    int max_time_lapse = -1, tmp_lapse;

    printf("# filling available throttling speeds\n");
    fillAvailableThrottlingSpeeds( cpu_avail_freq, 1 );
    int i, j, idx;

    // initialize thread attributes with cpu affinity
    // initialize throttling controls
    idx = 0;

//    for(idx = 0; idx < max_threads; idx++) {
//        CPU_ZERO( &cpus[idx]);
//    }
//
//    for(cpu_it = userspace_cpu.begin(); cpu_it != userspace_cpu.end(); cpu_it++) {
//        for(idx = 0; idx < max_threads; idx++) {
//            CPU_SET( cpu_it->first, &cpus[idx]);
//        }
//    }

    idx = 0;
    for( cpu_it = userspace_cpu.begin(), i = 0; cpu_it != userspace_cpu.end(); cpu_it++, i++ ) {
        for(j = 0; j < thread_count; ++j, ++idx) {
            CPU_ZERO( &cpus[idx] );
            CPU_SET( cpu_it->first, &cpus[idx] );
            pthread_attr_init( &thread_attrs[idx] );
//            pthread_attr_setscope(&thread_attrs[idx], PTHREAD_SCOPE_SYSTEM);   // explicitly state the each thread is its own process; (END result - no effect from either scope; something must be overriding)

            int val = pthread_attr_setaffinity_np( &thread_attrs[idx], sizeof( cpu_set_t ), &cpus[idx] );

            if( val ) {
                printf( "Set Affinity Fail: %s\n", strerror(val) );
            }
            pthread_attr_setdetachstate( &thread_attrs[idx], PTHREAD_CREATE_DETACHED ); // make thread detachable
//            pthread_attr_setschedpolicy( &thread_attrs[idx], SCHED_RR);
//            throts[idx].root = new node_t();
//            generateCircularGraph( throts[idx].root, node_count );


            throts[idx].cpu_id = cpu_it->first;
            throts[idx].node_count = node_count;
    //        ctrl_event_t ctrl1, ctrl2;
    //
    //        freq_it = cpu_avail_freq.begin();
    //        ctrl1.throt_speed = freq_it->second;
    //        ctrl2.throt_speed = cpu_avail_freq.rbegin()->second;
    //
    //        if( cpu_it->first  % 4 ) {
    //            throts[i].events.push_back( ctrl1 );
    //            throts[i].events.push_back( ctrl1 );
    //        } else {
    //            throts[i].events.push_back( ctrl1 );
    //            throts[i].events.push_back( ctrl2 );
    //        }

            tmp_lapse = buildEvents(freq_event, idx, cpu_avail_freq, throts[idx].events);
            if(max_time_lapse < tmp_lapse) {
                max_time_lapse = tmp_lapse;
            }
        }
    }

    TIME t1;
    timespec t;

    for( int samp = 0; samp < samplings; ++samp ) {
        printf( "Sampling...%d\n", samp );
        idx = 0;
        for( cpu_it = userspace_cpu.begin(), i = 0; cpu_it != userspace_cpu.end(); cpu_it++, i++ ) {
            for(j = 0; j < thread_count; ++j, ++idx) {
                if( rc = pthread_create( &threads[idx], &thread_attrs[idx], EventThreads, ( void * ) &throts[idx] ) ) {
                    printf( "Error creating threads\n" );
                    return;
                }

//                if( rc = pthread_setaffinity_np( threads[idx], sizeof( cpu_set_t ), &cpus[idx] ) ) {
//                    printf( "Error setting affinity %d: %s\n", idx, strerror(rc) );
//                }
            }
        }

//        idx = 0;
//        for( i = 0; i < userspace_cpu.size(); ++i ) {
//            for(j = 0; j < thread_count; ++j, ++idx) {
////                printf("Checking %d of %d (%d * %d), %d, %d\n", idx, max_threads, thread_count, (int)userspace_cpu.size(), i, j);
//                if( rc = pthread_getaffinity_np( threads[idx], sizeof( cpu_set_t ), &check_cpu ) ) {
//                    printf( "Error checking affinity %d: %s\n", idx, strerror(rc) );
//                } else {
//                    for( cpu_it = userspace_cpu.begin(); cpu_it !=  userspace_cpu.end(); cpu_it++ ) {
//                        if( CPU_ISSET( cpu_it->first, &check_cpu ) ) {
//                            printf( "\t%d -> %d\n", idx, cpu_it->first );
//                        }
//                    }
//                }
//            }
//        }

//        idx = 0;
//        for( cpu_it = userspace_cpu.begin(), i = 0; cpu_it != userspace_cpu.end(); cpu_it++, i++ ) {
//            for(j = 0; j < thread_count; ++j, ++idx) {
//                if( rc = pthread_join( threads[idx], &status ) ) {
//                    printf( "Error joining threads\n" );
//                    return;
//                }
//            }
//        }



        GetTime(t1);

        t = convertTimeToTimespec(t1);
        t.tv_sec += (max_time_lapse + 5);

        pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
        pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

        pthread_cond_timedwait( &cond, &mutex, &t);
    }

    printParallelThreadsTable( userspace_cpu, throts, samplings, thread_count );

    for(idx = 0; idx < max_threads; idx++) {
        pthread_attr_destroy(&thread_attrs[idx]);
    }
}
Example #5
0
// reads the SNDINFO lump
int S_Read_SNDSEQ(int lump)
{
  Parser p;
  sndseq_t temp;
  sndseq_t *ss;

  temp.number = -1;
  int i, n, hseq = -1;

  if (!p.Open(lump))
    return -1;

  CONS_Printf("Reading SNDSEQ...\n");

  p.RemoveComments(';');
  while (p.NewLine())
    {
      char line[33];

      n = p.GetString(line, 32);
      if (n > 0)
	{
	  if (line[0] == ':')
	    {
	      if (temp.number >= 0)
		CONS_Printf("Nested sequence in sequence %d.\n", temp.number);
	      else
		{
		  // new sequence
		  temp.clear();
		  temp.name = &line[1]; // omitting the colon

		  if (p.MustGetInt(&i))
		    temp.number = i; // Legacy format, :SeqName <number>
		  else
		    {
		      // old Hexen style kludge
		      for (i=0; i<NUMSEQ; i++)
			if (!strcasecmp(HexenSeqs[i].tag, line+1))
			  break;
		      if (i == NUMSEQ)
			{
			  CONS_Printf("No sequence number given for '%s'.\n", line);
			  temp.number = -2;
			  continue;
			}
		      else
			{
			  temp.number = HexenSeqs[i].seq[0];
			  hseq = i;
			}
		    }
		  //CONS_Printf(" starting seq %d, '%s'\n", temp.number, temp.name.c_str());
		}
	    }
	  else if (temp.number >= 0)
	    switch (P_MatchString(line, SOUNDSEQ_cmds))
	      {
	      case SSEQ_PLAY:
		if (p.GetString(line, 32))
		  {
		    temp.data.push_back(SSEQ_PLAY);
		    temp.data.push_back(S_GetSoundID(line));
		  }
		break;

	      case SSEQ_PLAYUNTILDONE:
		if (p.GetString(line, 32))
		  {
		    temp.data.push_back(SSEQ_PLAY);
		    temp.data.push_back(S_GetSoundID(line));
		    temp.data.push_back(SSEQ_WAITUNTILDONE);
		  }
		break;

	      case SSEQ_PLAYTIME:
		if (p.GetString(line, 32))
		  {
		    temp.data.push_back(SSEQ_PLAY);
		    temp.data.push_back(S_GetSoundID(line));
		    temp.data.push_back(SSEQ_DELAY);
		    temp.data.push_back(p.GetInt());
		  }

	      case SSEQ_PLAYREPEAT:
		if (p.GetString(line, 32))
		  {
		    temp.data.push_back(SSEQ_PLAYREPEAT);
		    temp.data.push_back(S_GetSoundID(line));
		  }
		break;

	      case SSEQ_DELAY:
		temp.data.push_back(SSEQ_DELAY);
		temp.data.push_back(p.GetInt());
		break;

	      case SSEQ_DELAYRAND:
		temp.data.push_back(SSEQ_DELAYRAND);
		temp.data.push_back(p.GetInt());
		temp.data.push_back(p.GetInt());
		break;

	      case SSEQ_VOLUME:
		temp.data.push_back(SSEQ_VOLUME);
		temp.data.push_back(p.GetInt());
		break;

	      case SSEQ_STOPSOUND:
		if (p.GetString(line, 32))
		  {
		    temp.data.push_back(SSEQ_STOPSOUND);
		    temp.stopsound = S_GetSoundID(line);
		  }
		break;

	      case SSEQ_END:
		temp.data.push_back(SSEQ_END);

		// create and store the sequence
		if (SoundSeqs.count(temp.number)) // already there
		  {
		    CONS_Printf("Warning: Sequence %d defined more than once!\n", temp.number);
		    delete SoundSeqs[temp.number]; // later one takes precedence
		  }

		ss = new sndseq_t(temp); // make a copy
		SoundSeqs[ss->number] = ss; // insert into the map

		//CONS_Printf(" seq %d done\n", ss->number);

		if (hseq >= 0)
		  { // other half of the Hexen kludge:
		    // some sequences need to be copied
		    for (n=1; n<3; n++)
		      if (HexenSeqs[hseq].seq[n] != -1)
			{
			  ss = new sndseq_t(temp);
			  ss->number = HexenSeqs[hseq].seq[n];
			  SoundSeqs[ss->number] = ss;
			  //CONS_Printf(" seq %d done\n", ss->number);
			}
		    
		    hseq = -1;
		  }

		temp.number = -1;
		break;

	      case SSEQ_VOLUMERAND:
		temp.data.push_back(SSEQ_VOLUMERAND);
		temp.data.push_back(p.GetInt());
		temp.data.push_back(p.GetInt());
		break;

	      case SSEQ_CHVOL:
		temp.data.push_back(SSEQ_CHVOL);
		temp.data.push_back(p.GetInt());
		break;

	      default:
		CONS_Printf("Unknown command '%s'.\n", line);
		break;
	      }
	}
    }

  CONS_Printf(" %d sequences found.\n", SoundSeqs.size());
  return SoundSeqs.size();
}
Example #6
0
    bool ChooserEvaluator::select_parameters(
        const std::vector<ChooserPoly> &operands, 
        int budget_gap, double noise_standard_deviation, 
        const map<int, vector<SmallModulus> > &coeff_modulus_options, 
        EncryptionParameters &destination)
    {
        if (budget_gap < 0)
        {
            throw std::invalid_argument("budget_gap cannot be negative");
        }
        if (noise_standard_deviation < 0)
        {
            throw invalid_argument("noise_standard_deviation can not be negative");
        }
        if (coeff_modulus_options.size() == 0)
        {
            throw invalid_argument("parameter_options must contain at least one entry");
        }
        if (operands.empty())
        {
            throw invalid_argument("operands cannot be empty");
        }

        int largest_bit_count = 0;
        int largest_coeff_count = 0;
        for (size_t i = 0; i < operands.size(); i++)
        {
            if (operands[i].comp_ == nullptr)
            {
                throw logic_error("no operation history to simulate");
            }
            int current_bit_count = get_significant_bit_count(operands[i].max_abs_value_);
            largest_bit_count = (current_bit_count > largest_bit_count) ? 
                current_bit_count : largest_bit_count;

            int current_coeff_count = operands[i].max_coeff_count_;
            largest_coeff_count = (current_coeff_count > largest_coeff_count) ? 
                current_coeff_count : largest_coeff_count;
        }

        // We restrict to plain moduli that are powers of two. Here largest_bit_count 
        // is the largest positive coefficient that we can expect to appear. Thus, we 
        // need one more bit.
        uint64_t new_plain_modulus;
        if (largest_bit_count >= SEAL_USER_MODULO_BIT_BOUND)
        {
            // The plain_modulus needed is too big
            return false;
        }
        new_plain_modulus = 1ULL << largest_bit_count;
        destination.set_plain_modulus(new_plain_modulus);

        bool found_good_parms = false;
        map<int, vector<SmallModulus> >::const_iterator iter = coeff_modulus_options.begin();
        while (iter != coeff_modulus_options.end() && !found_good_parms)
        {
            int dimension = iter->first;
            if (dimension < 512 || (dimension & (dimension - 1)) != 0)
            {
                throw invalid_argument("coeff_modulus_options keys invalid");
            }

            int coeff_bit_count = 0;
            for(auto mod : iter->second)
            {
                coeff_bit_count += mod.bit_count();
            }

            if (dimension > largest_coeff_count && 
                coeff_bit_count > destination.plain_modulus().bit_count())
            {
                // Set the polynomial
                destination.set_coeff_modulus(iter->second);
                BigPoly new_poly_modulus(dimension + 1, 1);
                new_poly_modulus.set_zero();
                new_poly_modulus[0] = 1;
                new_poly_modulus[dimension] = 1;
                destination.set_poly_modulus(new_poly_modulus);

                // The bound needed for GapSVP->search-LWE reduction
                //parms.noise_standard_deviation() = round(sqrt(dimension / (2 * 3.1415)) + 0.5);

                // Use constant (small) standard deviation.
                destination.set_noise_standard_deviation(noise_standard_deviation);

                found_good_parms = true;
                for (size_t i = 0; i < operands.size(); i++)
                {
                    // If one of the operands does not decrypt, set found_good_parms to false.
                    found_good_parms = operands[i].simulate(destination).decrypts(budget_gap) ? 
                        found_good_parms : false;
                }
            }

            // This dimension/coeff_modulus are to small. Move on to the next pair.
            iter++;
        }

        if (!found_good_parms)
        {
            destination = EncryptionParameters();
        }

        return found_good_parms;
    }
Example #7
0
/*
 * Runs the program in command shell mode, listening for commands until the user exits
 */
void runShell(){
	bool exit = false;
	while (!exit) {
		vector<string> args;
		cout << "==>" ;
		string line;
		cin.clear();

		//Get line and convert to vector
		getline(cin, line);
		istringstream input (line);
		string word;
		vector<string> list;
		while(input >> word){
			list.push_back(word);
			if (word == "exit" && list.size() == 1){
				exit = true;
			}
		}

		if(exit){
			//Check if background processes are running
			if( running.size() == 0)
				break;
			else{
			
			cout << "There are processes running, please wait before exiting\n";
			exit = false;
			}
		}else if (list.size() < 1){
			//Do nothing
		}else if(list[0] == "cd"){
			//Change directory

			if (chdir(list[1].c_str()) < 0){
				cerr << "Error changing directory\n";
			}
		}else if(list[0] == "jobs"){

			printJobs();
		}else {
			//copy args
			char *newargs[list.size() + 1];
			for(int i = 0; i < (int)list.size(); i++){
				newargs[i] = (char *)list[i].c_str();
			} 
			newargs[list.size()] = 0;

			//remove & if it is in the list
			bool back = false;
			if(newargs[list.size() -1][0] ==  '&'){
				newargs[list.size() -1 ] = 0;
				back = true;
			}
			int pid = runCommand(newargs);
			if(back){
				//Setup task as background task
				struct timeval astart;
				gettimeofday(&astart, NULL);
				process p = {pid, newargs[0], timevalToMs(astart), running.size()+1};
				running[pid] = p;
				cout << "[" << running.size() << "] " << pid << "\n";
			}else{
				//wait and get stats
				getStats(-1, pid);
			}
		}
		list.clear();

	}
}
Example #8
0
		Filter(string className){
			cerr<<className<<endl;
			filterManager.insert(make_pair(className,this));
			cerr<<filterManager.size()<<endl;
		}
Example #9
0
void generic_request_handler(struct evhttp_request *req, void *arg)
{
    struct evbuffer *returnbuffer = evbuffer_new();
	evhttp_add_header(req->output_headers, "Content-Type", "text/html; charset=UTF-8");
    evhttp_add_header(req->output_headers, "Server", "conn_test_server");
    evhttp_add_header(req->output_headers, "Connection", "close");
	
	evbuffer_add_printf(returnbuffer, "<html><head><title>conn_test_server</title>");

	evbuffer_add_printf(returnbuffer, "<meta http-equiv=\"refresh\" content=\"%d\"/>", 1);

	evbuffer_add_printf(returnbuffer, "</head><body>");

	evbuffer_add_printf(returnbuffer, "<font size=\"24px\">");
	evbuffer_add_printf(returnbuffer, "<table align=\"center\">");
	evbuffer_add_printf(returnbuffer, "<tr><td><font size=\"24px\">Connections:</font></td><td><strong><font color=\"blue\" size=\"24px\">%u</font></strong></td></tr>", (unsigned int)g_conns.size());
#ifndef WIN32
	evbuffer_add_printf(returnbuffer, "<tr><td><font size=\"24px\">Total Flow:</font></td><td><strong><font color=\"blue\" size=\"24px\">%lluB</font></strong></td></tr>", g_new_flow);
#else
	evbuffer_add_printf(returnbuffer, "<tr><td><font size=\"24px\">Total Flow:</font></td><td><strong><font color=\"blue\" size=\"24px\">%I64uB</font></strong></td></tr>", g_new_flow);
#endif
	evbuffer_add_printf(returnbuffer, "<tr><td><font size=\"24px\">Total Speed:</font></td><td><strong><font color=\"blue\" size=\"24px\">%f%s</font></strong></td></tr>", g_flow_speed, g_flow_speed_unit);
	evbuffer_add_printf(returnbuffer, "</table>");
	evbuffer_add_printf(returnbuffer, "</font>");
    evbuffer_add_printf(returnbuffer, "</body></html>");
    evhttp_send_reply(req, HTTP_OK, "Client", returnbuffer);
    evbuffer_free(returnbuffer);
    return;
}
Example #10
0
double AmovaCommand::runAMOVA(ofstream& AMOVAFile, map<string, vector<int> > groupSampleMap, double alpha) {
	try {
		map<string, vector<int> >::iterator it;

		int numGroups = groupSampleMap.size();
		int totalNumSamples = 0;

		for(it = groupSampleMap.begin();it!=groupSampleMap.end();it++){
			totalNumSamples += it->second.size();			
		}

		double ssTotalOrig = calcSSTotal(groupSampleMap);
		double ssWithinOrig = calcSSWithin(groupSampleMap);
		double ssAmongOrig = ssTotalOrig - ssWithinOrig;
		
		double counter = 0;
		for(int i=0;i<iters;i++){
			map<string, vector<int> > randomizedGroup = getRandomizedGroups(groupSampleMap);
			double ssWithinRand = calcSSWithin(randomizedGroup);
			if(ssWithinRand < ssWithinOrig){	counter++;	}
		}
		
		double pValue = (double)counter / (double) iters;
		string pString = "";
		if(pValue < 1/(double)iters){	pString = '<' + toString(1/(double)iters);	}
		else						{	pString = toString(pValue);					}
		
		
		//print anova table
		it = groupSampleMap.begin();
		AMOVAFile << it->first;
		m->mothurOut(it->first);
		it++;
		for(it;it!=groupSampleMap.end();it++){
			AMOVAFile << '-' << it->first;
			m->mothurOut('-' + it->first);
		}
		
		AMOVAFile << "\tAmong\tWithin\tTotal" << endl;
		m->mothurOut("\tAmong\tWithin\tTotal\n");
		
		AMOVAFile << "SS\t" << ssAmongOrig << '\t' << ssWithinOrig << '\t' << ssTotalOrig << endl;
		m->mothurOut("SS\t" + toString(ssAmongOrig) + '\t' + toString(ssWithinOrig) + '\t' + toString(ssTotalOrig) + '\n');
		
		int dfAmong = numGroups - 1;				double MSAmong = ssAmongOrig / (double) dfAmong;
		int dfWithin = totalNumSamples - numGroups;	double MSWithin = ssWithinOrig / (double) dfWithin;
		int dfTotal = totalNumSamples - 1;			double Fs = MSAmong / MSWithin;
		
		AMOVAFile << "df\t" << dfAmong << '\t' << dfWithin << '\t' << dfTotal << endl;
		m->mothurOut("df\t" + toString(dfAmong) + '\t' + toString(dfWithin) + '\t' + toString(dfTotal) + '\n');

		AMOVAFile << "MS\t" << MSAmong << '\t' << MSWithin << endl << endl;
		m->mothurOut("MS\t" + toString(MSAmong) + '\t' + toString(MSWithin) + "\n\n");

		AMOVAFile << "Fs:\t" << Fs << endl;
		m->mothurOut("Fs:\t" + toString(Fs) + '\n');
		
		AMOVAFile << "p-value: " << pString;
		m->mothurOut("p-value: " + pString);

		if(pValue < alpha){
			AMOVAFile << "*";
			m->mothurOut("*");
		}
		AMOVAFile << endl << endl;
		m->mothurOutEndLine();m->mothurOutEndLine();

		return pValue;
	}
	catch(exception& e) {
		m->errorOut(e, "AmovaCommand", "runAMOVA");
		exit(1);
	}
}
Example #11
0
//! 保存个人房屋内的物品信息
bool    CRsDupRgn::SaveDupRgnObj(const CGUID& ownerID, map<CGUID,CDBRgnGoods*>& goodsGroup, _ConnectionPtr& cn)
{

	if(cn == NULL)
	{
		AddLogText(CStringReading::LoadString(IDS_DBS_RSDUPRGN,STR_DBS_DUPRGN_CNPTRNULL));
		return false;
	}

	_RecordsetPtr rs;
	// 比物品个数多分配2048字节
	char *sql = new char[1024 * (goodsGroup.size()+2)];
	
	string iniName   = "phrgnobj";
	string tableName = "CSL_DUPRGN_GOODS";
	try
	{
		TESTHR(CreateRs(rs));

		char szGUID[128];
		ownerID.tostring(szGUID);

		sprintf(sql, "DELETE FROM CSL_DUPRGN_GOODS WHERE DupRgnGUID='%s'", szGUID);
		// 先删除该个人房屋的成员
		if(!ExecuteCn(sql, cn))
		{
			PrintErr(CStringReading::LoadString(IDS_DBS_RSDUPRGN,STR_DBS_DUPRGN_DELRGNOBJFAIL));
			return false;
		}

		// 清空sql语句
		memset(sql, 0, 1024 * (goodsGroup.size()+2));

		// 生成语句头
		strcpy(sql, "INSERT INTO CSL_DUPRGN_GOODS(");

		CDataEntityManager* pObjAttrDef = NULL;
		std::map<string, CDataEntityManager*>::iterator itr = GetGame()->GetDBEntityManager()->GetObjAttrDef().find(iniName);
		if(itr != GetGame()->GetDBEntityManager()->GetObjAttrDef().end())
			pObjAttrDef = itr->second;

		if(!pObjAttrDef) return false;

		//! 生成语句身
		CDataEntityManager::EntityPropertyMapItr attrItr = pObjAttrDef->GetEntityPropertyMap().begin();
		for (; attrItr != pObjAttrDef->GetEntityPropertyMap().end(); attrItr++)
		{
			if(attrItr->second->GetDBTableName() == tableName)
			{
				CWrapDataObject* wdo = attrItr->second->GetDataObject(0);
				if(wdo)
				{
					// 添加属性字段名
					strcat(sql, attrItr->second->GetEPName().c_str());
					strcat(sql, ",");
				}
			}
		}

		long sqlLen = strlen(sql);
		sql[sqlLen-1] = '\0';
		strcat(sql, ") select ");

		map<CGUID,CDBRgnGoods*>::iterator goodsItr = goodsGroup.begin();
		for(; goodsItr != goodsGroup.end(); goodsItr++)
		{	
			//! 生成语句身
			attrItr = pObjAttrDef->GetEntityPropertyMap().begin();
			for (; attrItr != pObjAttrDef->GetEntityPropertyMap().end(); attrItr++)
			{
				if(attrItr->second)
				{
					if(attrItr->second->GetDBTableName() == tableName)
					{
						// 添加属性字段值
						CEntityProperty* ep = (goodsItr->second)->GetDataEntityManager().GetEntityProperty(attrItr->second->GetEPName());
						if(ep)
						{
							if(ep->GetDBTableName() == tableName)
							{
								switch(ep->GetDataType())
								{
								case DATA_OBJECT_TIME:
									{
										char szTimeValue[2048];
										DWORD timeValue[6] = {0};
										ep->GetBufAttr(0, (void*)&timeValue[0], sizeof(DWORD)*6);
										sprintf(szTimeValue, "%d-%d-%d %d:%d:%d", timeValue[0], timeValue[1], timeValue[2],
											timeValue[3], timeValue[4], timeValue[5]);
										//rs->PutCollect((*epItr).c_str(), szTimeValue);
										strcat(sql, "'");
										strcat(sql, szTimeValue);
										strcat(sql, "',");
									}
									break;
								case  DATA_OBJECT_STRING:
									{
										//rs->PutCollect((*epItr).c_str(), );
										strcat(sql, "'");
										const char* pStr = ep->GetStringAttr(0);
										if(pStr)
											strcat(sql, pStr);
										else
											strcat(sql, "");
										strcat(sql, "',");
									}
									break;
								case DATA_OBJECT_BUFFER:
									{
										//SaveBufferField((*goodsItr), (*epItr).c_str(), rs);
									}
									break;
								case DATA_OBJECT_GUID:
									{
										CGUID tGUID;
										ep->GetGuidAttr(0, tGUID);
										char szGuid[128];
										tGUID.tostring(szGuid);
										//rs->PutCollect((*epItr).c_str(), szGuid);
										strcat(sql, "'");
										strcat(sql, szGuid);
										strcat(sql, "',");
									}
									break;
								case DATA_OBJECT_BOOL:
								case DATA_OBJECT_CHAR:
								case DATA_OBJECT_BYTE:
									{
										//rs->PutCollect((*epItr).c_str(), (BYTE)ep->GetLongAttr(0));
										char value[32];
										memset(value, 0, sizeof(value));
										itoa((BYTE)ep->GetLongAttr(0), value, 10);
										strcat(sql, value);
										strcat(sql, ",");
									}
									break;
								case DATA_OBJECT_SHORT:
								case DATA_OBJECT_WORD:
								case DATA_OBJECT_USHORT:
									{
										//rs->PutCollect((*epItr).c_str(), (WORD)ep->GetLongAttr(0));
										char value[32];
										memset(value, 0, sizeof(value));
										itoa((WORD)ep->GetLongAttr(0), value, 10);
										strcat(sql, value);
										strcat(sql, ",");
									}
									break;
								case DATA_OBJECT_FLOAT:
								case DATA_OBJECT_LONG:
								case DATA_OBJECT_ULONG:
								case DATA_OBJECT_DWORD:
									{
										//rs->PutCollect((*epItr).c_str(), (DWORD)ep->GetLongAttr(0));
										char value[32];
										memset(value, 0, sizeof(value));
										itoa((DWORD)ep->GetLongAttr(0), value, 10);
										strcat(sql, value);
										strcat(sql, ",");
									}
									break;
								}
							}
						}
					}
				}
			}

			sqlLen = strlen(sql);
			sql[sqlLen-1] = '\0';

			strcat(sql, " union all select ");
		}
		sqlLen = strlen(sql);
		sql[sqlLen-17] = '\0';

		TESTHR(ExecuteCn(sql, cn));
		SAFE_DELETE_ARRAY(sql);
		return true;
	}
	catch (_com_error &e)
	{
		SAFE_DELETE_ARRAY(sql);
		ReleaseRs(rs);
		PrintErr(CStringReading::LoadString(IDS_DBS_RSDUPRGN,STR_DBS_DUPRGN_SAVERGNGOODSFAIL), e);
		return false;
	}
	SAFE_DELETE_ARRAY(sql);
	return false;
}
bool Expression::Operate(const map<string, float>& mapOperandValue, float& Result)
{
	if(operands->GetKeyCount() > mapOperandValue.size() + constant_float.size())
		return false;
	stack<float> stackOperand;//操作数
	Result = 0;
	string variable;
	map<string, float>::const_iterator iter;
	vector<float> operand_values;
	for(unsigned int index = 0; index < m_vecPostfixExp.size(); index++)
	{
		if(m_vecPostfixExp[index].enum_item_type == OPERAND)
		{
			variable = operands->GetKey(*((uint32_t*)m_vecPostfixExp[index].item));
			iter = mapOperandValue.find(variable);
			if(iter == mapOperandValue.end())
			{
				iter = constant_float.find(variable);
				if(iter == constant_float.end())
				{
#ifdef DEBUG
					cout<<"[EXPRESSION ERROR] find operand's value failed [operand = "<<this<<","<<constant_float.size()<<","<<constant_int.size()<<", "<<variable<<"]"<<endl;
#endif
					return false;
				}
			}
#ifdef DEBUG
			cout<<"push operand:"<<iter->second<<endl;
#endif
			stackOperand.push(iter->second);
		}
		else
		{
			// 从栈中弹出需要的操作数个数
			OperatorType Oper = *(OperatorType*)(m_vecPostfixExp[index].item);
			map<OperatorType, OperatorParameter>::iterator iterOper = mapOperatorPriority.find(Oper);
			if(iterOper == mapOperatorPriority.end())
			{
#ifdef DEBUG
				cout<<"[EXPRESSION ERROR] "<<Oper<<": unknown operator."<<endl;
#endif
				return false;
			}
#ifdef DEBUG
			cout<<"Oper : "<<GetOperatorName(Oper)<<" need "<<iterOper->second.operands<<" operands."<<endl;
#endif

			// 栈中的操作数小于操作符所需的操作数
			if(stackOperand.size() < iterOper->second.operands)
			{
#ifdef DEBUG
				cout<<"[EXPRESSION ERROR] operator needs more operands than "<<stackOperand.size()<<endl;
#endif
				return false;
			}
			// 依次弹出所需的操作数,先弹出的操作数在最右边
			// 为了简化,本解析器暂时不处理三个及三个以上的操作数
			operand_values.clear();
#ifdef DEBUG
			cout<<"operate : "<<Oper<<" on:";
#endif
			while(stackOperand.size() > 0 && operand_values.size() < iterOper->second.operands)
			{
#ifdef DEBUG
				cout<<stackOperand.top()<<",";
#endif
				operand_values.push_back(stackOperand.top());
				stackOperand.pop();
			}
			float result = DoOperating(Oper, operand_values);
#ifdef DEBUG
			cout<<"result = "<<result<<endl;
#endif
			stackOperand.push(result);
		}
	}

	// 正确运算结果是最后留下在栈中的那个值
	if(stackOperand.size() != 1)
	{
#ifdef DEBUG
		cout<<"[EXPRESSION ERROR] En? It looks like something wrong happened."<<endl;
#endif
		return false;
	}

	Result = stackOperand.top();

	return true;
}
// 说明:输入表达式中各个操作数的值,计算结果
bool Expression::Operate(const map<string, int32_t>& mapOperandValue, int32_t& Result)
{
	if(operands->GetKeyCount() > mapOperandValue.size() + constant_int.size())
		return false;
	stack<uint32_t> stackOperand;//操作数栈
	Result = 0;
	std::string variable;
	map<string, int32_t>::const_iterator iter;
	vector<int32_t> operand_values;
	for(unsigned int index = 0; index < m_vecPostfixExp.size(); index++)
	{
		if(m_vecPostfixExp[index].enum_item_type == OPERAND)
		{
			variable = operands->GetKey(*((uint32_t*)m_vecPostfixExp[index].item));
			iter = mapOperandValue.find(variable);
			if(iter == mapOperandValue.end())
			{
				iter = constant_int.find(variable);
				if(iter == constant_int.end())
					return false;
			}
#ifdef DEBUG
			cout<<"push operand:"<<iter->second<<endl;
#endif
			stackOperand.push(iter->second);
		}
		else
		{
			// 从栈中弹出需要的操作数个数
			OperatorType Oper = *(OperatorType*)(m_vecPostfixExp[index].item);
			map<OperatorType, OperatorParameter>::iterator iterOper = mapOperatorPriority.find(Oper);
			if(iterOper == mapOperatorPriority.end())
				return false;

			// 栈中的操作数小于操作符所需的操作数
			if(stackOperand.size() < iterOper->second.operands)
				return false;
			// 依次弹出所需的操作数,先弹出的操作数在最右边
			// 为了简化,本解析器暂时不处理三个及三个以上的操作数
			operand_values.clear();
#ifdef DEBUG
			cout<<"operate : "<<Oper<<" on:";
#endif
			while(stackOperand.size() > 0 && operand_values.size() < iterOper->second.operands)
			{
#ifdef DEBUG
				cout<<stackOperand.top()<<",";
#endif
				operand_values.push_back(stackOperand.top());
				stackOperand.pop();
			}
#ifdef DEBUG
			cout<<endl;
#endif
			uint32_t result = DoOperating(Oper, operand_values);
#ifdef DEBUG
			cout<<"result = "<<result<<endl;
#endif
			stackOperand.push(result);
		}
	}

	// 正确运算结果是最后留下在栈中的那个值
	if(stackOperand.size() != 1)
		return false;

	Result = stackOperand.top();
	return true;
}
/////////////////////////////////////////////////
// 说明:初始化操作符优先级
void InitializePriority()
{
	if(mapOperatorPriority.size() > 0)
	  return;
	OperatorParameter operator_parameter;
	operator_parameter.priority = 5;
	operator_parameter.operands = 0;
	operator_parameter.type = 8;
	mapOperatorPriority[LEFT_BRACKET] = operator_parameter;
	//mapOperatorPriority[LEFT_BRACKET] = pair<uint32_t, uint32_t>(5, 0);
	mapOperatorName["("] = LEFT_BRACKET;
	mapOperatorPriority[RIGHT_BRACKET] = operator_parameter;
	mapOperatorName[")"] = RIGHT_BRACKET;
	// 负号不保存名字
	operator_parameter.priority = 6;
	operator_parameter.operands = 1;
	operator_parameter.type = 1;
	mapOperatorPriority[NEGATIVE] = operator_parameter;
	//mapOperatorPriority[NEGATIVE] = pair<uint32_t, uint32_t>(6,1);

	// 优先级相同的在运算时按照出现的先后顺序计算
	mapOperatorName["*"] = MUTIPLY;
	operator_parameter.priority = 7;
	operator_parameter.operands = 2;
	operator_parameter.type = 1;
	mapOperatorPriority[MUTIPLY] = operator_parameter;
	//mapOperatorPriority[MUTIPLY] = pair<uint32_t, uint32_t>(7, 2);
	mapOperatorName["/"] = DEVIDE;
	mapOperatorPriority[DEVIDE] = operator_parameter;
	//mapOperatorPriority[DEVIDE] = pair<uint32_t, uint32_t>(7, 2);
	mapOperatorName["%"] = MODE;
	mapOperatorPriority[MODE] = operator_parameter;
	//mapOperatorPriority[MODE] = pair<uint32_t, uint32_t>(7, 2);

	mapOperatorName["+"] = PLUS;
	operator_parameter.priority = 8;
	operator_parameter.operands = 2;
	operator_parameter.type = 1;
	mapOperatorPriority[PLUS] = operator_parameter;
	//mapOperatorPriority[PLUS] = pair<uint32_t, uint32_t>(8, 2);
	mapOperatorName["-"] = MINUS;
	mapOperatorPriority[MINUS] = operator_parameter;
	//mapOperatorPriority[MINUS] = pair<uint32_t, uint32_t>(8, 2);

	mapOperatorName["<"] = LESS_THAN;
	operator_parameter.priority = 9;
	operator_parameter.operands = 2;
	operator_parameter.type = 4;
	mapOperatorPriority[LESS_THAN] = operator_parameter;
	//mapOperatorPriority[LESS_THAN] = pair<uint32_t, uint32_t>(9, 2);
	mapOperatorName[">"] = MORE_THAN;
	mapOperatorPriority[MORE_THAN] = operator_parameter;
	//mapOperatorPriority[MORE_THAN] = pair<uint32_t, uint32_t>(9, 2);
	mapOperatorName["<="] = LESS_EQUAL;
	mapOperatorPriority[LESS_EQUAL] = operator_parameter;
	//mapOperatorPriority[LESS_EQUAL] = pair<uint32_t, uint32_t>(9, 2);
	mapOperatorName[">="] = MORE_EQUAL;
	mapOperatorPriority[MORE_EQUAL] = operator_parameter;
	//mapOperatorPriority[MORE_EQUAL] = pair<uint32_t, uint32_t>(9, 2);

	mapOperatorName["=="] = EQUAL_TO;
	operator_parameter.priority = 10;
	operator_parameter.operands = 2;
	operator_parameter.type = 4;
	mapOperatorPriority[EQUAL_TO] = operator_parameter;
	//mapOperatorPriority[EQUAL_TO] = pair<uint32_t, uint32_t>(10, 2);
	mapOperatorName["!="] = NOT_EQUAL;
	mapOperatorPriority[NOT_EQUAL] = operator_parameter;
	//mapOperatorPriority[NOT_EQUAL] = pair<uint32_t, uint32_t>(10, 2);

	mapOperatorName["^"] = XOR;
	operator_parameter.priority = 11;
	operator_parameter.operands = 2;
	operator_parameter.type = 2;
	mapOperatorPriority[XOR] = operator_parameter;
	//mapOperatorPriority[XOR] = pair<uint32_t, uint32_t>(11, 2);
	mapOperatorName["&&"] = AND;
	operator_parameter.priority = 12;
	mapOperatorPriority[AND] = operator_parameter;
	//mapOperatorPriority[AND] = pair<uint32_t, uint32_t>(12, 2);
	mapOperatorName["||"] = OR;
	operator_parameter.priority = 13;
	mapOperatorPriority[OR] = operator_parameter;
	//mapOperatorPriority[OR] = pair<uint32_t, uint32_t>(13, 2);
}
Example #15
0
void miningTemplate_02(RuleNode* initRule, vector<Label*> &previousLabels) 
{
	int i,j,k;
	map<string,int>::iterator it;
	map<string,int>::iterator it1;
	map<string,int> possibleViews;
	map<string,int> allNextEvents;
	for(i=0;i<previousLabels.size();i++)
	{
		if(previousLabels[i]->eventNum < traceSet[previousLabels[i]->traceNum].size()-2)
		{
			//stored nextViewName as hashkey
			string nextViewName=traceSet[previousLabels[i]->traceNum][previousLabels[i]->eventNum+1]->name;
			
			if(possibleViews.find(nextViewName)!=possibleViews.end())
			{
				possibleViews[nextViewName]++;
			}
			else
			{
				possibleViews[nextViewName]=1;
			}
			cout<<possibleViews[nextViewName]<<"view"<<endl;
		}
			// ABABCDE
			//						A			C			E
			//(0,0)(0,1)			1			1			1
			//(0,2)(0,3)			0			1			1

			//create a table and fill zero into table
		vector <vector<int>> table;
		table.resize(possibleViews.size());
		for(i=0;i<table.size();i++)
		{ 
			table[i].resize(allStateEvents.size());
			for(j=0;j<allStateEvents.size();j++)
			{
				table[i][j]=0;
			}
		}
 
		for(it=possibleViews.begin();it!=possibleViews.end();it++)			
		{
			for(j=0;j<allStateEvents.size();j++)
			{
				for(k=0;k<traceSet[j].size();k++)
				{
					if(traceSet[j][k]->name==it1->first)
					{
						table[j][k]=1;
					}
				}
			}
		}

		//calculate the number of StateEvent
		int count=0;
		for(i=0;i<possibleViews.size();i++)	
		{
	
			for(j=0;j<allStateEvents.size();j++)
			{
				if(table[i][j]=1)
				{
					count++;
				}
			}
		}
		//calculate confidence and recursive
		map<string,int>::iterator it;
		for(it=allNextEvents.begin();it!=allNextEvents.end();++it)
		{
			double a=it->second;
			double b=previousLabels.size();
			if( a/b >= confidenceThreshold)
			{
				//seperate the combinedName
				for(i=0;i < it->first.size();i++)
				{
					if(it->first[i]=='+')
					{
						break;
					}
				}
				string childViewEventName=it->first.substr(0,i);
				string childStateEventName=it->first.substr(i+1,it->first.size()-i-1);
				//update labels
				vector<Label*> nextLabels;
				for(i=0;i<previousLabels.size();i++)
				{
					if(previousLabels[i]->eventNum < traceSet[previousLabels[i]->traceNum].size()-2)
					{
						if(traceSet[previousLabels[i]->traceNum][previousLabels[i]->eventNum+1]->name==childViewEventName && 
						traceSet[previousLabels[i]->traceNum][previousLabels[i]->eventNum+2]->name==childStateEventName)
						{
							Label* newLabel=new Label(previousLabels[i]->traceNum,previousLabels[i]->eventNum+2);
							nextLabels.push_back(newLabel);
						}					
					}
				}
				//add to children 
				RuleNode* newStateRuleNode=new RuleNode;
				newStateRuleNode->name=childStateEventName;
				RuleNode* newViewRuleNode=new RuleNode;
				newViewRuleNode->name=childViewEventName;
				initRule->children.push_back(newViewRuleNode);
				newViewRuleNode->children.push_back(newStateRuleNode);
				//recursive
				miningTemplate_02(newStateRuleNode,nextLabels);
			}
		}
	}	
}
Example #16
0
/**
 * This function will be called by libevent when there is a connection
 * ready to be accepted.
 */
static void on_accept(evutil_socket_t fd, short ev, void *arg)
{
	int client_fd;
	struct sockaddr_in client_addr;
	socklen_t client_len = (socklen_t)sizeof(client_addr);
	static int maxfd = 80000;
	
	client_fd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
	if (client_fd == -1)
    {
        fprintf(stderr, "accept failed. errno:%d, info:%s\n", 
            EVUTIL_SOCKET_ERROR(), get_error_string(EVUTIL_SOCKET_ERROR()));
		return;
	}

	if(client_fd > maxfd + 1000)
    {
		maxfd = client_fd;
		printf("maxfd %d\n", maxfd );
	}

    if (g_tcp_send_buf_len >= 0)
    {
        setsockopt(client_fd, SOL_SOCKET, SO_SNDBUF, (const char*)&g_tcp_send_buf_len, sizeof(int));
    }
	
	if (g_no_delay)
	{
		int flag;
		setsockopt(client_fd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
	}
	
//	setsockopt(client_fd, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (char *)&fd, sizeof(fd));
	
	/* Set the client socket to non-blocking mode. */
	if (evutil_make_socket_nonblocking(client_fd) < 0)
    {
		fprintf(stderr, "failed to set client socket non-blocking.\n");
    }

    server_conn *nlc = new server_conn(client_fd);
   	event_set(nlc->get_ev_read(), client_fd, EV_READ, on_read, nlc);
  	event_set(nlc->get_ev_write(), client_fd, EV_WRITE | EV_PERSIST, on_write, nlc);
    nlc->set_max_send_len(g_send_buf_len);
    if (!g_same)
    {
        nlc->set_mask((unsigned int)genrand64_int64());
    }
    nlc->set_block(g_block);
    nlc->set_check(g_check);
	nlc->set_alter(g_alter);
    nlc->set_debug_level(g_verbose);

 	printf("accepted connection(%d) from %s:%d.\n", client_fd, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

    g_conns.insert(pair<int, server_conn *>(client_fd, nlc));
    printf("current connected sockets number:%u\n", (unsigned int)g_conns.size());

    if(event_add(nlc->get_ev_read(), NULL) != 0)
    {
        nlc->set_error_no(NL_CONN_ERROR_EV_READ);
        close_client(client_fd);
        fprintf(stderr, "event_add failed(%d) from %s:%d.\n", client_fd, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
 	}
}
Example #17
0
bool isLinkListLoop(Loop * pLoop, map<PHINode *, set<Value *> > & LinkListHeaderMapping )
{
	BasicBlock * pHeader = pLoop->getHeader();

	vector<PHINode *> vecToDo;

	for(BasicBlock::iterator II = pHeader->begin(); II != pHeader->end(); II ++ )
	{
		if(isa<PHINode>(II))
		{
			if(PointerType * pPointerType = dyn_cast<PointerType>(II->getType()))
			{
				if(isa<StructType>(pPointerType->getElementType()))
				{
					vecToDo.push_back(cast<PHINode>(II));
				}
			}
		}
		else
		{
			break;
		}
	}


	if(vecToDo.size() == 0)
	{
		return false;
	}

	vector<PHINode *>::iterator itVecPhiBegin = vecToDo.begin();
	vector<PHINode *>::iterator itVecPhiEnd   = vecToDo.end();


	for(; itVecPhiBegin != itVecPhiEnd; itVecPhiBegin ++ )
	{
		PHINode * pPHI = *itVecPhiBegin;

		bool bFlag = true;

		for(unsigned i = 0; i < pPHI->getNumIncomingValues(); i ++ )
		{
			if(pLoop->contains(pPHI->getIncomingBlock(i)))
			{
				if(Instruction * pInst = dyn_cast<Instruction>(pPHI->getIncomingValue(i)))
				{
					if(!isReachableThroughLinkListDereference(pPHI, pInst, pLoop))
					{
						bFlag = false;
						break;
					}
				}
				else
				{
					bFlag = false;
					break;
				}
			}
		}

		if(bFlag)
		{
			for(unsigned i = 0; i < pPHI->getNumIncomingValues(); i ++ )
			{
				if(!pLoop->contains(pPHI->getIncomingBlock(i)))
				{
					LinkListHeaderMapping[pPHI].insert(pPHI->getIncomingValue(i));
				}
			}
		}
	}


	if(LinkListHeaderMapping.size() > 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}
Example #18
0
std::vector<std::string> ScriptSystem::load() {

    std::vector<std::string> filenames;

    static const string types[] = {
        "config", "global", "extensions",
        "classes", "states", "ui"
    };
    for (unsigned int i = 0; i < sizeof(types) / sizeof(types[0]); i++) {

        std::vector<std::string> gathered = chi::System::gatherFiles(
                                                System::resourceLocation() + "/script/" + types[i],
                                                "(.*\\.js|.*\\.coffee)"
                                            );

        for (unsigned int j = 0; j < gathered.size(); j++) {
            filenames.push_back(gathered[j]);
        }
    }

    sort(filenames.begin(), filenames.end());

    HandleScope scope;

    for (unsigned int i = 0; i < filenames.size(); i++) {

        Script *script = Script::factory->create();
        scripts[filenames[i]] = script->compileFile(filenames[i]);
    }

    std::vector<std::string> loadedFilenames;

    while (scripts.size() > 0) {

        unsigned int size = scripts.size();

        vector<string>::iterator i = filenames.begin();
        while (i != filenames.end()) {

            try {
                scripts[*i]->run();

                loadedFilenames.push_back(*i);

                delete scripts[*i];

                scripts.erase(*i);
                i = filenames.erase(i);
            }
            catch (std::exception &e) {

                ++i;
            }
        }

        if (size == scripts.size()) {

            std::string text;

            map<string, Script *>::iterator i = scripts.begin();
            while (i != scripts.end()) {

                try {
                    (i->second)->run();
                }
                catch (std::exception &e) {
                    text += e.what();
                }

                delete i->second;
                scripts.erase(i++);
            }

            throw chi::Exception(text);
        }
    }

    return loadedFilenames;
}
Example #19
0
//Main program entry point
int main(int argc, char** argv)
{
	g_bProgressOverwrite = false;
	g_iNumThreads = 0;
	g_iCompressAmount = Z_DEFAULT_COMPRESSION;
	DWORD iTicks = GetTickCount();

	vfs.Prepare();
		
	//read in the resource names to pack
	initResMap();
	initSoundManifest();
	parseCmdLine(argc, argv);
	
	if(argc < 2)
	{
		cout << "Usage: liCompress [pakfile1] [pakfile2] ... [pakfileN]" << endl;
		return 0;
	}
	
	for(int iArg = 1; iArg < argc; iArg++)
	{
		if(argv[iArg][0] == '-')	//Skip over commandline switches
			continue;
		
		list<wstring> lFilenames;	//Files in this pakfile that we're going to compress
		wstring sArg = s2ws(argv[iArg]);
		size_t pos = sArg.find(TEXT(".filelist.txt"));
		if(pos != wstring::npos)
			sArg.erase(pos, wstring::npos);	//Erase a .filelist.pak extension if there is one
		cout << endl << "Packing resource blob file " << ws2s(sArg) << endl;
		
		//Determine what files to pack into this .pak file
		wstring sInfilename = sArg;
		sInfilename += TEXT(".filelist.txt");
		ifstream infile(ws2s(sInfilename).c_str());
		if(infile.fail())
		{
			cout << "Cannot open " << ws2s(sInfilename) << " to pack " << ws2s(sArg) << " Skipping..." << endl;
			continue;
		}
		
		while(!infile.fail() && !infile.eof())	//Pull in all the lines out of this file
		{
			string ss;
			getline(infile, ss);
			wstring s = s2ws(ttvfs::FixSlashes(ss));
			if(!s.length() || s == TEXT(""))
				continue;	//Ignore blank lines
			lFilenames.push_back(s);	//Add this to our list of files to package
		}
		
		threadedCompress(lFilenames);	//Compress everything
		
		//Ok, now we have all the compressed files in RAM. Stick them in the .pak file and call it a day
		if(g_pakHelping.size() != lFilenames.size())	//These should be the same
		{
			cout << "Error: size of file list: " << g_pakHelping.size() << " differs from size of files to pak: " << lFilenames.size() << endl;
			continue;
		}
		
		//Create a mini residmap.dat file and stick it into g_pakHelping to compress if we need to
		//See what IDs are known and unknown
		map<wstring, u32> mResIDs;
		map<u32, wstring> mUnknownIDs;
		for(list<wstring>::iterator i = lFilenames.begin(); i != lFilenames.end(); i++)
		{
			u32 id = getKnownResID(*i);
			if(!id)	//The ID mapping is unknown
			{
				id = hash(*i);
				mUnknownIDs[id] = toBackslashes(*i);	//Make sure we use backslashes inside a residmap.dat
			}
			mResIDs[*i] = id;
		}
		
		//If there are any unknown mappings, make our residmap.dat
		if(mUnknownIDs.size())
		{
			lFilenames.push_front(TEXT(RESIDMAP_NAME));	//Add this to the front, so it'll decompress first so we'll have all the filenames
			mResIDs[TEXT(RESIDMAP_NAME)] = RESIDMAP_ID;	//Add this to the IDs we'll compress
			createMiniResidMap(&mUnknownIDs);	//And create the file in memory
		}
		
		//Open our output pakfile for writing
		FILE* f = _wfopen(sArg.c_str(), TEXT("wb"));
		if(f == NULL)
		{
			cout << "Unable to open file " << ws2s(sArg) << " for writing. Skipping..." << endl;
			continue;
		}
		
		//Add the header
		blobHeader bh;
		bh.pakVersion = 0x01;
		bh.numItems = lFilenames.size();
		
		fwrite(&bh, 1, sizeof(blobHeader), f);
		
		//Get the starting file pos for where we (should) be writing objects to
		size_t offsetPos = sizeof(blobHeader) + (lFilenames.size() * sizeof(resourceHeader));	
		
		//Add the table of contents
		cout << "\rAdding table of contents...                " << endl;
		for(list<wstring>::iterator i = lFilenames.begin(); i != lFilenames.end(); i++)
		{
			resourceHeader rH;
			rH.id = mResIDs[*i];
			rH.flags = 0x01;
			
			rH.offset = offsetPos;	//Offset
			rH.size = g_pakHelping[*i].dataSz;
			if(g_pakHelping[*i].bCompressed)
				rH.size += sizeof(compressedHeader);	//Compressed files have a compression header also
			else
				rH.flags = 0x00;	//Set the flags to uncompressed
			
			fwrite(&rH, 1, sizeof(resourceHeader), f);	//Write this to the file
			
			offsetPos += rH.size;	//Add this size to our running tally of where we are
		}
		
		//Add actual resource data
		cout << "Adding compressed files..." << endl;
		for(list<wstring>::iterator i = lFilenames.begin(); i != lFilenames.end(); i++)
		{
			pakHelper pH = g_pakHelping[*i];
			
			//Write the compressed header only if compressed
			if(pH.bCompressed)
				fwrite(&(pH.cH), 1, sizeof(compressedHeader), f);
			
			fwrite(pH.data, 1, pH.dataSz, f);	//One pass to write this file. Simple enough.
			//Don't free the memory here, in case there's more than one .pak file with this data in it.
		}
		fclose(f);	//Done packing this .pak file
		
		//Clear memory
		for(map<wstring, pakHelper>::iterator i = g_pakHelping.begin(); i != g_pakHelping.end(); i++)
			free(i->second.data);
		g_pakHelping.clear();
	}
	
	cout << "Done." << endl;
	
	iTicks = GetTickCount() - iTicks;
	float iSeconds = (float)iTicks / 1000.0;	//Get seconds elapsed
	int iMinutes = iSeconds / 60;
	iSeconds -= iMinutes * 60;
	
	cout << "Time elapsed: " << iMinutes << " min, " << iSeconds << " sec" << endl;
	
	return 0;
}
Example #20
0
int main(int argc, char* argv[])
{
	uPort = GetPrivateProfileInt( "Server", "Port", 8080, ".\\cli.ini" );
	DWORD dwSize = 255;
	GetPrivateProfileString( "Server", "IP", "127.0.0.1", strIP, dwSize, ".\\cli.ini" );
	setvbuf( stdout, (char*)NULL, _IONBF, 0 );     //added
	Socket::SocketInit();
	//	Client( NULL );
	DWORD dwThreadID;
	int i = 1;
	int nThreadCount = 0;
	char sCount[5];
	sCount[0]= getchar();
	sCount[1]= getchar();
	sCount[2]= getchar();
	getchar();
	sCount[3]= 0;
	nThreadCount = atoi( sCount );
	//	nThreadCount = 999;
	printf( "创建%d个client 按任意键开始\n", nThreadCount );
	for ( i = 1; i <= nThreadCount; i++ ){
		HANDLE hThread = CreateThread( 
			NULL, 0, 
			(LPTHREAD_START_ROUTINE)Client,
			(LPVOID)NULL, 0, &dwThreadID );
		if ( NULL == hThread )
		{
			printf( "create client(%d) error\n", i );
		}
		if ( 0 == i % 200 ) 
		{
			printf( "create%d\n", i );
			//			getchar();
		}
	}
	char c[100];
	int nPos;
	THREAD_CONTROL* pThead;
	map<DWORD, THREAD_CONTROL*>::iterator it;
	int nCount;
	while ( 1 ){
		c[0] = getchar();
		c[1] = getchar();
		c[2] = getchar();
		c[3] = getchar();
		c[3] = 0;
		nPos = atoi( c );
		nCount = g_activeThread.size();
		if ( nPos > nCount )
		{
			printf( "创建线程%d/%d\n", nPos, nCount );
			HANDLE hThread = CreateThread( 
				NULL, 0, 
				(LPTHREAD_START_ROUTINE)Client,
				(LPVOID)NULL, 0, &dwThreadID );
		}
		else printf( "检查线程%d/%d\n", nPos, nCount );
		tm *last = localtime(&g_lastdata);
		char stime[256];
		strftime( stime, 256, "%Y-%m-%d %H:%M:%S", last );
		printf( "last data:%s\n", stime );
		Sleep( 1000 );
		it = g_activeThread.begin();
		for ( i = 1; it != g_activeThread.end(); it++, i++ )
		{
			pThead = it->second;
			if ( i == nPos ) pThead->bCheck = true;
			else pThead->bCheck = false;
		}
		
		Sleep( 1000 );
	}
	
	return 0;
}
Example #21
0
mainClass(int luminosity=5000){ // luminosity is in /pb unit



  cutname[0]="nocut";cutname[1]="Njet_4";cutname[2]="ht_500" ;cutname[3]="mht_200";
  cutname[4]="delphi";cutname[5]="iso";
  cutname[6]="CSVM_0";
  cutname[7]="CSVM_1";
  cutname[8]="CSVM_2";
  cutname[9]="CSVM_3";

  WJtype[0]="EventsWith_1RecoMuon_0RecoElectron";
  TTbartype[0]="EventsWith_1RecoMuon_0RecoElectron";



// .....................................................................................................................................................//
// WJ Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> WJ_xs_vec;

  WJ_xs_vec.push_back(1817.0); // HT 100-200
  WJ_xs_vec.push_back(471.6);  // HT 200-400
  WJ_xs_vec.push_back(55.61);  // HT 400-600
  WJ_xs_vec.push_back(18.81);  // HT 600-Inf

  const int wjnHT = (int) WJ_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"../Results/results_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"../Results/results_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"../Results/results_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*WJ_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,WJ_xs_vec[i-1]);

    WJ_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "WJ normalization scale factor determination done \n " << std::endl;




//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"HadTauEstimation_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"HadTauEstimation_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    WJ_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<wjnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) WJ_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(WJ_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);

        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("WJ main histograms stacked \n ");






// .....................................................................................................................................................//
// TTbar Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> TTbar_xs_vec;

  TTbar_xs_vec.push_back(806.1); // 

  const int ttbarnHT = (int) TTbar_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*TTbar_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,TTbar_xs_vec[i-1]);

    TTbar_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "TTbar normalization scale factor determination done \n " << std::endl;
  



//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    TTbar_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=TTbartype.begin(); itt!=TTbartype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<ttbarnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", TTbartype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) TTbar_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(TTbar_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("TTbar main histograms stacked \n ");



// ..................................................................................................................................................... //
// Stack main histograms from TTbar and WJet
// ..................................................................................................................................................... //

  // There are two contributors 1-TTbar and 2-WJ
  int NSamples=2;

  // A vector that contains all the samples
  vector<TFile*> sample_inputfilevec;

  THStack * tempstack2 = new THStack("stack","Binned Sample Stack");

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=NSamples ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
    else{cout << " Error!! There are only 2 contributors! " << endl;}
    sample_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  delete tempstack;
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();


      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<NSamples ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          tempstack2 = (THStack *) sample_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist = (TH1D*)tempstack2->GetStack()->Last(); 
          
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("All samples main histograms stacked \n ");






} // End of the constructor 
Example #22
0
 int get_count()
 {
   return hashmap.size();
 }
  PepNovoInfile pepnovo_infile2;
  pepnovo_infile2 = pepnovo_infile1;
  TEST_EQUAL(( pepnovo_infile1 == pepnovo_infile2 ), true)
END_SECTION

START_SECTION((void setModifications(const StringList &fixed_mods, const StringList &variable_mods)))
	NOT_TESTABLE // will be tested in next section
END_SECTION

START_SECTION(void getModifications(std::map<String,String>& modification_key_map) const)
	PepNovoInfile pepnovo_infile;
	pepnovo_infile.setModifications(fix_mods, var_mods);
	pepnovo_infile.getModifications(keys_and_mods);

	//TEST_EQUAL(keys_and_mods.size(), 4)
  TEST_EQUAL(keys_and_mods.size(), 3)


  if(keys_and_mods.size()==4)
  {
    map<String, String>::iterator mod_it=keys_and_mods.begin();
    TEST_EQUAL((mod_it++)->first, "$+43")
    TEST_EQUAL((mod_it++)->first, "C+80")
    TEST_EQUAL((mod_it++)->first, "D+80")
//    TEST_EQUAL((mod_it)->first, "^+229")
  }
END_SECTION

START_SECTION(void store(const String& filename))
  PepNovoInfile pepnovo_infile;
  pepnovo_infile.setModifications(fix_mods, var_mods);
/** Generate output workspace
  */
TableWorkspace_sptr LoadFullprofResolution::genTableWorkspace(
    map<int, map<string, double>> bankparammap) {
  g_log.notice() << "Start to generate table workspace ...."
                 << ".\n";

  // Retrieve some information
  size_t numbanks = bankparammap.size();
  if (numbanks == 0)
    throw runtime_error("Unable to generate a table from an empty map!");

  map<int, map<string, double>>::iterator bankmapiter = bankparammap.begin();
  size_t numparams = bankmapiter->second.size();

  // vector of all parameter name
  vector<string> vec_parname;
  vector<int> vec_bankids;

  map<string, double>::iterator parmapiter;
  for (parmapiter = bankmapiter->second.begin();
       parmapiter != bankmapiter->second.end(); ++parmapiter) {
    string parname = parmapiter->first;
    vec_parname.push_back(parname);
  }

  for (bankmapiter = bankparammap.begin(); bankmapiter != bankparammap.end();
       ++bankmapiter) {
    int bankid = bankmapiter->first;
    vec_bankids.push_back(bankid);
  }

  g_log.debug() << "[DBx240] Number of imported parameters is " << numparams
                << ", Number of banks = " << vec_bankids.size() << "."
                << "\n";

  // Create TableWorkspace
  TableWorkspace_sptr tablews(new TableWorkspace());

  // set columns :
  // Any 2 columns cannot have the same name.
  tablews->addColumn("str", "Name");
  for (size_t i = 0; i < numbanks; ++i) {
    stringstream colnamess;
    int bankid = vec_bankids[i];
    colnamess << "Value_" << bankid;
    tablews->addColumn("double", colnamess.str());
  }

  g_log.debug() << "Number of column = " << tablews->columnCount() << ".\n";

  // add BANK ID row
  TableRow newrow = tablews->appendRow();
  newrow << "BANK";
  for (size_t i = 0; i < numbanks; ++i)
    newrow << static_cast<double>(vec_bankids[i]);

  g_log.debug() << "Number of row now = " << tablews->rowCount() << ".\n";

  // add profile parameter rows
  for (size_t i = 0; i < numparams; ++i) {
    TableRow newrow = tablews->appendRow();

    string parname = vec_parname[i];
    newrow << parname;

    for (size_t j = 0; j < numbanks; ++j) {
      int bankid = vec_bankids[j];

      // Locate map of bank 'bankid'
      map<int, map<string, double>>::iterator bpmapiter;
      bpmapiter = bankparammap.find(bankid);
      if (bpmapiter == bankparammap.end()) {
        throw runtime_error("Bank cannot be found in map.");
      }

      // Locate parameter
      map<string, double>::iterator parmapiter;
      parmapiter = bpmapiter->second.find(parname);
      if (parmapiter == bpmapiter->second.end()) {
        throw runtime_error("Parameter cannot be found in a bank's map.");
      } else {
        double pvalue = parmapiter->second;
        newrow << pvalue;
      }

    } // END(j)
  }   // END(i)

  return tablews;
}
Example #25
0
void handle_list_message(struct sockaddr_in sock)
{

	//check whether the user is in usernames
	//if yes, send a list of channels
	//if not send an error message to the user



	string ip = inet_ntoa(sock.sin_addr);

	int port = sock.sin_port;

 	char port_str[6];
 	sprintf(port_str, "%d", port);
	string key = ip + "." +port_str;


	//check whether key is in rev_usernames
	map <string,string> :: iterator iter;

    cout << this_Server << ":" << this_Port << " " << ip << ":" << port
    << " recv Request List " << endl;

	iter = rev_usernames.find(key);
	if (iter == rev_usernames.end() )
	{
		//ip+port not recognized - send an error message
		send_error_message(sock, "Not logged in ");
	}
	else
	{
		string username = rev_usernames[key];
		int size = channels.size();
		//cout << "size: " << size << endl;

		active_usernames[username] = 1;

		ssize_t bytes;
		void *send_data;
		size_t len;


		//struct text_list temp;
		struct text_list *send_msg = (struct text_list*)malloc(sizeof (struct text_list) + (size * sizeof(struct channel_info)));


		send_msg->txt_type = TXT_LIST;

		send_msg->txt_nchannels = size;


		map<string,channel_type>::iterator channel_iter;



		//struct channel_info current_channels[size];
		//send_msg.txt_channels = new struct channel_info[size];
		int pos = 0;

		for(channel_iter = channels.begin(); channel_iter != channels.end(); channel_iter++)
		{
			string current_channel = channel_iter->first;
			const char* str = current_channel.c_str();
			//strcpy(current_channels[pos].ch_channel, str);
			//cout << "channel " << str <<endl;
			strcpy(((send_msg->txt_channels)+pos)->ch_channel, str);
			//strcpy(((send_msg->txt_channels)+pos)->ch_channel, "hello");
			//cout << ((send_msg->txt_channels)+pos)->ch_channel << endl;

			pos++;

		}



		//send_msg.txt_channels =
		//send_msg.txt_channels = current_channels;
		send_data = send_msg;
		len = sizeof (struct text_list) + (size * sizeof(struct channel_info));

					//cout << username <<endl;
		struct sockaddr_in send_sock = sock;


		//bytes = sendto(s, send_data, len, 0, (struct sockaddr*)&send_sock, fromlen);
		bytes = sendto(s, send_data, len, 0, (struct sockaddr*)&send_sock, sizeof send_sock);

		if (bytes < 0)
		{
			perror("Message failed\n"); //error
		}
		else
		{
			//printf("Message sent\n");

		}

		//cout << "server: " << username << " lists channels"<<endl;


	}



}
Example #26
0
	void add(long state, map<long, size_t> & m) {
		size_t c = m.size();
		m[state] = c;
	}
Example #27
0
int main(){
#ifdef ONLINE_JUDGE
  freopen( "division.in" , "r" , stdin );
  freopen( "division.out" , "w" , stdout );
#endif
  cin >> n;
  v.resize( n );
  for( int i = 0 ; i < n ; i ++ ){
    cin >> v[ i ].X >> v[ i ].Y;
    idx[ v[ i ] ] = i + 1;
  }
  assert( (int)idx.size() == n );
  sort( v.begin() , v.end() );
  for( int i = 0 ; i < n ; i ++ ){
    int up = 0 , on = 0 , dn = 0;
    for( int j = 0 ; j < n ; j ++ ){
      if( v[ j ].X < v[ i ].X )
        continue;
      if( v[ j ].Y > v[ i ].Y ) up ++;
      else if( v[ j ].Y < v[ i ].Y ) dn ++;
      else on ++;
    }
    if( on > 1 ) continue;
    okt[ i ] = true;
    lst[ i ] = make_tuple( up , on , dn );
  }
  for( int i = 0 ; i < n ; i ++ ){
    int up = 0 , on = 0 , dn = 0;
    for( int j = 0 ; j < n ; j ++ ){
      if( v[ j ].X >= v[ i ].X )
        continue;
      if( v[ j ].Y > v[ i ].Y ) up ++;
      else if( v[ j ].Y < v[ i ].Y ) dn ++;
      else on ++;
    }
    if( on > 0 ) continue;
    oks[ i ] = true;
    st[ i ] = make_tuple( up , on , dn );
  }
  for( int i = 0 ; i < n ; i ++ )
    for( int j = i ; j < n ; j ++ ){
      if( v[ j ].X == v[ i ].X ) continue;
      int up = 0 , on = 0 , dn = 0;
      int dx = v[ j ].X - v[ i ].X;
      int dy = v[ j ].Y - v[ i ].Y;
      // yy = ( x - v[ i ].X ) / dx * dy
      for( int k = 0 ; k < n ; k ++ ){
        if( v[ k ].X < v[ i ].X or
            v[ k ].X >= v[ j ].X ) continue;
        int yy = ( v[ k ].X - v[ i ].X ) * dy + v[ i ].Y * dx;
        int y2 = v[ k ].Y * dx;
        if( y2 > yy ) up ++;
        else if( y2 < yy ) dn ++;
        else on ++;
      }
      if( on > 1 ) continue;
      okk[ i ][ j ] = true;
      cst[ i ][ j ] = make_tuple( up , on , dn );
    }
  int ans = n + n , ai = 0 , aj = 0 , ak = 0;
  for( int i = 0 ; i < n ; i ++ ){
    if( not oks[ i ] ) continue;
    ok[ i ][ get<0>( st[ i ] ) ][ get<1>( st[ i ] ) ] = true;
    fr[ i ][ get<0>( st[ i ] ) ][ get<1>( st[ i ] ) ] = -1;
    fi[ i ][ get<0>( st[ i ] ) ][ get<1>( st[ i ] ) ] = -1;
    fj[ i ][ get<0>( st[ i ] ) ][ get<1>( st[ i ] ) ] = -1;
  }
  for( int i = 0 ; i < n ; i ++ )
    for( int j = 0 ; j <= n ; j ++ )
      for( int k = 0 ; k <= n ; k ++ ){
        if( not ok[ i ][ j ][ k ] ) continue;
        for( int ii = i + 1 ; ii < n ; ii ++ ){
          if( v[ ii ].X == v[ i ].X )
            continue;
          if( not okk[ i ][ ii ] )
            continue;
          int nj = j + get<0>( cst[ i ][ ii ] );
          int nk = k + get<1>( cst[ i ][ ii ] );
          if( ok[ ii ][ nj ][ nk ] ) continue;
          ok[ ii ][ nj ][ nk ] = true;
          fr[ ii ][ nj ][ nk ] = i;
          fi[ ii ][ nj ][ nk ] = j;
          fj[ ii ][ nj ][ nk ] = k;
        }
        if( not okt[ i ] ) continue;
        int upp = j + get<0>( lst[ i ] );
        int onn = k + get<1>( lst[ i ] );
        int dnn = n - upp - onn;
        if( max( upp , max( onn , dnn ) ) -
            min( upp , min( onn , dnn ) ) < ans ){
          ans = max( upp , max( onn , dnn ) ) -
                min( upp , min( onn , dnn ) );
          ai = i;
          aj = j;
          ak = k;
        }
      }
  vector<int> va;
  while( ai >= 0 ){
    va.push_back( idx[ v[ ai ] ] );
    int ni = fr[ ai ][ aj ][ ak ];
    int nj = fi[ ai ][ aj ][ ak ];
    int nk = fj[ ai ][ aj ][ ak ];
    ai = ni;
    aj = nj;
    ak = nk;
  }
  reverse( va.begin() , va.end() );
  if( va.empty() ) va.push_back( 1 );
  printf( "%d\n" , (int)va.size() );
  for( size_t i = 0 ; i < va.size() ; i ++ )
    printf( "%d%c" , va[ i ] , " \n"[ i + 1 == va.size() ] );
}
Example #28
0
bool parseURI(string stringUri, URI &uri) {
	/*
	 * schema://[username[:password]@]host[:port][/[path[?parameters]]]
	 */
	LOG_URI("------------------------");
	LOG_URI("stringUri: `%s`", STR(stringUri));
	string fullUri;
	string fullUriWithAuth = stringUri;
	string scheme;
	string authentication;
	string username;
	string password;
	string hostPort;
	string host;
	string portString;
	uint16_t port = 0;
	bool portSpecified = false;
	string fullDocumentPathWithParameters;
	string fullDocumentPath;
	string fullParameters;
	string documentPath;
	string document;
	string documentWithFullParameters;
	Variant parameters;

	string::size_type cursor = 0;
	string::size_type pos = 0;

	//1. Reset
	uri.Reset();

	//2. trim
	trim(stringUri);
	if (stringUri == "") {
		FATAL("Empty uri");
		return false;
	}

	//2. Get the scheme and the default port
	pos = stringUri.find("://", cursor);
	if (pos == string::npos) {
		FATAL("Unable to determine scheme");
		return false;
	}
	scheme = lowerCase(stringUri.substr(cursor, pos - cursor));
	cursor = pos + 3;
	if (_schemeToPort.size() == 0) {
		_schemeToPort["http"] = 80;
		_schemeToPort["rtmpt"] = 80;
		_schemeToPort["rtmpte"] = 80;
		_schemeToPort["https"] = 443;
		_schemeToPort["rtmps"] = 443;
		_schemeToPort["rtsp"] = 554;
		_schemeToPort["rtmp"] = 1935;
		_schemeToPort["rtmpe"] = 1935;
		_schemeToPort["mms"] = 1755;
	}
	if (MAP_HAS1(_schemeToPort, scheme)) {
		port = _schemeToPort[scheme];
	}
	//	else {
	//		FATAL("Scheme `%s` not supported", STR(scheme));
	//		return false;
	//	}
	LOG_URI("scheme: %s; default port: %"PRIu16, STR(scheme), port);

	//3. get the authentication portion. the search starts from
	//where the scheme detection left and up to the first / character
	string::size_type limit = stringUri.find("/", cursor);
	bool hasAuthentication = false;
	pos = stringUri.find("@", cursor);
	if (pos != string::npos) {
		if (limit != string::npos) {
			hasAuthentication = pos<limit;
		} else {
			hasAuthentication = true;
		}
	}
	if (hasAuthentication) {
		authentication = stringUri.substr(cursor, pos - cursor);
		fullUri = stringUri.substr(0, cursor);
		fullUri += stringUri.substr(pos + 1);
		cursor = pos + 1;
	} else {
		fullUri = fullUriWithAuth;
	}
	if (authentication != "") {
		pos = authentication.find(":");
		if (pos != string::npos) {
			username = authentication.substr(0, pos);
			password = authentication.substr(pos + 1);
		} else {
			username = authentication;
			password = "";
		}
	}
	LOG_URI("fullUri: `%s`; fullUriWithAuth: `%s`", STR(fullUri), STR(fullUriWithAuth));
	LOG_URI("username: `%s`; password: `%s`", STR(username), STR(password));

	//4. Get the host:port
	pos = stringUri.find("/", cursor);
	if (pos == string::npos) {
		hostPort = stringUri.substr(cursor);
		cursor = stringUri.size() - 1;
		fullDocumentPathWithParameters = "/";
	} else {
		hostPort = stringUri.substr(cursor, pos - cursor);
		cursor = pos + 1;
		fullDocumentPathWithParameters = "/" + stringUri.substr(cursor);
	}
	trim(hostPort);
	if (hostPort == "") {
		FATAL("Invalid host:port specified");
		return false;
	}
	pos = hostPort.find(":");
	if (pos == string::npos) {
		host = hostPort;
		portSpecified = false;
	} else {
		host = hostPort.substr(0, pos);
		trim(host);
		portString = hostPort.substr(pos + 1);
		portSpecified = true;
		port = (uint16_t) atoi(STR(portString));
		if (format("%"PRIu16, port) != portString) {
			FATAL("Invalid port number specified: `%s`", STR(portString));
			return false;
		}
	}
	LOG_URI("host: %s; port: %"PRIu16"; portSpecified: %d", STR(host), port, portSpecified);

	//5. fullDocumentPathWithParameters
	fullDocumentPath = "/";
	fullParameters = "";
	documentPath = "/";
	document = "";
	documentWithFullParameters = "";
	parameters.Reset();
	parameters.IsArray(false);
	if (fullDocumentPathWithParameters != "/") {
		pos = fullDocumentPathWithParameters.find("?");
		if (pos == string::npos) {
			fullDocumentPath = fullDocumentPathWithParameters;
			fullParameters = "";
		} else {
			fullDocumentPath = fullDocumentPathWithParameters.substr(0, pos);
			fullParameters = fullDocumentPathWithParameters.substr(pos + 1);
		}

		trim(fullParameters);
		if (fullParameters != "") {
			vector<string> elements;
			split(fullParameters, "&", elements);
			for (uint32_t i = 0; i < elements.size(); i++) {
				string kvp = elements[i];
				if (kvp == "")
					continue;
				string k = "";
				string v = "";
				pos = kvp.find("=");
				if (pos == string::npos) {
					k = kvp;
					v = "";
				} else {
					k = kvp.substr(0, pos);
					v = kvp.substr(pos + 1);
				}
				if (k == "")
					continue;
				parameters[k] = v;
			}
		}

		bool rtmpDocument = false;

		if (scheme.find("rtmp") == 0) {
			pos = fullDocumentPath.find(':');
			if (pos == string::npos) {
				rtmpDocument = false;
			} else {
				pos = fullDocumentPath.rfind('/', pos);
				if (pos == string::npos) {
					rtmpDocument = false;
				} else {
					rtmpDocument = true;
				}
			}
		} else {
			rtmpDocument = false;
		}

		if (rtmpDocument) {
			pos = fullDocumentPath.find(':');
			pos = fullDocumentPath.rfind('/', pos);
			documentPath = fullDocumentPath.substr(0, pos + 1);
			document = fullDocumentPath.substr(pos + 1);
		} else {
			for (string::size_type i = fullDocumentPath.size() - 1; i != 0; i--) {
				if (fullDocumentPath[i] == '/')
					break;
				document = fullDocumentPath[i] + document;
			}
			documentPath = fullDocumentPath.substr(0, fullDocumentPath.size() - document.size());
		}
		documentWithFullParameters = document;
		if (fullParameters != "")
			documentWithFullParameters += "?" + fullParameters;
	}
	LOG_URI("fullDocumentPathWithParameters: `%s`", STR(fullDocumentPathWithParameters));
	LOG_URI("fullDocumentPath: `%s`", STR(fullDocumentPath));
	LOG_URI("fullParameters: `%s`", STR(fullParameters));
	LOG_URI("documentPath: `%s`", STR(documentPath));
	LOG_URI("document: `%s`", STR(document));
	LOG_URI("documentWithFullParameters: `%s`", STR(documentWithFullParameters));
	LOG_URI("parameters:");
#ifdef DEBUG_URI

	FOR_MAP(parameters, string, Variant, i) {
		LOG_URI("\t`%s`: `%s`", STR(MAP_KEY(i)), STR(MAP_VAL(i)));
	}
Example #29
0
void udp_recv_process(int udpsock)
{
	char	ubuf[2500], *pn = ubuf;
	char	sbuf[2500];
	struct	sockaddr_in clnt_addr;
	UINT	clilen = sizeof(clnt_addr);
	
	int	rlen = recvfrom(udpsock,(void *)ubuf,2048,0,(struct sockaddr *)&clnt_addr, &clilen);
	if(rlen <= 0)  return;
	ubuf[rlen] = 0;

_LOGFILE("\n <++++++%s: udp_recv_process(%dbyte): \"%s\"\n",strHHMMSS(g_Now), rlen, ubuf);

	string srcId   = GetToken(pn,SEPARATOR,pn);
	string dstId   = GetToken(pn,SEPARATOR,pn);

strcpy(sbuf,pn);				//  보내기위해 저장..

	string command = GetToken(pn,SEPARATOR,pn);
	string key     = GetToken(pn,SEPARATOR,pn);
	string data    = GetToken(pn,SEPARATOR,pn);


	_LOGFILE_NONUM("고객수: %d\t====> %s\n",g_PosMap.size(),ubuf);


	Z_POS *pPos, *pDstPos;

	

	if((pPos=GetMember(g_PosMap,srcId)) == NULL) {
		pPos = new Z_POS;

		pPos->udpsock = udpsock;

		char	peer_ip[20];
		inet_ntop(AF_INET,&clnt_addr.sin_addr,peer_ip,sizeof(peer_ip));
		pPos->peer_ip = peer_ip;

		pPos->peerport   = ntohs(clnt_addr.sin_port);
		memcpy((char*)&pPos->clnt_addr,(char*)&clnt_addr, clilen);

		pPos->user_id = srcId;
	}

	g_PosMap[pPos->user_id] = pPos;
	WriteUser(pPos->user_id, pPos->clnt_addr);



_LOGFILE("\n srcId='%s'\n",srcId.c_str());
_LOGFILE("\n dstId='%s'\n",dstId.c_str());
_LOGFILE("\n command='%s'\n",command.c_str());

	if(dstId.length() == 0 || dstId == "0")	{
		udp_send_process(pPos, sbuf);	sleep(1);
		udp_send_process(pPos, sbuf);
		return;
	}	
		
	if((pDstPos=GetMember(g_PosMap,dstId)) == NULL) { pDstPos = new Z_POS; }

//	dbSelect_Position(pPos);
//	dbSelect_Position(pDstPos);
	
	pDstPos = GetMember(g_PosMap,dstId);



//	pPos->LOGGING();



	if(command == "ROOM")	{ }
	if(command == "READY")	{ }
	if(command == "GAME")	{ }


	udp_send_process(pDstPos, sbuf);
}
Example #30
0
void check(){
  int before_sixty = -1;
  int before_thirty = -1;
  while(1){
    int i;
    int thirty = -1;
    int sixty = -1;
    sleep(2);
    time_t now = time(NULL);
    struct tm *pnow = localtime(&now);
    int all = ((pnow->tm_hour*60+pnow->tm_min)*60)+pnow->tm_sec;
    //    cout << all << endl;
    if(window_mood.size() != 0){
      for(i = window_num-1 ; i >= 0 ; i--){
	int dif = all - time_window[i];
	//cout << dif << endl;
	//cout << time_window[i] << endl;
	if (dif > 30 && thirty == -1){
	  thirty = i;
	  // cout << "ok:" << thirty << endl;
	}
	if(dif > 120 && sixty == -1){
	  sixty = i;
	  //  cout << "ok2:" << sixty << endl;

	}
      }
      //if(){
	int aa;
	if(sixty == -1)
	  aa = 0;
	else if(before_sixty != -1 && sixty == before_sixty){
	  aa = before_sixty;
	}
	else 
	  aa = sixty;
	//	int l = thirty;
       	for(int l = window_num-1; l >= aa ; l--){
	  double sub;
	  if( window_mood[time_window[l]][human_time[time_window[l]]] == 0)
	    break;
	  sub = all-time_window[l];
	  
	  window_mood[time_window[l]][human_time[time_window[l]]] *= pow(0.1,(sub/120));
	  //  cout << pow(2,0.05) << endl;
	  cout <<  window_mood[time_window[l]][human_time[time_window[l]]] << endl;
	}
	//	before_thirty = thirty;
	//cout << "in" << endl;
	//}
      if(sixty >= 0 && sixty != before_sixty){
	int l = sixty;
	//for(int l = sixty; l > 0 ; l--)
	window_mood[time_window[l]][human_time[time_window[l]]] = 0;
	before_sixty = sixty;
	
	cout << "in2" << endl;
      }
    }
  }
}