Ejemplo n.º 1
0
void MainWindow::loadData()
{
    const auto& homedir = QDir::homePath();
    const auto& pimedir = homedir + "/.pinyin-translator/";
    const auto& local   = pimedir + "local.dic";

    QDir dir(pimedir);
    if (!dir.mkpath(pimedir))
        throw std::runtime_error("failed to create ~/.pinyin-translator");

    std::size_t wordCount = 0;

    // load local dictionary (if any). this is where new words are stored by default.
    meta data;
    data.file   = local;
    data.metaid = 1;
    meta_.insert(std::make_pair(1, data));
    if (QFileInfo(local).exists())
    {
        dic_.load(local, 1);
        wordCount = dic_.wordCount();
        qDebug() << "Loaded local dictionary " << local << " with " << wordCount << " words";
    }

    // load our "global" dictionary. this is the one that comes with the application.
    const auto& instdir = QApplication::applicationDirPath();
    const auto& datadir = instdir + "/data/";
    const auto& global  = datadir + "cedict.dic";
    const auto& freq    = datadir + "frequency.txt";
    data.file   = global;
    data.metaid = 2;
    dic_.load(global, 2);
    meta_.insert(std::make_pair(2, data));

    qDebug() << "Loaded global dictionary " << global << " with " 
             << dic_.wordCount() - wordCount << " words";
    wordCount = dic_.wordCount();

    freq_.load(freq);
    qDebug() << "Loaded word frequency data " << freq << " with "
             << freq_.freqCount() << " words";

    // load any other .dic files in user home
    quint32 metaid = 3;
    QStringList filter("*.dic");
    QStringList dics = dir.entryList(filter);
    for (const auto& file : dics)
    {
        if (file == "local.dic")
            continue;

        meta data;
        data.file = pimedir + file;
        data.metaid = metaid;
        qDebug() << "Loading: " << pimedir + file;

        dic_.load(pimedir + file, metaid);
        meta_.insert(std::make_pair(metaid, data));
        ++metaid;
    }

    NOTE(QString("Loaded dictionary with %1 words").arg(dic_.wordCount()));            

    updateDictionary("");
    updateWordCount();    
}
Ejemplo n.º 2
0
CBaseEntity	* CASW_Rocket::FindPotentialTarget( void ) const
{
	float		bestdist = 0;		
	CBaseEntity	*bestent = NULL;

	Vector v_forward, v_right, v_up;
	AngleVectors( GetAbsAngles(), &v_forward, &v_right, &v_up );

	// find the aimtarget nearest us
	int count = AimTarget_ListCount();		
	if ( count )
	{
		CBaseEntity **pList = (CBaseEntity **)stackalloc( sizeof(CBaseEntity *) * count );
		AimTarget_ListCopy( pList, count );

		CTraceFilterSkipTwoEntities filter(this, GetOwnerEntity(), COLLISION_GROUP_NONE);

		for ( int i = 0; i < count; i++ )
		{
			CBaseEntity *pEntity = pList[i];

			if (!pEntity || !pEntity->IsAlive() || !pEntity->edict() || !pEntity->IsNPC() )
			{
				//Msg("not alive or not an edict, skipping\n");
				continue;
			}

			if (!pEntity || !pEntity->IsAlive() || !pEntity->edict() || !pEntity->IsNPC() )
			{
				//Msg("not alive or not an edict, skipping\n");
				continue;
			}
	
			// don't autoaim onto marines
			if (pEntity->Classify() == CLASS_ASW_MARINE)
				continue;

			if ( pEntity->Classify() == CLASS_ASW_PARASITE )
			{
				CASW_Parasite *pParasite = static_cast< CASW_Parasite* >( pEntity );
				if ( pParasite->m_bInfesting )
				{
					continue;
				}
			}

			Vector center = pEntity->BodyTarget( GetAbsOrigin() );
			Vector center_flat = center;
			center_flat.z = GetAbsOrigin().z;

			Vector dir = (center - GetAbsOrigin());
			VectorNormalize( dir );

			Vector dir_flat = (center_flat - GetAbsOrigin());
			VectorNormalize( dir_flat );

			// make sure it's in front of the rocket
			float dot = DotProduct (dir, v_forward );
			//if (dot < 0)
			//{					
			//continue;
			//}

			float dist = (pEntity->GetAbsOrigin() - GetAbsOrigin()).LengthSqr();
			if (dist > ASW_ROCKET_MAX_HOMING_RANGE)
				continue;

			// check another marine isn't between us and the target to reduce FF
			trace_t tr;
			UTIL_TraceLine(GetAbsOrigin(), pEntity->WorldSpaceCenter(), MASK_SHOT, &filter, &tr);
			if (tr.fraction < 1.0f && tr.m_pEnt != pEntity && tr.m_pEnt && tr.m_pEnt->Classify() == CLASS_ASW_MARINE)
				continue;

			// does this critter already have enough rockets to kill it?
			{ 
				CASW_DamageAllocationMgr::IndexType_t assignmentIndex = m_RocketAssigner.Find( pEntity );
				if ( m_RocketAssigner.IsValid(assignmentIndex) )
				{
					if ( m_RocketAssigner[assignmentIndex].m_flAccumulatedDamage > pEntity->GetHealth() )
					{
						continue;
					}
				}
			}


			// check another marine isn't between us and the target to reduce FF
			UTIL_TraceLine(GetAbsOrigin(), pEntity->WorldSpaceCenter(), MASK_SHOT, &filter, &tr);
			if (tr.fraction < 1.0f && tr.m_pEnt != pEntity && tr.m_pEnt && tr.m_pEnt->Classify() == CLASS_ASW_MARINE)
				continue;

			// increase distance if dot isn't towards us
			dist += (1.0f - dot) * 150;	// bias of x units when object is 90 degrees to the side
			if (bestdist == 0 || dist < bestdist)
			{
				bestdist = dist;
				bestent = pEntity;
			}
		}

		if ( bestent && asw_rocket_debug.GetBool() )
		{
			Vector center = bestent->BodyTarget( GetAbsOrigin() );
			Vector center_flat = center;
			center_flat.z = GetAbsOrigin().z;

			Vector dir = (center - GetAbsOrigin());
			VectorNormalize( dir );
			Msg( "Rocket[%d] starting homing in on %s(%d) dir = %f %f %f\n", entindex(), bestent->GetClassname(), bestent->entindex(), VectorExpand( dir ) );
		}
	}

	return bestent;
}
Ejemplo n.º 3
0
void DocbookDocVisitor::visit(DocVerbatim *s)
{
  if (m_hide) return;
  switch(s->type())
  {
    case DocVerbatim::Code: // fall though
      m_t << "<programlisting>";
      Doxygen::parserManager->getParser(m_langExt)
        ->parseCode(m_ci,s->context(),s->text(),
            s->isExample(),s->exampleFile());
      m_t << "</programlisting>";
      break;
    case DocVerbatim::Verbatim:
      m_t << "<programlisting><literallayout>";
      filter(s->text());
      m_t << "</literallayout></programlisting>";
      break;
    case DocVerbatim::HtmlOnly:    
      break;
    case DocVerbatim::RtfOnly:     
      break;
    case DocVerbatim::ManOnly:     
      break;
    case DocVerbatim::LatexOnly:   
      break;
    case DocVerbatim::XmlOnly:     
      break;
    case DocVerbatim::DocbookOnly: 
      break;
      m_t << s->text();
      break;
    case DocVerbatim::Dot:
      {
        static int dotindex = 1;
        QCString baseName(4096);
        QCString stext = s->text();
        m_t << "<para>" << endl;
        baseName.sprintf("%s%d",
            (Config_getString("DOCBOOK_OUTPUT")+"/inline_dotgraph_").data(),
            dotindex++
            );
        QFile file(baseName+".dot");
        if (!file.open(IO_WriteOnly))
        {
          err("Could not open file %s.msc for writing\n",baseName.data());
        }
        file.writeBlock( stext, stext.length() );
        file.close();
        m_t << "    <figure>" << endl;
        m_t << "        <title></title>" << endl;
        m_t << "        <mediaobject>" << endl;
        m_t << "            <imageobject>" << endl;
        writeDotFile(baseName);
        m_t << "            </imageobject>" << endl;
        m_t << "       </mediaobject>" << endl;
        m_t << "    </figure>" << endl;
        m_t << "</para>" << endl;
      }
      break;
    case DocVerbatim::Msc:
      static int mscindex = 1;
      QCString baseName(4096);
      QCString stext = s->text();
      m_t << "<para>" << endl;
      baseName.sprintf("%s%d",
          (Config_getString("DOCBOOK_OUTPUT")+"/inline_mscgraph_").data(),
          mscindex++
          );
      QFile file(baseName+".msc");
      if (!file.open(IO_WriteOnly))
      {
        err("Could not open file %s.msc for writing\n",baseName.data());
      }
      QCString text = "msc {";
      text+=stext;
      text+="}";
      file.writeBlock( text, text.length() );
      file.close();
      m_t << "    <figure>" << endl;
      m_t << "        <title></title>" << endl;
      m_t << "        <mediaobject>" << endl;
      m_t << "            <imageobject>" << endl;
      writeMscFile(baseName);
      m_t << "            </imageobject>" << endl;
      m_t << "       </mediaobject>" << endl;
      m_t << "    </figure>" << endl;
      m_t << "</para>" << endl;
      break;
  }
}
Ejemplo n.º 4
0
//assumes list hold intptr_t fields
int countNs(list_t * xs, intptr_t n) {
  return length(filter(isN, (void*)n, xs));
}
Ejemplo n.º 5
0
void UFuncPar::rollDetectBatch()
{ // filter camculated with this oversample rate (filter frequency compared to sample frequency)
  const int oversamplingRate = 40;
  // need double amount of samples to filter around pitch frequency
  int sn = round(varp.scRollPeriods->getDouble() * oversamplingRate) * 2;
  // pointer to variable with raw data
  UVariable * rotHist;
  bool isOK;
  // obtained samples
  int rollRawCnt, pitchRawCnt;
  // obtained samples when filtered
  int rollFiltCnt, pitchFiltCnt;
  UTime t, t0, toTime;
  // estimated values
  double rollMuHat, rollSigmaHat, pitchMuHat, pitchSigmaHat;
  // update rate
  double updr = -1.0;
  // bandpass filter assuming sample rate is 40 times natural roll frq.
  // center frequency is 1/20 = 0.05
  // MATLAB filter51 = fir1(51, [0.045 0.06])
  const int firCnt = 51;
  const double fir51[] = {
  -0.003218328227846,  -0.004057818065448,  -0.005242771040626,  -0.006854855724642,  -0.008903243900917,  -0.011317902752974,
  -0.013950493386618,  -0.016583013848246,  -0.018943644085201,  -0.020728605105972,  -0.021628290934674,  -0.021355518618346,
  -0.019673505879184,  -0.016421150568180,  -0.011533356575684,  -0.005054515489408,   0.002856216387663,   0.011928552849292,
   0.021793609182402,   0.032004583207385,   0.042064159327846,   0.051456638607989,   0.059682385435555,   0.066291962326425,
   0.070917318410768,   0.073297605871962,   0.073297605871962,   0.070917318410768,   0.066291962326425,   0.059682385435555,
   0.051456638607989,   0.042064159327846,   0.032004583207385,   0.021793609182402,   0.011928552849292,   0.002856216387663,
  -0.005054515489408,  -0.011533356575684,  -0.016421150568180,  -0.019673505879184,  -0.021355518618346,  -0.021628290934674,
  -0.020728605105972,  -0.018943644085201,  -0.016583013848246,  -0.013950493386618,  -0.011317902752974,  -0.008903243900917,
  -0.006854855724642,  -0.005242771040626,  -0.004057818065448,  -0.003218328227846
};
  //
  if (sn > imuSampleMaxCnt)
  { // need for more space in sample buffer
//    rollRaw = (double *) realloc(rollRaw, sn * sizeof(double));
    rollFilt = (double *) realloc(rollFilt, sn * sizeof(double));
//    pitchRaw = (double *) realloc(pitchRaw, sn * sizeof(double));
    pitchFilt = (double *) realloc(pitchFilt, sn * sizeof(double));
    yawRaw = (double *) realloc(yawRaw, sn * sizeof(double));
    timeRaw = (double *) realloc(timeRaw, sn * sizeof(double));
    w2gDrive = (double *) realloc(w2gDrive, sn * sizeof(double));
    imuSampleMaxCnt = sn;
    printf("Allocated space for %d samples\n", sn);
  }
  t.now();
  isOK = sn <= imuSampleMaxCnt;
  if (isOK)
  {
    UVarPool * vp = getVarPool();
    const char * varSrc = varImuSource->getValues();
    rotHist = vp->getGlobalVariable(varSrc);
    isOK = rotHist != NULL;
    if (isOK)
      isOK = rotHist->hasHist() and rotHist->getHistoryRows() > oversamplingRate * 4;
    printf("PAR: imu.rot has %d samples, need %d (OK = %s)\n", rotHist->getHistoryRows(), oversamplingRate * 4, bool2str(isOK));
  }
  if (isOK)
  { // get sample rate for data vector
    updr = rotHist->hist->getSampleRate(50);
    // get step size of data for pitch (highest sample rate)
    int step = maxi(1, round(updr * varp.rollT->getDouble() / double(oversamplingRate * 2))); // / varp.updFrq->getDouble());
    // actual sample time for roll and pitch
    double dtR = 0.1, dtP = 0.1;
    //
    printf("PAR: uses every %d step from imu.rot history buffer\n", step);
    //
    t0 = rotHist->getUpdTime();
    if (not t0.valid)
      t0.now();
    toTime = t0 - varp.scRollPeriods->getDouble() * varp.rollT->getDouble();
    // debug
    // do not limit using sample time
    toTime.SetTime(0, 0);
    // debug end
    rollRawCnt  = rotHist->hist->getVectorToTime(rollRaw, sn, 0, toTime, step, &dtR);
    pitchRawCnt = rotHist->hist->getVectorToTime(pitchRaw, sn, 1, toTime, step, &dtP);
    //
    imuSampleCnt = mini(rollRawCnt, pitchRawCnt);
    // debug
    // debug save of values
    // get also yaw info - used for debug only (loaded with sweep frequency
    // NB! index 0 is the newest
    rotHist->hist->getVectorToTime(yawRaw, sn, 2, toTime, step, NULL);
    rotHist->hist->getVectorToTime(timeRaw, sn, -2, toTime, step, NULL);
    // debug print
    printf("IMU sensor raw data %g Hz update rate\n", updr);
    printf(" - pitch: uses every %d measurement, got dtP=%gsec (sfP=%gHz optimal %gHz)\n",
           step, dtP, 1.0/dtP, 2.0*oversamplingRate/varp.rollT->getDouble());
    printf(" - roll:  uses every %d measurement, got dtR=%gsec (sfR=%gHz optimal %gHz)\n",
           step * 2, dtR * 2, 0.5/dtR, oversamplingRate/varp.rollT->getDouble());
    printf(" - rollcnt=%d, pitchcnt=%d/%d, time span max = %g sec\n",
           rollRawCnt, pitchRawCnt, sn, timeRaw[0] - timeRaw[pitchRawCnt-1]);
    // debug end
    // do we have enough samples to try an estimate
    isOK = imuSampleCnt > oversamplingRate * 2;
    if (not isOK)
      printf(" - sample count too low, needs %d got %d\n", oversamplingRate * 2, imuSampleCnt);
  }
  // debug
  //printf("ParRollDetect took %g msec to get roll and pitch data\n", t.getTimePassed()*1000.0);
  // debug end
  if (isOK)
  { // filter roll by half frequency
    memset(rollFilt, 0, sizeof(double)*imuSampleCnt); // firCnt should be enough
    memset(pitchFilt, 0, sizeof(double)*imuSampleCnt);
    rollFiltCnt  = filter(&rollFilt[firCnt],  rollRaw,  imuSampleCnt, fir51, firCnt, 2);
    pitchFiltCnt = filter(&pitchFilt[firCnt], pitchRaw, imuSampleCnt, fir51, firCnt, 1);
    //
  }
  // debug
  //printf("ParRollDetect took %g msec including filter\n", t.getTimePassed() * 1000.0);
  // debug end
  if (isOK)
  { // variance estimate of filtered values
    FILE * toLog;
    toLog = fopen("medianRoll.txt", "w");
    rollMuHat = median(&rollFilt[firCnt], rollFiltCnt, 2, toLog);
    fclose(toLog);
    toLog = fopen("medianPitch.txt", "w");
    pitchMuHat = median(&pitchFilt[firCnt], pitchFiltCnt, 2, toLog);
    fclose(toLog);
    //
    rollSigmaHat = sqr(medianAbsMean(&rollFilt[firCnt], rollFiltCnt, rollMuHat, 2)/0.6745);
    pitchSigmaHat = sqr(medianAbsMean(&pitchFilt[firCnt], pitchFiltCnt, pitchMuHat, 1)/0.6745);
    printf("PAR mean_roll_hat=%.5f, mean_pitch_hat=%.5f, roll_sigma_hat=%.5f, pitch_sigma_hat=%.5f\n",
           rollMuHat, pitchMuHat, rollSigmaHat, pitchSigmaHat);
  }
  // scaled signal combined of filtered pitch squared roll.
  if (isOK)
  { // roll rollFiltCnt is the number of usable samples in the analysis sample set.
    double driveScale = 1.0/(1.0 + sqrt(rollSigmaHat * pitchSigmaHat));
    printf("PAR: drive scale=%.5f\n", driveScale);
    for (int i = 0; i < rollFiltCnt; i++)
    {  // roll has the lowest sample rate, so use i<<1 for pitch index
      w2gDrive[i] = sqr(rollFilt[i] - rollMuHat) * (pitchFilt[i] - pitchMuHat) * driveScale;
    }
    // debug save of values
    if (isOK) // and rollRawCnt > sn - 10)
    {
      double * pData[7];
      pData[0] = timeRaw;
      pData[1] = rollRaw;
      pData[2] = pitchRaw;
      pData[3] = rollFilt;
      pData[4] = pitchFilt;
      pData[5] = yawRaw;
      pData[6] = w2gDrive;
      toFile("rollPitchFilt.txt",pData, 7, rollFiltCnt);
    }
  }
  if (isOK)
  { // find shape of Weibull distribution
    double w2gShape;
    double w2gScale, sm = 0.0;
    //
    w2gShape = findW2gScale(w2gDrive, rollFiltCnt);
    for (int i = 0; i < rollFiltCnt; i++)
      sm += pow(w2gDrive[i], w2gShape);
    w2gScale = pow(sm/double(rollFiltCnt), 1.0/w2gShape);
    //
    vars.w2gShape->setDouble(w2gShape);
    vars.w2gScale->setDouble(w2gScale);
  }
  // debug
  //printf("ParRollDetect took %g msec including median\n", t.getTimePassed() * 1000.0);
  // debug end
  update6hMax(varp.horizon6h->getDouble() * 60.0);
  // debug
  //printf("ParRollDetect took %g msec including 6h update\n", t.getTimePassed() * 1000.0);
  vars.calcTime->setDouble(t.getTimePassed() * 1000.0);
  // debug end
}
Ejemplo n.º 6
0
void PrefsTree::setLoadedOnly( bool b_only )
{
    b_show_only_loaded = b_only;
    filter( "" );
}
Ejemplo n.º 7
0
    static bool HandleBanListCharacterCommand(ChatHandler* handler, char const* args)
    {
        if (!*args)
            return false;

        char* filterStr = strtok((char*)args, " ");
        if (!filterStr)
            return false;

        std::string filter(filterStr);
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUID_BY_NAME_FILTER);
        stmt->setString(0, filter);
        PreparedQueryResult result = CharacterDatabase.Query(stmt);
        if (!result)
        {
            handler->PSendSysMessage(LANG_BANLIST_NOCHARACTER);
            return true;
        }

        handler->PSendSysMessage(LANG_BANLIST_MATCHINGCHARACTER);

        // Chat short output
        if (handler->GetSession())
        {
            do
            {
                Field* fields = result->Fetch();
                PreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANNED_NAME);
                stmt2->setUInt32(0, fields[0].GetUInt32());
                PreparedQueryResult banResult = CharacterDatabase.Query(stmt2);
                if (banResult)
                    handler->PSendSysMessage("%s", (*banResult)[0].GetCString());
            }
            while (result->NextRow());
        }
        // Console wide output
        else
        {
            handler->SendSysMessage(LANG_BANLIST_CHARACTERS);
            handler->SendSysMessage(" =============================================================================== ");
            handler->SendSysMessage(LANG_BANLIST_CHARACTERS_HEADER);
            do
            {
                handler->SendSysMessage("-------------------------------------------------------------------------------");

                Field* fields = result->Fetch();

                std::string char_name = fields[1].GetString();

                PreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANINFO_LIST);
                stmt2->setUInt32(0, fields[0].GetUInt32());
                PreparedQueryResult banInfo = CharacterDatabase.Query(stmt2);
                if (banInfo)
                {
                    Field* banFields = banInfo->Fetch();
                    do
                    {
                        time_t timeBan = time_t(banFields[0].GetUInt32());
                        tm* tmBan = localtime(&timeBan);

                        if (banFields[0].GetUInt32() == banFields[1].GetUInt32())
                        {
                            handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|   permanent  |%-15.15s|%-15.15s|",
                                char_name.c_str(), tmBan->tm_year%100, tmBan->tm_mon+1, tmBan->tm_mday, tmBan->tm_hour, tmBan->tm_min,
                                banFields[2].GetCString(), banFields[3].GetCString());
                        }
                        else
                        {
                            time_t timeUnban = time_t(banFields[1].GetUInt32());
                            tm* tmUnban = localtime(&timeUnban);
                            handler->PSendSysMessage("|%-15.15s|%02d-%02d-%02d %02d:%02d|%02d-%02d-%02d %02d:%02d|%-15.15s|%-15.15s|",
                                char_name.c_str(), tmBan->tm_year%100, tmBan->tm_mon+1, tmBan->tm_mday, tmBan->tm_hour, tmBan->tm_min,
                                tmUnban->tm_year%100, tmUnban->tm_mon+1, tmUnban->tm_mday, tmUnban->tm_hour, tmUnban->tm_min,
                                banFields[2].GetCString(), banFields[3].GetCString());
                        }
                    }
                    while (banInfo->NextRow());
                }
            }
            while (result->NextRow());
            handler->SendSysMessage(" =============================================================================== ");
        }

        return true;
    }
Ejemplo n.º 8
0
void sobelitereen(double xm2, double xm1, double x0, double x1, double x2, double x3, double x4, double x5,
                  double x6, double x7, double x8, double x9, double x10, double x11, double x12,
                  double x13, double x14, double x15, double x16, double x17, double x18, double x19, double x20, double x21,
                  double* z1, double* z2, double* z3, double* z4, double* z5, double* z6, double* z7,
                  double* z8, double* z9, double* z10, double* z11, double* z12, double* z13, double* z14,
                  double* z15, double* z16, double* z17, double* z18, double* z19) 
{
  double y0, y1, y2, y3, y4, y5, y6, y7, y8, y9;
  double y10, y11, y12, y13, y14, y15, y16, y17, y18, y19;
  
  y0=blur(xm2,xm1,x0,x1,x2);
  y1=blur(xm1,x0,x1,x2,x3);
  y2=blur(x0,x1,x2,x3,x4);
  y3=blur(x1,x2,x3,x4,x5);
  y4=blur(x2,x3,x4,x5,x6);
  y5=blur(x3,x4,x5,x6,x7);
  y6=blur(x4,x5,x6,x7,x8);
  y7=blur(x5,x6,x7,x8,x9);
  y8=blur(x6,x7,x8,x9,x10);
  y9=blur(x7,x8,x9,x10,x11);
  y10=blur(x8,x9,x10,x11,x12);
  y11=blur(x9,x10,x11,x12,x13);
  y12=blur(x10,x11,x12,x13,x14);
  y13=blur(x11,x12,x13,x14,x15);
  y14=blur(x12,x13,x14,x15,x16);
  y15=blur(x13,x14,x15,x16,x17);
  y16=blur(x14,x15,x16,x17,x18);
  y17=blur(x15,x16,x17,x18,x19);
  y18=blur(x16,x17,x18,x19,x20);
  y19=blur(x17,x18,x19,x20,x21);

  filter(y0, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17, y18, y19,
        &x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9, &x10, &x11, &x12, &x13, &x14, &x15, &x16, &x17, &x18, &x19);
  filter(y0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19,
        &y1, &y2, &y3, &y4, &y5, &y6, &y7, &y8, &y9, &y10, &y11, &y12, &y13, &y14, &y15, &y16, &y17, &y18, &y19);
  filter(y0, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17, y18, y19,
        &x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9, &x10, &x11, &x12, &x13, &x14, &x15, &x16, &x17, &x18, &x19);
  filter(y0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19,
        &y1, &y2, &y3, &y4, &y5, &y6, &y7, &y8, &y9, &y10, &y11, &y12, &y13, &y14, &y15, &y16, &y17, &y18, &y19);
  filter(y0, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12, y13, y14, y15, y16, y17, y18, y19,
        &x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9, &x10, &x11, &x12, &x13, &x14, &x15, &x16, &x17, &x18, &x19);
  filter(y0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19,
        &y1, &y2, &y3, &y4, &y5, &y6, &y7, &y8, &y9, &y10, &y11, &y12, &y13, &y14, &y15, &y16, &y17, &y18, &y19);
  
  *z1 = y1;
  *z2 = y2;
  *z3 = y3;
  *z4 = y4;
  *z5 = y5;
  *z6 = y6;
  *z7 = y7;
  *z8 = y8;
  *z9 = y9;
  *z10 = y10;
  *z11 = y11;
  *z12 = y12;
  *z13 = y13;
  *z14 = y14;
  *z15 = y15;
  *z16 = y16;
  *z17 = y17;
  *z18 = y18;
  *z19 = y19;
}
Ejemplo n.º 9
0
void CGrenadeHomer::Detonate(void)
{
	StopRocketTrail();

	StopSound(entindex(), CHAN_BODY, STRING(m_sFlySound));

	m_takedamage	= DAMAGE_NO;	

	CPASFilter filter( GetAbsOrigin() );

	te->Explosion( filter, 0.0,
		&GetAbsOrigin(), 
		g_sModelIndexFireball,
		2.0, 
		15,
		TE_EXPLFLAG_NONE,
		m_DmgRadius,
		m_flDamage );

//	int magnitude = 1.0;
//	int	colorRamp = random->RandomInt( 128, 255 );


	if ( m_nRocketTrailType == HOMER_SMOKE_TRAIL_ALIEN )
	{
		// Add a shockring
		CBroadcastRecipientFilter filter3;
		te->BeamRingPoint( filter3, 0, 
			GetAbsOrigin(),	//origin
			16,			//start radius
			1000,		//end radius
			m_spriteTexture, //texture
			0,			//halo index
			0,			//start frame
			2,			//framerate
			0.3f,		//life
			128,		//width
			16,			//spread
			0,			//amplitude
			100,		//r
			0,			//g
			200,		//b
			50,			//a
			128			//speed
			);


		// Add a shockring
		CBroadcastRecipientFilter filter4;
		te->BeamRingPoint( filter4, 0, 
			GetAbsOrigin(),	//origin
			16,			//start radius
			500,		//end radius
			m_spriteTexture, //texture
			0,			//halo index
			0,			//start frame
			2,			//framerate
			0.3f,		//life
			128,		//width
			16,			//spread
			0,			//amplitude
			200,		//r
			0,			//g
			100,		//b
			50,			//a
			128			//speed
			);



	}


	Vector vecForward = GetAbsVelocity();
	VectorNormalize(vecForward);
	trace_t		tr;
	UTIL_TraceLine ( GetAbsOrigin(), GetAbsOrigin() + 60*vecForward,  MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, & tr);

	UTIL_DecalTrace( &tr, "Scorch" );

	UTIL_ScreenShake( GetAbsOrigin(), 25.0, 150.0, 1.0, 750, SHAKE_START );

	RadiusDamage ( CTakeDamageInfo( this, GetOwnerEntity(), m_flDamage, DMG_BLAST ), GetAbsOrigin(), m_DmgRadius, CLASS_NONE, NULL );
	CPASAttenuationFilter filter2( this, "GrenadeHomer.StopSounds" );
	EmitSound( filter2, entindex(), "GrenadeHomer.StopSounds" );
	UTIL_Remove( this );
}
Ejemplo n.º 10
0
 /**
  * @brief Execute
  * @param imgIn
  * @param imgOut
  * @param threshold_nuked
  * @return
  */
 static Image* Execute(Image *imgIn, Image *imgOut, float threshold_nuked = 1e4)
 {
     FilterRemoveNuked filter(threshold_nuked);
     imgOut = filter.ProcessP(Single(imgIn), imgOut);
     return imgOut;
 }
Ejemplo n.º 11
0
void main() 
{
  double xm2, xm1, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9;
  double x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21;
  double y0, y1, y2, y3, y4, y5, y6, y7, y8, y9;
  double y10, y11, y12, y13, y14, y15, y16, y17, y18, y19;
  
  filter(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0,
         &x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9, &x10, &x11, &x12, &x13, &x14, &x15, &x16, &x17, &x18, &x19);
  filter(1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0,
         &x1, &x2, &x3, &x4, &x5, &x6, &x7, &x8, &x9, &x10, &x11, &x12, &x13, &x14, &x15, &x16, &x17, &x18, &x19);
  
  xm2=0;
  xm1=0;
  x0=0;
  x1=-1;
  x2=-0.5;
  x3=0.75;
  x4=1;
  x5=1;
  x6=1;
  x7=1;
  x8=1;
  x9=1;
  x10=1;
  x11=1;
  x12=1;
  x13=1;
  x14=1;
  x15=1;
  x16=1;
  x17=1;
  x18=1;
  x19=1;
  x20=1;
  x21=1;

  sobelitereen(xm2, xm1, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9,
               x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21,
               &y1, &y2, &y3, &y4, &y5, &y6, &y7, &y8, &y9, &y10, &y11, &y12, &y13, &y14, &y15, &y16, &y17, &y18, &y19);
  x1=0;
  x2=0.5;
  x3=1.0;
  sobelitereen(xm2, xm1, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9,
               x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21,
               &y1, &y2, &y3, &y4, &y5, &y6, &y7, &y8, &y9, &y10, &y11, &y12, &y13, &y14, &y15, &y16, &y17, &y18, &y19);

  int i = 0;
  while (i < 10) {
    x1 = __VERIFIER_nondet_double();
    x2 = __VERIFIER_nondet_double();
    x3 = __VERIFIER_nondet_double();
    __VERIFIER_assume(x1 >= -1.0 + i/10 && x1 <= -1.0 + (i+1)/10);
    __VERIFIER_assume(x2 >= -.5 + i/10 && x2 <= -0.5 + (i+1)/10);
    __VERIFIER_assume(x3 >= 0.75+i/40 && x3 <= 0.75+(i+1)/40);
    sobelitereen(xm2, xm1, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9,
                 x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21,
                 &y1, &y2, &y3, &y4, &y5, &y6, &y7, &y8, &y9, &y10, &y11, &y12, &y13, &y14, &y15, &y16, &y17, &y18, &y19);
    ++i;
  };

  __VERIFIER_assert(y1 >= -1. && y1 <= 1.);
  __VERIFIER_assert(y2 >= -1. && y2 <= 1.);
  __VERIFIER_assert(y3 >= -1. && y3 <= 1.);
  __VERIFIER_assert(y4 >= -1. && y4 <= 1.);
  __VERIFIER_assert(y5 >= -1. && y5 <= 1.);
  __VERIFIER_assert(y6 >= -1. && y6 <= 1.);
  __VERIFIER_assert(y7 >= -1. && y7 <= 1.);
  __VERIFIER_assert(y8 >= -1. && y8 <= 1.);
  __VERIFIER_assert(y9 >= -1. && y9 <= 1.);
  __VERIFIER_assert(y10 >= -1. && y10 <= 1.);
  __VERIFIER_assert(y11 >= -1. && y11 <= 1.);
  __VERIFIER_assert(y12 >= -1. && y12 <= 1.);
  __VERIFIER_assert(y13 >= -1. && y13 <= 1.);
  __VERIFIER_assert(y14 >= -1. && y14 <= 1.);
  __VERIFIER_assert(y15 >= -1. && y15 <= 1.);
  __VERIFIER_assert(y16 >= -1. && y16 <= 1.);
  __VERIFIER_assert(y17 >= -1. && y17 <= 1.);
  __VERIFIER_assert(y18 >= -1. && y18 <= 1.);
  __VERIFIER_assert(y19 >= -1. && y19 <= 1.);
}
Ejemplo n.º 12
0
NamesAndTypesList NamesAndTypesList::filter(const Names & names) const
{
    return filter(NameSet(names.begin(), names.end()));
}
//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CNPC_PoisonZombie::Spawn( void )
{
	Precache();

	m_fIsTorso = m_fIsHeadless = false;

#ifdef HL2_EPISODIC
	SetBloodColor( BLOOD_COLOR_ZOMBIE );
#else
	SetBloodColor( BLOOD_COLOR_YELLOW );
#endif // HL2_EPISODIC

	m_iHealth = sk_zombie_poison_health.GetFloat();
	m_flFieldOfView = 0.2;

	CapabilitiesClear();
	CapabilitiesAdd( bits_CAP_MOVE_GROUND | bits_CAP_INNATE_MELEE_ATTACK1 | bits_CAP_INNATE_RANGE_ATTACK1 | bits_CAP_INNATE_RANGE_ATTACK2 );

	BaseClass::Spawn();

	CPASAttenuationFilter filter( this, ATTN_IDLE );
	m_pFastBreathSound = ENVELOPE_CONTROLLER.SoundCreate( filter, entindex(), CHAN_ITEM, "NPC_PoisonZombie.FastBreath", ATTN_IDLE );
	ENVELOPE_CONTROLLER.Play( m_pFastBreathSound, 0.0f, 100 );

	CPASAttenuationFilter filter2( this );
	m_pSlowBreathSound = ENVELOPE_CONTROLLER.SoundCreate( filter2, entindex(), CHAN_ITEM, "NPC_PoisonZombie.Moan1", ATTN_NORM );
	ENVELOPE_CONTROLLER.Play( m_pSlowBreathSound, BREATH_VOL_MAX, 100 );

	int nCrabs = m_nCrabCount;
	if ( !nCrabs )
	{
		nCrabs = MAX_CRABS;
	}
	m_nCrabCount = 0;

	//
	// Generate a random set of crabs based on the crab count
	// specified by the level designer.
	//
	int nBits[] = 
	{
		// One bit
		0x01,
		0x02,
		0x04,

		// Two bits
		0x03,
		0x05,
		0x06,
	};

	int nBitMask = 7;
	if (nCrabs == 1)
	{
		nBitMask = nBits[random->RandomInt( 0, 2 )];
	}
	else if (nCrabs == 2)
	{
		nBitMask = nBits[random->RandomInt( 3, 5 )];
	}

	for ( int i = 0; i < MAX_CRABS; i++ )
	{
		EnableCrab( i, ( nBitMask & ( 1 << i ) ) != 0 );
	}
}
Ejemplo n.º 14
0
void renderQuiz(int slideIndex, std::string* pHead, std::string* pHTML)
{      
   // tweak the radio button size
   pHead->append(
      "<style>.quiz-multichoice .reveal input { zoom: 2.5; }</style>\n");

   // build form id
   std::string suffix = safe_convert::numberToString<int>(slideIndex);
   std::string formId = "quizForm" + suffix;

   // build validation script
   boost::format fmtScript(
      "<script>\n"
      "function %1%(answer, correct, feedback) {\n"
      "  document.getElementById('%2%_correctFeedback').innerText = feedback;\n"
      "  document.getElementById('%2%_incorrectFeedback').innerText = feedback;\n"
      "  document.getElementById('%2%_correct').style.display ="
            " correct ? \"block\" : \"none\";\n"
      "  document.getElementById('%2%_incorrect').style.display ="
            " correct ? \"none\" : \"block\";\n"
      "  if (window.parent.recordPresentationQuizAnswer)\n"
      "    window.parent.recordPresentationQuizAnswer("
            "%3%, answer, correct);\n "
      "}\n"
      "</script>\n\n");
   pHead->append(boost::str(fmtScript
                              % handleClickFunction(formId)
                              % formId
                              % slideIndex));

   // correct and incorrect divs
   std::string cssAttribs = "class=\"quizFeedback\" style=\"display:none\"";
   boost::format fmtFeedback(
      "<div id=\"%1%_correct\" %2%>\n"
      "<img src=\"slides-images/correct.png\"/>"
      "<span id=\"%1%_correctFeedback\">Correct!</span>\n"
      "</div>\n"
      "<div id=\"%1%_incorrect\" %2%>\n"
      "<img src=\"slides-images/incorrect.png\"/>"
      "<span id=\"%1%_incorrectFeedback\">Incorrect</span>\n"
      "</div>\n");
   std::string feedbackHTML = boost::str(fmtFeedback % formId % cssAttribs);

   // enclose in form
   boost::format fmt("<form id=\"%1%\">\n\n<ul>");
   boost::algorithm::replace_first(*pHTML, "<ul>", boost::str(fmt % formId));
   boost::format suffixFmt("</ul>\n\n%1%\n</form>\n");
   boost::algorithm::replace_last(*pHTML, "</ul>", boost::str(suffixFmt %
                                                               feedbackHTML));

   // create input elements
   int itemIndex = 0;
   boost::iostreams::regex_filter filter(boost::regex("<li>(.+?)<\\/li>"),
                                         boost::bind(asFormInput,
                                                      _1, formId, &itemIndex));

   // inputs html
   Error error = regex_utils::filterString(*pHTML, filter, pHTML);
   if (error)
      LOG_ERROR(error);
}
Ejemplo n.º 15
0
////////////////////////////////////////////////////////////////////////////////
// Project  Remaining  Avg Age  Complete  0%                  100%
// A               12      13d       55%  XXXXXXXXXXXXX-----------
// B              109   3d 12h       10%  XXX---------------------
int CmdSummary::execute (std::string& output)
{
  int rc = 0;

  // Scan the pending tasks.
  handleRecurrence ();

  // Apply filter.
  std::vector <Task> filtered;
  filter (filtered);
  context.tdb2.commit ();

  // Generate unique list of project names from all pending tasks.
  std::map <std::string, bool> allProjects;
  std::vector <Task>::iterator task;
  for (task = filtered.begin (); task != filtered.end (); ++task)
    if (task->getStatus () == Task::pending)
      allProjects[task->get ("project")] = false;

  // Initialize counts, sum.
  std::map <std::string, int> countPending;
  std::map <std::string, int> countCompleted;
  std::map <std::string, double> sumEntry;
  std::map <std::string, int> counter;
  time_t now = time (NULL);

  // Initialize counters.
  std::map <std::string, bool>::iterator project;
  for (project = allProjects.begin (); project != allProjects.end (); ++project)
  {
    countPending   [project->first] = 0;
    countCompleted [project->first] = 0;
    sumEntry       [project->first] = 0.0;
    counter        [project->first] = 0;
  }

  // Count the various tasks.
  for (task = filtered.begin (); task != filtered.end (); ++task)
  {
    std::string project = task->get ("project");
    ++counter[project];

    if (task->getStatus () == Task::pending ||
        task->getStatus () == Task::waiting)
    {
      ++countPending[project];

      time_t entry = strtol (task->get ("entry").c_str (), NULL, 10);
      if (entry)
        sumEntry[project] = sumEntry[project] + (double) (now - entry);
    }

    else if (task->getStatus () == Task::completed)
    {
      ++countCompleted[project];

      time_t entry = strtol (task->get ("entry").c_str (), NULL, 10);
      time_t end   = strtol (task->get ("end").c_str (), NULL, 10);
      if (entry && end)
        sumEntry[project] = sumEntry[project] + (double) (end - entry);
    }
  }

  // Create a table for output.
  ViewText view;
  view.width (context.getWidth ());
  view.add (Column::factory ("string",            STRING_CMD_SUMMARY_PROJECT));
  view.add (Column::factory ("string.right",      STRING_CMD_SUMMARY_REMAINING));
  view.add (Column::factory ("string.right",      STRING_CMD_SUMMARY_AVG_AGE));
  view.add (Column::factory ("string.right",      STRING_CMD_SUMMARY_COMPLETE));
  view.add (Column::factory ("string.left_fixed", "0%                        100%"));

  Color bar_color (context.config.get ("color.summary.bar"));
  Color bg_color  (context.config.get ("color.summary.background"));

  int barWidth = 30;
  std::vector <std::string> processed;
  std::map <std::string, bool>::iterator i;
  for (i = allProjects.begin (); i != allProjects.end (); ++i)
  {
    if (countPending[i->first] > 0)
    {
      const std::vector <std::string> parents = extractParents (i->first);
      std::vector <std::string>::const_iterator parent;
      for (parent = parents.begin (); parent != parents.end (); parent++)
      {
        if (std::find (processed.begin (), processed.end (), *parent)
           == processed.end ())
        {
          int row = view.addRow ();
          view.set (row, 0, indentProject (*parent));
          processed.push_back (*parent);
        }
      }

      int row = view.addRow ();
      view.set (row, 0, (i->first == ""
                          ? STRING_CMD_SUMMARY_NONE
                          : indentProject (i->first, "  ", '.')));

      view.set (row, 1, countPending[i->first]);
      if (counter[i->first])
        view.set (row, 2, Duration ((int) (sumEntry[i->first] / (double)counter[i->first])).format ());

      int c = countCompleted[i->first];
      int p = countPending[i->first];
      int completedBar = (c * barWidth) / (c + p);

      std::string bar;
      std::string subbar;
      if (context.color ())
      {
        bar += bar_color.colorize (std::string (           completedBar, ' '));
        bar += bg_color.colorize  (std::string (barWidth - completedBar, ' '));
      }
      else
      {
        bar += std::string (           completedBar, '=')
            +  std::string (barWidth - completedBar, ' ');
      }
      view.set (row, 4, bar);

      char percent[12];
      sprintf (percent, "%d%%", 100 * c / (c + p));
      view.set (row, 3, percent);
      processed.push_back (i->first);
    }
  }

  std::stringstream out;
  if (view.rows ())
  {
    out << optionalBlankLine ()
        << view.render ()
        << optionalBlankLine ();

    if (view.rows ())
      out << format (STRING_CMD_PROJECTS_SUMMARY2, view.rows ());
    else
      out << STRING_CMD_PROJECTS_SUMMARY;

    out << "\n";
  }
  else {
    out << STRING_CMD_PROJECTS_NO << "\n";
    rc = 1;
  }

  output = out.str ();
  return rc;
}
Ejemplo n.º 16
0
/*
 * Main loop for command mode command decoding.
 * A few commands are executed here, but main function
 * is to strip command addresses, do a little address oriented
 * processing and call command routines to do the real work.
 */
void
commands(bool noprompt, bool exitoneof)
{
	register line *addr;
	register int c;
	register int lchng;
	int given;
	int seensemi;
	int cnt;
	bool hadpr;

	resetflav();
	nochng();
	for (;;) {
		/*
		 * If dot at last command
		 * ended up at zero, advance to one if there is a such.
		 */
		if (dot <= zero) {
			dot = zero;
			if (dol > zero)
				dot = one;
		}
		shudclob = 0;

		/*
		 * If autoprint or trailing print flags,
		 * print the line at the specified offset
		 * before the next command.
		 */
		if (pflag ||
		    (lchng != chng && value(AUTOPRINT) && !inglobal && !inopen && endline)) {
			pflag = 0;
			nochng();
			if (dol != zero) {
				addr1 = addr2 = dot + poffset;
				if (addr1 < one || addr1 > dol)
error("Offset out-of-bounds|Offset after command too large");
				setdot1();
				goto print;
			}
		}
		nochng();

		/*
		 * Print prompt if appropriate.
		 * If not in global flush output first to prevent
		 * going into pfast mode unreasonably.
		 */
		if (inglobal == 0) {
			flush();
			if (!hush && value(PROMPT) && !globp && !noprompt && endline) {
				ex_putchar(':');
				hadpr = 1;
			}
			TSYNC();
		}

		/*
		 * Gobble up the address.
		 * Degenerate addresses yield ".".
		 */
		addr2 = 0;
		given = seensemi = 0;
		do {
			addr1 = addr2;
			addr = address(0);
			c = getcd();
			if (addr == 0) {
				if (c == ',')
					addr = dot;
				else if (addr1 != 0) {
					addr2 = dot;
					break;
				} else
					break;
			}
			addr2 = addr;
			given++;
			if (c == ';') {
				c = ',';
				dot = addr;
				seensemi = 1;
			}
		} while (c == ',');
		if (c == '%') {
			/* %: same as 1,$ */
			addr1 = one;
			addr2 = dol;
			given = 2;
			c = ex_getchar();
		}
		if (addr1 == 0)
			addr1 = addr2;
		if (c == ':')
			c = ex_getchar();

		/*
		 * Set command name for special character commands.
		 */
		tailspec(c);

		/*
		 * If called via : escape from open or visual, limit
		 * the set of available commands here to save work below.
		 */
		if (inopen) {
			if (c=='\n' || c=='\r' || c==CTRL('d') || c==EOF) {
				if (addr2)
					dot = addr2;
				if (c == EOF)
					return;
				continue;
			}
			if (any(c, "o"))
notinvis:
				tailprim(Command, 1, 1);
		}
		switch (c) {

		case 'a':

			switch(peekchar()) {
			case 'b':
/* abbreviate */
				tail("abbreviate");
				setnoaddr();
				mapcmd(0, 1);
				anyabbrs = 1;
				continue;
			case 'r':
/* args */
				tail("args");
				setnoaddr();
				eol();
				pargs();
				continue;
			}

/* append */
			if (inopen)
				goto notinvis;
			tail("append");
			setdot();
			aiflag = exclam();
			ex_newline();
			vmacchng(0);
			deletenone();
			setin(addr2);
			inappend = 1;
			ignore(append(gettty, addr2));
			inappend = 0;
			nochng();
			continue;

		case 'c':
			switch (peekchar()) {

/* copy */
			case 'o':
				tail("copy");
				vmacchng(0);
				move();
				continue;

#ifdef CHDIR
/* cd */
			case 'd':
				tail("cd");
				goto changdir;

/* chdir */
			case 'h':
				ignchar();
				if (peekchar() == 'd') {
					register char *p;
					tail2of("chdir");
changdir:
					if (savedfile[0] == '/' || !value(WARN))
						ignore(exclam());
					else
						ignore(quickly());
					if (skipend()) {
						p = getenv("HOME");
						if (p == NULL)
							error("Home directory unknown");
					} else
						getone(), p = file;
					eol();
					if (chdir(p) < 0)
						filioerr(p);
					if (savedfile[0] != '/')
						edited = 0;
					continue;
				}
				if (inopen)
					tailprim("change", 2, 1);
				tail2of("change");
				break;

#endif
			default:
				if (inopen)
					goto notinvis;
				tail("change");
				break;
			}
/* change */
			aiflag = exclam();
			setCNL();
			vmacchng(0);
			setin(addr1);
			delete(0);
			inappend = 1;
			ignore(append(gettty, addr1 - 1));
			inappend = 0;
			nochng();
			continue;

/* delete */
		case 'd':
			/*
			 * Caution: dp and dl have special meaning already.
			 */
			tail("delete");
			c = cmdreg();
			setCNL();
			vmacchng(0);
			if (c)
				YANKreg(c);
			delete(0);
			appendnone();
			continue;

/* edit */
/* ex */
		case 'e':
			tail(peekchar() == 'x' ? "ex" : "edit");
editcmd:
			if (!exclam() && chng)
				c = 'E';
			filename(c);
			if (c == 'E') {
				ungetchar(lastchar());
				ignore(quickly());
			}
			setnoaddr();
doecmd:
			init();
			addr2 = zero;
			laste++;
			ex_sync();
			rop(c);
			nochng();
			continue;

/* file */
		case 'f':
			tail("file");
			setnoaddr();
			filename(c);
			noonl();
/*
			synctmp();
*/
			continue;

/* global */
		case 'g':
			tail("global");
			global(!exclam());
			nochng();
			continue;

/* insert */
		case 'i':
			if (inopen)
				goto notinvis;
			tail("insert");
			setdot();
			nonzero();
			aiflag = exclam();
			ex_newline();
			vmacchng(0);
			deletenone();
			setin(addr2);
			inappend = 1;
			ignore(append(gettty, addr2 - 1));
			inappend = 0;
			if (dot == zero && dol > zero)
				dot = one;
			nochng();
			continue;

/* join */
		case 'j':
			tail("join");
			c = exclam();
			setcount();
			nonzero();
			ex_newline();
			vmacchng(0);
			if (given < 2 && addr2 != dol)
				addr2++;
			join(c);
			continue;

/* k */
		case 'k':
casek:
			pastwh();
			c = ex_getchar();
			if (endcmd(c))
				serror("Mark what?|%s requires following letter", Command);
			ex_newline();
			if (!islower(c))
				error("Bad mark|Mark must specify a letter");
			setdot();
			nonzero();
			names[c - 'a'] = *addr2 &~ 01;
			anymarks = 1;
			continue;

/* list */
		case 'l':
			tail("list");
			setCNL();
			ignorf(setlist(1));
			pflag = 0;
			goto print;

		case 'm':
			if (peekchar() == 'a') {
				ignchar();
				if (peekchar() == 'p') {
/* map */
					tail2of("map");
					setnoaddr();
					mapcmd(0, 0);
					continue;
				}
/* mark */
				tail2of("mark");
				goto casek;
			}
/* move */
			tail("move");
			vmacchng(0);
			move();
			continue;

		case 'n':
			if (peekchar() == 'u') {
				tail("number");
				goto numberit;
			}
/* next */
			tail("next");
			setnoaddr();
			ckaw();
			ignore(quickly());
			if (getargs())
				makargs();
			next();
			c = 'e';
			filename(c);
			goto doecmd;

/* open */
		case 'o':
			tail("open");
			oop();
			pflag = 0;
			nochng();
			continue;

		case 'p':
		case 'P':
			switch (peekchar()) {

/* put */
			case 'u':
				tail("put");
				setdot();
				c = cmdreg();
				eol();
				vmacchng(0);
				if (c)
					putreg(c);
				else
					put();
				continue;

			case 'r':
				ignchar();
				if (peekchar() == 'e') {
/* preserve */
					tail2of("preserve");
					eol();
					if (preserve() == 0)
						error("Preserve failed!");
					else
						error("File preserved.");
				}
				tail2of("print");
				break;

			default:
				tail("print");
				break;
			}
/* print */
			setCNL();
			pflag = 0;
print:
			nonzero();
			if (CL && span() > EX_LINES) {
				flush1();
				vclear();
			}
			plines(addr1, addr2, 1);
			continue;

/* quit */
		case 'q':
			tail("quit");
			setnoaddr();
			c = quickly();
			eol();
			if (!c)
quit:
				nomore();
			if (inopen) {
				vgoto(WECHO, 0);
				if (!ateopr())
					vnfl();
				else {
					tostop();
				}
				flush();
				setty(normf);
			}
			cleanup(1);
			ex_exit(0);

		case 'r':
			if (peekchar() == 'e') {
				ignchar();
				switch (peekchar()) {

/* rewind */
				case 'w':
					tail2of("rewind");
					setnoaddr();
					if (!exclam()) {
						ckaw();
						if (chng && dol > zero)
							error("No [email protected] last chage (:rewind! overrides)");
					}
					eol();
					erewind();
					next();
					c = 'e';
					ungetchar(lastchar());
					filename(c);
					goto doecmd;

/* recover */
				case 'c':
					tail2of("recover");
					setnoaddr();
					c = 'e';
					if (!exclam() && chng)
						c = 'E';
					filename(c);
					if (c == 'E') {
						ungetchar(lastchar());
						ignore(quickly());
					}
					init();
					addr2 = zero;
					laste++;
					ex_sync();
					recover();
					rop2();
					revocer();
					if (status == 0)
						rop3(c);
					if (dol != zero)
						change();
					nochng();
					continue;
				}
				tail2of("read");
			} else
				tail("read");
/* read */
			if (savedfile[0] == 0 && dol == zero)
				c = 'e';
			pastwh();
			vmacchng(0);
			if (peekchar() == '!') {
				setdot();
				ignchar();
				unix0(0);
				filter(0);
				continue;
			}
			filename(c);
			rop(c);
			nochng();
			if (inopen && endline && addr1 > zero && addr1 < dol)
				dot = addr1 + 1;
			continue;

		case 's':
			switch (peekchar()) {
			/*
			 * Caution: 2nd char cannot be c, g, or r
			 * because these have meaning to substitute.
			 */

/* set */
			case 'e':
				tail("set");
				setnoaddr();
				set();
				continue;

/* shell */
			case 'h':
				tail("shell");
				setNAEOL();
				vnfl();
				putpad(TE);
				flush();
				unixwt(1, unixex("-i", (char *) 0, 0, 0));
				vcontin(0);
				continue;

/* source */
			case 'o':
#ifdef notdef
				if (inopen)
					goto notinvis;
#endif
				tail("source");
				setnoaddr();
				getone();
				eol();
				source(file, 0);
				continue;
#ifdef SIGTSTP
/* stop, suspend */
			case 't':
				tail("stop");
				goto suspend;
			case 'u':
				tail("suspend");
suspend:
				if (!dosusp)
					error("Old tty driver|Not using new tty driver/shell");
				c = exclam();
				eol();
				if (!c)
					ckaw();
				onsusp(0);
				continue;
#endif

			}
			/* fall into ... */

/* & */
/* ~ */
/* substitute */
		case '&':
		case '~':
			Command = "substitute";
			if (c == 's')
				tail(Command);
			vmacchng(0);
			if (!substitute(c))
				pflag = 0;
			continue;

/* t */
		case 't':
			if (peekchar() == 'a') {
				tail("tag");
				tagfind(exclam());
				if (!inopen)
					lchng = chng - 1;
				else
					nochng();
				continue;
			}
			tail("t");
			vmacchng(0);
			move();
			continue;

		case 'u':
			if (peekchar() == 'n') {
				ignchar();
				switch(peekchar()) {
/* unmap */
				case 'm':
					tail2of("unmap");
					setnoaddr();
					mapcmd(1, 0);
					continue;
/* unabbreviate */
				case 'a':
					tail2of("unabbreviate");
					setnoaddr();
					mapcmd(1, 1);
					anyabbrs = 1;
					continue;
				}
/* undo */
				tail2of("undo");
			} else
				tail("undo");
			setnoaddr();
			markDOT();
			c = exclam();
			ex_newline();
			undo(c);
			continue;

		case 'v':
			switch (peekchar()) {

			case 'e':
/* version */
				tail("version");
				setNAEOL();
				ex_printf("@(#) Version 3.6, 11/3/80"
				    " (4.0BSD).  git "
				    "160803 14:24"
				    +5);
				noonl();
				continue;

/* visual */
			case 'i':
				tail("visual");
				if (inopen) {
					c = 'e';
					goto editcmd;
				}
				vop();
				pflag = 0;
				nochng();
				continue;
			}
/* v */
			tail("v");
			global(0);
			nochng();
			continue;

/* write */
		case 'w':
			c = peekchar();
			tail(c == 'q' ? "wq" : "write");
wq:
			if (skipwh() && peekchar() == '!') {
				pofix();
				ignchar();
				setall();
				unix0(0);
				filter(1);
			} else {
				setall();
				wop(1);
				nochng();
			}
			if (c == 'q')
				goto quit;
			continue;

/* xit */
		case 'x':
			tail("xit");
			if (!chng)
				goto quit;
			c = 'q';
			goto wq;

/* yank */
		case 'y':
			tail("yank");
			c = cmdreg();
			setcount();
			eol();
			vmacchng(0);
			if (c)
				YANKreg(c);
			else
				yank();
			continue;

/* z */
		case 'z':
			zop(0);
			pflag = 0;
			continue;

/* * */
/* @ */
		case '*':
		case '@':
			c = ex_getchar();
			if (c=='\n' || c=='\r')
				ungetchar(c);
			if (any(c, "@*\n\r"))
				c = lastmac;
			if (isupper(c))
				c = tolower(c);
			if (!islower(c))
				error("Bad register");
			ex_newline();
			setdot();
			cmdmac(c);
			continue;

/* | */
		case '|':
			endline = 0;
			goto caseline;

/* \n */
		case '\n':
			endline = 1;
caseline:
			notempty();
			if (addr2 == 0) {
				if (UP != NOSTR && c == '\n' && !inglobal)
					c = CTRL('k');
				if (inglobal)
					addr1 = addr2 = dot;
				else {
					if (dot == dol)
						error("At EOF|At end-of-file");
					addr1 = addr2 = dot + 1;
				}
			}
			setdot();
			nonzero();
			if (seensemi)
				addr1 = addr2;
			ex_getline(*addr1);
			if (c == CTRL('k')) {
				flush1();
				destline--;
				if (hadpr)
					shudclob = 1;
			}
			plines(addr1, addr2, 1);
			continue;

/* " */
		case '"':
			comment();
			continue;

/* # */
		case '#':
numberit:
			setCNL();
			ignorf(setnumb(1));
			pflag = 0;
			goto print;

/* = */
		case '=':
			ex_newline();
			setall();
			if (inglobal == 2)
				pofix();
			ex_printf("%d", lineno(addr2));
			noonl();
			continue;

/* ! */
		case '!':
			if (addr2 != 0) {
				vmacchng(0);
				unix0(0);
				setdot();
				filter(2);
			} else {
				unix0(1);
				pofix();
				putpad(TE);
				flush();
				unixwt(1, unixex("-c", uxb, 0, 0));
				vclrech(1);	/* vcontin(0); */
				nochng();
			}
			continue;

/* < */
/* > */
		case '<':
		case '>':
			for (cnt = 1; peekchar() == c; cnt++)
				ignchar();
			setCNL();
			vmacchng(0);
			shift(c, cnt);
			continue;

/* ^D */
/* EOF */
		case CTRL('d'):
		case EOF:
			if (exitoneof) {
				if (addr2 != 0)
					dot = addr2;
				return;
			}
			if (!isatty(0)) {
				if (intty)
					/*
					 * Chtty sys call at UCB may cause a
					 * input which was a tty to suddenly be
					 * turned into /dev/null.
					 */
					onhup(0);
				return;
			}
			if (addr2 != 0) {
				setlastchar('\n');
				putnl();
			}
			if (dol == zero) {
				if (addr2 == 0)
					putnl();
				notempty();
			}
			ungetchar(EOF);
			zop(hadpr);
			continue;

		default:
			if (!isalpha(c))
				break;
			ungetchar(c);
			tailprim("", 0, 0);
		}
		ierror("What?|Unknown command character '%c'", c);
	}
}
Ejemplo n.º 17
0
/* creates/returns a list of CodecCap based on given filter function and caps */
static GList *
get_plugins_filtered_from_caps (FilterFunc filter,
                                GstCaps *caps,
                                GstPadDirection direction)
{
  GList *walk, *result;
  GList *list = NULL;
  GstCaps *matched_caps = NULL;

  result = gst_registry_get_feature_list (gst_registry_get (),
          GST_TYPE_ELEMENT_FACTORY);

  result = g_list_sort (result, (GCompareFunc) compare_ranks);

  for (walk = result; walk; walk = walk->next)
  {
    GstElementFactory *factory = GST_ELEMENT_FACTORY (walk->data);

    /* Ignore unranked plugins */
    if (gst_plugin_feature_get_rank (GST_PLUGIN_FEATURE (factory)) ==
        GST_RANK_NONE)
      continue;

    if (!filter (factory))
      continue;

    if (caps && !check_caps_compatibility (factory, caps, &matched_caps))
      continue;

    if (!matched_caps)
    {
      list = create_codec_cap_list (factory, direction, list, NULL);
    }
    else
    {
      gint i;
      GPtrArray *capslist = g_ptr_array_new_with_free_func (
        (GDestroyNotify) gst_caps_unref);

      while (gst_caps_get_size (matched_caps) > 0)
      {
        GstCaps *stolencaps = gst_caps_new_full (
          gst_caps_steal_structure (matched_caps, 0), NULL);
        gboolean got_match = FALSE;

        for (i = 0; i < capslist->len; i++)
        {
          GstCaps *intersect = gst_caps_intersect (stolencaps,
              g_ptr_array_index (capslist, i));

          if (gst_caps_is_empty (intersect))
          {
            gst_caps_unref (intersect);
          }
          else
          {
            got_match = TRUE;
            gst_caps_unref (g_ptr_array_index (capslist, i));
            g_ptr_array_index (capslist, i) = intersect;
          }
        }

        if (got_match)
          gst_caps_unref (stolencaps);
        else
          g_ptr_array_add (capslist, stolencaps);

      }
      gst_caps_unref (matched_caps);

      for (i = 0; i < capslist->len; i++)
        list = create_codec_cap_list (factory, direction, list,
            g_ptr_array_index (capslist, i));
      g_ptr_array_unref (capslist);
    }
  }

  gst_plugin_feature_list_free (result);

  return list;
}
Ejemplo n.º 18
0
void array_expression(Array* a, int d, bool& success, Array*& _out, bool* tape__ANONYMOUS_s102/* len = 143 */, int& tape_index__ANONYMOUS_s103) {
  _out = NULL;
  assertion ((d) > (0));;
  bool  c1_s36=0;
  flip(c1_s36, tape__ANONYMOUS_s102, tape_index__ANONYMOUS_s103);
  if ((d) == (1)) {
    success = 1;
    if (c1_s36) {
      Array*  _out_s38=NULL;
      empty_list(_out_s38);
      _out = _out_s38;
      return;
    } else {
      _out = a;
      return;
    }
  }
  bool  c2_s40=0;
  flip(c2_s40, tape__ANONYMOUS_s102, tape_index__ANONYMOUS_s103);
  Array*  lp_s42=NULL;
  bool  array_success=0;
  array_expression(a, d - 1, array_success, lp_s42, tape__ANONYMOUS_s102, tape_index__ANONYMOUS_s103);
  bool  integer_success=0;
  int  z_s44=0;
  integer_expression(a, d - 1, integer_success, z_s44, tape__ANONYMOUS_s102, tape_index__ANONYMOUS_s103);
  bool  cdr_success=0;
  if ((d) > (2)) {
    bool  c3_s46=0;
    flip(c3_s46, tape__ANONYMOUS_s102, tape_index__ANONYMOUS_s103);
    Guard*  g_s48=NULL;
    bool  guard_success=0;
    guard_expression(a, d - 1, guard_success, g_s48, tape__ANONYMOUS_s102, tape_index__ANONYMOUS_s103);
    if ((c1_s36 && c2_s40) && c3_s46) {
      success = 1;
      Array*  _out_s50=NULL;
      empty_list(_out_s50);
      _out = _out_s50;
      return;
    }
    if ((c1_s36 && c2_s40) && !(c3_s46)) {
      success = 1;
      _out = a;
      return;
    }
    if ((c1_s36 && !(c2_s40)) && c3_s46) {
      if (array_success) {
        Array*  r_s52=NULL;
        cdr(lp_s42, cdr_success, r_s52);
        success = cdr_success;
        _out = r_s52;
        return;
      }
      success = 0;
      _out = lp_s42;
      return;
    }
    if ((c1_s36 && !(c2_s40)) && !(c3_s46)) {
      success = integer_success;
      Array*  _out_s54=NULL;
      singleton(z_s44, _out_s54);
      _out = _out_s54;
      return;
    }
    if ((!(c1_s36) && c2_s40) && c3_s46) {
      success = guard_success && array_success;
      Array*  _out_s56=NULL;
      filter(g_s48, lp_s42, _out_s56);
      _out = _out_s56;
      return;
    }
  } else {
    if (c2_s40 && c1_s36) {
      success = 1;
      Array*  _out_s58=NULL;
      empty_list(_out_s58);
      _out = _out_s58;
      return;
    }
    if (c2_s40 && !(c1_s36)) {
      success = 1;
      _out = a;
      return;
    }
    if (!(c2_s40) && c1_s36) {
      if (array_success) {
        Array*  r_s60=NULL;
        cdr(lp_s42, cdr_success, r_s60);
        success = cdr_success;
        _out = r_s60;
        return;
      }
      success = 0;
      _out = lp_s42;
      return;
    }
    if (!(c2_s40) && !(c1_s36)) {
      success = integer_success;
      Array*  _out_s62=NULL;
      singleton(z_s44, _out_s62);
      _out = _out_s62;
      return;
    }
  }
  assertion (0);;
}
Ejemplo n.º 19
0
WRAP_API void
wrap_filter(void)
{
	filter();
}
Ejemplo n.º 20
0
static void bandpass_filter(int16_t *samples)
{
    static int16_t history[BANDPASS_COUNT + SAMPLES_PER_ITER];
    filter(samples, BANDPASS_COEFFS, BANDPASS_COUNT, history);
}
Ejemplo n.º 21
0
int main(void)
{
  std::cout << "Hamming distance: " << hamming("ACCAGGG", "ACTATGG") << std::endl;

  std::vector<int> v = {1,3,5,67,33,56,44,45,67,76,67,789};

  Functions fnc;

  fnc(   from({9,8,7,6,5,4,3,2,1,0})
     ,   map([](int i){ return i*i;})
     ,   filter(_ > 5)
     ,   foreach([](int i){std::cout << i << " ";})
     );
    // std::cout << "------\n";
    // _(   Range(1000)
    //  ,   Filter([](int i) {return (i % 2) == 0;})
    //  ,   Take(20)
    //  ,   Map([](int i){return i+i;})
    //  ,   ForEach([](int i){std::cout << i << "\n";})
    //  );
    // std::cout << "------\n";
    // _(   Range()
    //  ,   Zip(From(v))
    //  ,   Zip(Range(100))
    //  ,   ForEach([](std::tuple<int, int, int>&& v){std::cout << std::get<0>(v) << ":" << std::get<1>(v) << ":" << std::get<2>(v) << "\n";})
    //  );
    // std::cout << "------\n";
    // _(   From({A{2000}, A{3}})
    //  ,   Map(&A::value)
    //  ,   Filter([](int i){return i > 10;})
    //  ,   ForEach([](int i){std::cout << i << "\n";})
    //  );
    // std::cout << "------\n";
    // _(   From({A{2000}, A{3}})
    //  ,   Map(&A::x)
    //  ,   Filter([](int i){return i > 10;})
    //  ,   ForEach([](int i){std::cout << i << "\n";})
    //  );
    // std::cout << "------\n";
    // _(   Range(1000)
    //  ,   Drop(998)
    //  ,   ForEach([](int i){std::cout << i << "\n";})
    //  );
    //  std::cout << "------\n";
    //  _(   Range(10, 0)
    //   ,   Take(14)
    //   ,   ForEach([](int i){std::cout << i << "\n";})
    //   );
    //
    // std::cout << "------\n";
    // int sum = _(   Range(5)
    //            ,   Reduce(0, [](int a, int b){ return a + b;})
    //            );
    // std::cout << "Sum is: " << sum << "\n";
    // std::cout << "------\n";

    size_t perfCount = 100000000;

    boost::timer tm;

    std::vector<int> tv;
    int c = 0;
    for(size_t i = 0; i < perfCount; ++i)
    {
        int v = i * i;
        if(i < perfCount/2 && v%2)
        {
            tv.emplace_back(v);
        }
        ++c;
    };
    std::cout << "\n------\n";
    std::cout << "Raw: " << tm.elapsed() << "\n";

    std::cout << "------\n";

    tm.restart();

    fnc( range(perfCount)
        , map([](int i) {return i * i;})
        , filter([](int i){ return i % 2;})
        , drop(perfCount/2)
        , into<std::vector<int>>()
        );

    std::cout << "blue-fnc: " << tm.elapsed() << "\n";

    // auto sample = []()
    // {
    //     double x = (double)rand() / RAND_MAX;
    //     double y = (double)rand() / RAND_MAX;
    //     return (x*x + y*y) < 1 ? 1 : 0;
    // };
    //
    // const int numSamples = 1000000;
    // auto count = _( Range(numSamples)
    //               , Map([sample](int){ return sample();})
    //               , Reduce(0, [](int a, int b){ return a + b;})
    //               );
    //
    // std::cout << "Pi: " << 4.0 * (double) count / (double) numSamples << "\n";

    return EXIT_SUCCESS;
}
Ejemplo n.º 22
0
static void lowpass_filter(int16_t *samples)
{
    static int16_t history[LOWPASS_COUNT + SAMPLES_PER_ITER];
    filter(samples, LOWPASS_COEFFS, LOWPASS_COUNT, history);
}
Ejemplo n.º 23
0
void ModelStateDialog::SetStateInfo(Model *cls, std::map< std::string, std::map<std::string, std::string> > &finfo) {
    NodeRangeGrid->SetColSize(COLOUR_COL, 50);
    SingleNodeGrid->SetColSize(COLOUR_COL, 50);
    NameChoice->Clear();
    model = cls;
    modelPreview->SetModel(cls);

    for (std::map< std::string, std::map<std::string, std::string> >::iterator it = finfo.begin();
         it != finfo.end(); it++) {

        std::string name = it->first;
        std::map<std::string, std::string> &info = it->second;

        NameChoice->Append(name);

        std::string type2 = info["Type"];
        if (type2 == "") {
            //old style, map
            if (name == "Coro" || name == "SingleNode") {
                info["Type"] = "SingleNode";
            } else if (name == "NodeRange") {
                info["Type"] = "NodeRange";
            }
        }

        stateData[name] = info;
    }

    if (NameChoice->GetCount() > 0) {
        DeleteButton->Enable();
        StateTypeChoice->Enable();
        NameChoice->SetSelection(0);
        SelectStateModel(NameChoice->GetString(NameChoice->GetSelection()).ToStdString());
    } else {
        DeleteButton->Disable();
        StateTypeChoice->Disable();
    }

    wxArrayString names;
    names.push_back("");
    for (size_t x = 0; x < cls->GetNodeCount(); x++) {
        wxString nn = cls->GetNodeName(x, true);
        names.push_back(nn);
    }

    for (int x = 0; x < SingleNodeGrid->GetNumberRows(); x++) {
        wxGridCellTextEditor *neditor = new wxGridCellTextEditor();
        wxString nfilter("abcdefghijklmnopqrstuvwxyz0123456789-_/\\|");
        wxTextValidator nvalidator(wxFILTER_INCLUDE_CHAR_LIST);
        nvalidator.SetCharIncludes(nfilter);
        neditor->SetValidator(nvalidator);

        NodesGridCellEditor *editor = new NodesGridCellEditor();
        editor->names = names;

        SingleNodeGrid->SetCellEditor(x, NAME_COL, neditor);
        SingleNodeGrid->SetCellEditor(x, CHANNEL_COL, editor);
        SingleNodeGrid->SetReadOnly(x, COLOUR_COL);
    }

    for (int x = 0; x < NodeRangeGrid->GetNumberRows(); x++) {
        wxGridCellTextEditor *reditor = new wxGridCellTextEditor();
        wxString filter("0123456789,-");
        wxTextValidator validator(wxFILTER_INCLUDE_CHAR_LIST);
        validator.SetCharIncludes(filter);
        reditor->SetValidator(validator);

        wxGridCellTextEditor *neditor2 = new wxGridCellTextEditor();
        wxString nfilter2("abcdefghijklmnopqrstuvwxyz0123456789-_/\\|");
        wxTextValidator nvalidator2(wxFILTER_INCLUDE_CHAR_LIST);
        nvalidator2.SetCharIncludes(nfilter2);
        neditor2->SetValidator(nvalidator2);

        NodeRangeGrid->SetCellEditor(x, NAME_COL, neditor2);
        NodeRangeGrid->SetCellEditor(x, CHANNEL_COL, reditor);
        NodeRangeGrid->SetReadOnly(x, COLOUR_COL);
    }

    ValidateWindow();
}
Ejemplo n.º 24
0
int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *ntptr, uint32_t *timing) 
{
	// variables
	int len;	
	uint32_t pos;
	uint8_t tmp4[4];
	uint8_t par[1] = {0x00};
	byte_t nr[4];
	uint32_t nt, ntpp; // Supplied tag nonce
	
	uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
	uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];
	uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];
	
	// Transmit MIFARE_CLASSIC_AUTH
	len = mifare_sendcmd_short(pcs, isNested, 0x60 + (keyType & 0x01), blockNo, receivedAnswer, receivedAnswerPar, timing);
	if (MF_DBGLEVEL >= 4)	Dbprintf("rand tag nonce len: %x", len);  
	if (len != 4) return 1;
	
	// "random" reader nonce:
	nr[0] = 0x55;
	nr[1] = 0x41;
	nr[2] = 0x49;
	nr[3] = 0x92; 
	
	// Save the tag nonce (nt)
	nt = bytes_to_num(receivedAnswer, 4);

	//  ----------------------------- crypto1 create
	if (isNested)
		crypto1_destroy(pcs);

	// Init cipher with key
	crypto1_create(pcs, ui64Key);

	if (isNested == AUTH_NESTED) {
		// decrypt nt with help of new key 
		nt = crypto1_word(pcs, nt ^ uid, 1) ^ nt;
	} else {
		// Load (plain) uid^nt into the cipher
		crypto1_word(pcs, nt ^ uid, 0);
	}

	// some statistic
	if (!ntptr && (MF_DBGLEVEL >= 3))
		Dbprintf("auth uid: %08x nt: %08x", uid, nt);  
	
	// save Nt
	if (ntptr)
		*ntptr = nt;

	// Generate (encrypted) nr+parity by loading it into the cipher (Nr)
	par[0] = 0;
	for (pos = 0; pos < 4; pos++)
	{
		mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos];
		par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos));
	}	
		
	// Skip 32 bits in pseudo random generator
	nt = prng_successor(nt,32);

	//  ar+parity
	for (pos = 4; pos < 8; pos++)
	{
		nt = prng_successor(nt,8);
		mf_nr_ar[pos] = crypto1_byte(pcs,0x00,0) ^ (nt & 0xff);
		par[0] |= (((filter(pcs->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7-pos));
	}	
		
	// Transmit reader nonce and reader answer
	ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);

	// Receive 4 byte tag answer
	len = ReaderReceive(receivedAnswer, receivedAnswerPar);
	if (!len)
	{
		if (MF_DBGLEVEL >= 1)	Dbprintf("Authentication failed. Card timeout.");
		return 2;
	}
	
	memcpy(tmp4, receivedAnswer, 4);
	ntpp = prng_successor(nt, 32) ^ crypto1_word(pcs, 0,0);
	
	if (ntpp != bytes_to_num(tmp4, 4)) {
		if (MF_DBGLEVEL >= 1)	Dbprintf("Authentication failed. Error card response.");
		return 3;
	}

	return 0;
}
Ejemplo n.º 25
0
//------------------------------------------------------------------------------
// Purpose : Draw attack beam and do damage / decals
// Input   :
// Output  :
//------------------------------------------------------------------------------
void CNPC_Stalker::DrawAttackBeam(void)
{
	if (!m_pBeam)
		return;

	// ---------------------------------------------
	//	Get beam end point
	// ---------------------------------------------
	Vector vecSrc = LaserStartPosition(GetAbsOrigin());
	trace_t tr;
	AI_TraceLine( vecSrc, vecSrc + m_vLaserDir * MAX_STALKER_FIRE_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr);

	CalcBeamPosition();

	bool bInWater = (UTIL_PointContents ( tr.endpos, MASK_WATER ) & MASK_WATER)?true:false;
	// ---------------------------------------------
	//	Update the beam position
	// ---------------------------------------------
	m_pBeam->SetStartPos( tr.endpos );
	m_pBeam->RelinkBeam();

	Vector vAttachPos;
	GetAttachment(STALKER_LASER_ATTACHMENT,vAttachPos);

	Vector vecAimDir = tr.endpos - vAttachPos;
	VectorNormalize( vecAimDir );

	SetAim( vecAimDir );

	// --------------------------------------------
	//  Play burn sounds
	// --------------------------------------------
	CBaseCombatCharacter *pBCC = ToBaseCombatCharacter( tr.m_pEnt );
	if (pBCC)
	{
		if (gpGlobals->curtime > m_fNextDamageTime)
		{
			ClearMultiDamage();

			float damage = 0.0;
			switch (m_eBeamPower)
			{
				case STALKER_BEAM_LOW:
					damage = 1;
					break;
				case STALKER_BEAM_MED:
					damage = 3;
					break;
				case STALKER_BEAM_HIGH:
					damage = 10;
					break;
			}

			CTakeDamageInfo info( this, this, damage, DMG_SHOCK );
			CalculateMeleeDamageForce( &info, m_vLaserDir, tr.endpos );
			pBCC->DispatchTraceAttack( info, m_vLaserDir, &tr );
			ApplyMultiDamage();
			m_fNextDamageTime = gpGlobals->curtime + 0.1;
		}
		if (pBCC->Classify()!=CLASS_BULLSEYE)
		{
			if (!m_bPlayingHitFlesh)
			{
				CPASAttenuationFilter filter( m_pBeam,"NPC_Stalker.BurnFlesh" );
				filter.MakeReliable();

				EmitSound( filter, m_pBeam->entindex(),"NPC_Stalker.BurnFlesh" );
				m_bPlayingHitFlesh = true;
			}
			if (m_bPlayingHitWall)
			{
				StopSound( m_pBeam->entindex(), "NPC_Stalker.BurnWall" );
				m_bPlayingHitWall = false;
			}

			tr.endpos.z -= 24.0f;
			if (!bInWater)
			{
				DoSmokeEffect(tr.endpos + tr.plane.normal * 8);
			}
		}
	}
	
	if (!pBCC || pBCC->Classify()==CLASS_BULLSEYE)
	{
		if (!m_bPlayingHitWall)
		{
			CPASAttenuationFilter filter( m_pBeam, "NPC_Stalker.BurnWall" );
			filter.MakeReliable();

			EmitSound( filter, m_pBeam->entindex(), "NPC_Stalker.BurnWall" );
			m_bPlayingHitWall = true;
		}
		if (m_bPlayingHitFlesh)
		{
			StopSound(m_pBeam->entindex(), "NPC_Stalker.BurnFlesh" );
			m_bPlayingHitFlesh = false;
		}

		UTIL_DecalTrace( &tr, "RedGlowFade");
		UTIL_DecalTrace( &tr, "FadingScorch" );
		
		tr.endpos.z -= 24.0f;
		if (!bInWater)
		{
			DoSmokeEffect(tr.endpos + tr.plane.normal * 8);
		}
	}

	if (bInWater)
	{
		UTIL_Bubbles(tr.endpos-Vector(3,3,3),tr.endpos+Vector(3,3,3),10);
	}

	/*
	CBroadcastRecipientFilter filter;
	TE_DynamicLight( filter, 0.0, EyePosition(), 255, 0, 0, 5, 0.2, 0 );
	*/
}
Ejemplo n.º 26
0
//------------------------------------------------------------------------------
// Purpose: Accepts damage and breaks if health drops below zero.
//------------------------------------------------------------------------------
void CBreakableSurface::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator )
{
    //=============================================================================
    // HPE_BEGIN:
    // [dwenger] Window break stat tracking
    //=============================================================================

    // Make sure this pane has not already been shattered
    bool bWasBroken = m_bIsBroken;

    //=============================================================================
    // HPE_END
    //=============================================================================

	// Decrease health
	m_iHealth -= info.GetDamage();
	m_OnHealthChanged.Set( m_iHealth, info.GetAttacker(), this );

	// If I'm not broken yet, break me
	if (!m_bIsBroken )
	{
		Vector vSurfDir = ptr->endpos - ptr->startpos;
		Die( info.GetAttacker(), vSurfDir );
	}

	if (info.GetDamageType() & (DMG_BULLET | DMG_CLUB))
	{
		// Figure out which panel has taken the damage and break it
		float flWidth,flHeight;
		PanePos(ptr->endpos,&flWidth,&flHeight);
		int nWidth  = flWidth;
		int nHeight = flHeight;
		
		if ( ShatterPane(nWidth, nHeight,vecDir*500,ptr->endpos) )
		{
            //=============================================================================
            // HPE_BEGIN:
            // [dwenger] Window break stat tracking
            //=============================================================================

            CBasePlayer* pAttacker = ToBasePlayer(info.GetAttacker());
            if ( ( pAttacker ) && ( !bWasBroken ) )
            {
                gamestats->Event_WindowShattered( pAttacker );
            }

            //=============================================================================
            // HPE_END
            //=============================================================================

			// Do an impact hit
			CEffectData	data;

			data.m_vNormal = ptr->plane.normal;
			data.m_vOrigin = ptr->endpos;

			CPASFilter filter( data.m_vOrigin );

			// client cannot trace against triggers
			filter.SetIgnorePredictionCull( true );

			te->DispatchEffect( filter, 0.0, data.m_vOrigin, "GlassImpact", data );
		}

		if (m_nSurfaceType == SHATTERSURFACE_GLASS)
		{
			// Break nearby panes if damages was near pane edge
			float flWRem = flWidth  - nWidth;
			float flHRem = flHeight - nHeight;

			if (flWRem > 0.8 && nWidth != m_nNumWide-1)
			{
				ShatterPane(nWidth+1, nHeight,vecDir*500,ptr->endpos);
			}
			else if (flWRem < 0.2 && nWidth != 0)
			{
				ShatterPane(nWidth-1, nHeight,vecDir*500,ptr->endpos);
			}
			if (flHRem > 0.8 && nHeight != m_nNumHigh-1)
			{
				ShatterPane(nWidth, nHeight+1,vecDir*500,ptr->endpos);
			}
			else if (flHRem < 0.2 && nHeight != 0)
			{
				ShatterPane(nWidth, nHeight-1,vecDir*500,ptr->endpos);
			}

			// Occasionally break the pane above me
			if (random->RandomInt(0,1)==0)
			{
				ShatterPane(nWidth, nHeight+1,vecDir*1000,ptr->endpos);
				// Occasionally break the pane above that
				if (random->RandomInt(0,1)==0)
				{
					ShatterPane(nWidth, nHeight+2,vecDir*1000,ptr->endpos);
				}		
			}
		}
	}
	else if (info.GetDamageType() & (DMG_SONIC | DMG_BLAST))
	{
		// ----------------------------------------
		// If it's tile blow out nearby tiles
		// ----------------------------------------
		if (m_nSurfaceType == SHATTERSURFACE_TILE)
		{
			// Figure out which panel has taken the damage and break it
			float flWidth,flHeight;
			if (info.GetAttacker())
			{
				PanePos(info.GetAttacker()->GetAbsOrigin(),&flWidth,&flHeight);
			}
			else
			{
				PanePos(ptr->endpos,&flWidth,&flHeight);
			}
			int nWidth  = flWidth;
			int nHeight = flHeight;

			// Blow out a roughly circular patch of tile with some randomness
			for (int width =nWidth-4;width<nWidth+4;width++)
			{
				for (int height =nHeight-4;height<nHeight+4;height++)
				{
					if ((abs(nWidth-width)+abs(nHeight-height))<random->RandomInt(2,5))
					{
						ShatterPane(width, height,vecDir*500,ptr->endpos);
					}
				}
			}
		}
		// ----------------------------------------
		// If it's glass blow out the whole window
		// ----------------------------------------
		else
		{
            //=============================================================================
            // HPE_BEGIN:
            // [pfreese] Window break stat tracking
            //=============================================================================

            CBasePlayer* pAttacker = ToBasePlayer(info.GetAttacker());
            if ( ( pAttacker ) && ( !bWasBroken ) )
            {
                gamestats->Event_WindowShattered( pAttacker );
            }

            //=============================================================================
            // HPE_END
            //=============================================================================

			float flDot = DotProduct(m_vNormal,vecDir);

#ifdef CSTRIKE_DLL
			float damageMultiplier = info.GetDamage();
#else
			float damageMultiplier = 1.0f;
#endif

			Vector vBlastDir;
			if (flDot > 0)
			{
				vBlastDir = damageMultiplier * 3000 * m_vNormal;
			}
			else
			{
				vBlastDir = damageMultiplier * -3000 * m_vNormal;
			}

			// Has the window already been destroyed?
			if (m_nNumBrokenPanes >= m_nNumWide*m_nNumHigh)
			{
				return;
			}
			// ---------------------------------------------------------------
			// If less than 10% of my panels have been broken, blow me 
			// up in one large glass shatter
			// ---------------------------------------------------------------
			else if ( m_nNumBrokenPanes < 0.1*(m_nNumWide*m_nNumHigh))
			{
				QAngle vAngles;
				VectorAngles(-1*m_vNormal,vAngles);

				CreateShards(m_vCorner, vAngles,vBlastDir, ptr->endpos, 
							m_nNumWide*m_flPanelWidth, m_nNumHigh*m_flPanelHeight, WINDOW_LARGE_SHARD_SIZE);
			}
			// ---------------------------------------------------------------
			// Otherwise break in the longest vertical strips possible
			// (to cut down on the network bandwidth)
			// ---------------------------------------------------------------
			else
			{
				QAngle vAngles;
				VectorAngles(-1*m_vNormal,vAngles);
				Vector vWidthDir,vHeightDir;
				AngleVectors(vAngles,NULL,&vWidthDir,&vHeightDir);

				for (int width=0;width<m_nNumWide;width++)
				{
					int height;
					int nHCount = 0;
					for ( height=0;height<m_nNumHigh;height++)
					{
						// Keep count of how many panes
						if (!IsBroken(width,height))
						{
							nHCount++;
						}
						// Shatter the strip and start counting again
						else if (nHCount > 0)
						{
							Vector vBreakPos = m_vCorner + 
													(width*vWidthDir*m_flPanelWidth) + 
													((height-nHCount)*vHeightDir*m_flPanelHeight);

							CreateShards(vBreakPos, vAngles,
								 vBlastDir,	  ptr->endpos,
								 m_flPanelWidth, nHCount*m_flPanelHeight,
								 WINDOW_LARGE_SHARD_SIZE);

							nHCount = 0;
						}
					}
					if (nHCount)
					{
						Vector vBreakPos = m_vCorner + 
												(width*vWidthDir*m_flPanelWidth) + 
												((height-nHCount)*vHeightDir*m_flPanelHeight);

						CreateShards(vBreakPos, vAngles,
								 vBlastDir,	  ptr->endpos,
								 m_flPanelWidth,nHCount*m_flPanelHeight,
								 WINDOW_LARGE_SHARD_SIZE);
					}
				}
			}

			BreakAllPanes();
		}
	}
}
Ejemplo n.º 27
0
void DocbookDocVisitor::visitPre(DocRef *ref)
{
  if (m_hide) return;
  if (!ref->file().isEmpty()) startLink(ref->file(),ref->anchor());
  if (!ref->hasLinkText()) filter(ref->targetTitle());
}
Ejemplo n.º 28
0
//-----------------------------------------------------------------------------
// Purpose: Hook for the sound system to tell us when a sound's been played
//-----------------------------------------------------------------------------
MicrophoneResult_t CEnvMicrophone::SoundPlayed( int entindex, const char *soundname, soundlevel_t soundlevel, float flVolume, int iFlags, int iPitch, const Vector *pOrigin, float soundtime, CUtlVector< Vector >& soundorigins )
{
	if ( m_bAvoidFeedback )
		return MicrophoneResult_Ok;

	// Don't hear sounds that have already been heard by a microphone to avoid feedback!
	if ( iFlags & SND_SPEAKER )
		return MicrophoneResult_Ok;

#ifdef DEBUG_MICROPHONE
	Msg("%s heard %s: ", STRING(GetEntityName()), soundname );
#endif

	if ( !CanHearSound( entindex, soundlevel, flVolume, pOrigin ) )
		return MicrophoneResult_Ok;

	// We've heard it. Play it out our speaker. If our speaker's gone away, we're done.
	if ( !m_hSpeaker )
	{
		// First time, find our speaker. Done here, because finding it in Activate() wouldn't
		// find players, and we need to be able to specify !player for a speaker.
		if ( m_iszSpeakerName != NULL_STRING )
		{
			m_hSpeaker = gEntList.FindEntityByName(NULL, STRING(m_iszSpeakerName) );

			if ( !m_hSpeaker )
			{
				Warning( "EnvMicrophone %s specifies a non-existent speaker name: %s\n", STRING(GetEntityName()), STRING(m_iszSpeakerName) );
				m_iszSpeakerName = NULL_STRING;
			}
		}

		if ( !m_hSpeaker )
		{
			return MicrophoneResult_Remove;
		}
	}

	m_bAvoidFeedback = true;

	// Add the speaker flag. Detected at playback and applies the speaker filter.
	iFlags |= SND_SPEAKER;
	CPASAttenuationFilter filter( m_hSpeaker );

	EmitSound_t ep;
	ep.m_nChannel = CHAN_STATIC;
	ep.m_pSoundName = soundname;
	ep.m_flVolume = flVolume;
	ep.m_SoundLevel = soundlevel;
	ep.m_nFlags = iFlags;
	ep.m_nPitch = iPitch;
	ep.m_pOrigin = &m_hSpeaker->GetAbsOrigin();
	ep.m_flSoundTime = soundtime;
	ep.m_nSpeakerEntity = entindex;

	CBaseEntity::EmitSound( filter, m_hSpeaker->entindex(), ep );

	Q_strncpy( m_szLastSound, soundname, sizeof(m_szLastSound) );
	m_OnRoutedSound.FireOutput( this, this, 0 );

	m_bAvoidFeedback = false;

	// Copy emitted origin to soundorigins array
	for ( int i = 0; i < ep.m_UtlVecSoundOrigin.Count(); ++i )
	{
		soundorigins.AddToTail( ep.m_UtlVecSoundOrigin[ i ] );
	}

	// Do we want to allow the original sound to play?
	if ( m_spawnflags & SF_MICROPHONE_SWALLOW_ROUTED_SOUNDS )
	{
		return MicrophoneResult_Swallow;
	}

	return MicrophoneResult_Ok;
}
Ejemplo n.º 29
0
void DocbookDocVisitor::visit(DocWord *w)
{
  if (m_hide) return;
  filter(w->word());
}
Ejemplo n.º 30
0
QGalleryMetaDataFilter QGalleryMetaDataFilter::operator !() const
{
    QGalleryMetaDataFilter filter(*this);
    filter.setNegated(!d->negated);
    return filter;
}