示例#1
3
nmethod* cacheProbingLookup::findMethodToReuse() {
  if ( !mightBeAbleToReuseNMethod() )
    return (nmethod*)cannotReuse;

  // build key for canonical method
  
  oop resultMH= result()->methodHolder_or_map(receiver);
  mapOop resultMHmapOop= 
    resultMH->is_map() ? mapOop(resultMH) : resultMH->map()->enclosing_mapOop();
  MethodLookupKey ck( NormalLookupType, MH_NOT_A_RESEND, resultMHmapOop, selector(), 0);
  canonical_key= ck; // copy info 

  nmethod* nm= Memory->code->lookup(canonical_key, needDebug);
  if ( nm &&  nm->reusable() )
    return nm;
  return (nmethod*)
         (shouldCompileReusableNMethod( nm) ? compileAndReuse : cannotReuse);
}
示例#2
0
int main(){
    scanf("%s",in);
    long long n = strlen(in);
    if(n==1){
        printf("0");
        return 0;
    }
    n--;
    if(ck(in[0])){
        h[0]=1;
        l[0]=0;
    }else{
        h[0]=0;
        l[0]=1;
    }
    for(long long i=1;in[i];++i){
        if(ck(in[i])){
            h[i]=h[i-1]+1;
            l[i]=l[i-1];
        }else{
            h[i]=h[i-1];
            l[i]=l[i-1]+1;
        }
        n=i;
    }
    long long ans=h[n];
    for(long long i=0;in[i];i++){
        ans = min(ans,l[i]+(h[n]-h[i+1]));
    }
    printf("%I64d",ans);
}
示例#3
0
static err_t inner_decode(buf_t *in, void *out) {
  struct inner *x = (struct inner*)out;

  vomControl ctl = controlNone;
  uint64_t index;

  while (true) {
    err_t err = decodeVar128(in, &index, &ctl); ck();
    if (ctl == controlEnd) {
      return ERR_OK;
    }
    if (ctl != controlNone) {
      // unexpected control message here
      err = ERR_DECVOM; ck();
    }

    switch (index) {
    case 0:
      err = decodeString(in, &x->String); ck();
      break;
    default:
      err = ERR_DECVOM; ck();      
    }
  }
}
示例#4
0
int range(Node p, int lo, int hi) {
	Symbol s = p->syms[0];

	switch (specific(p->op)) {
	case ADDRF+P:
	case ADDRL+P: ck(s->x.offset >= lo && s->x.offset <= hi);
	case CNST+I:  ck(s->u.c.v.i  >= lo && s->u.c.v.i  <= hi);
	case CNST+U:  ck(s->u.c.v.u  >= lo && s->u.c.v.u  <= hi);
	case CNST+P:  ck(s->u.c.v.p  == 0  && lo <= 0 && hi >= 0);
	}
	return LBURG_MAX;
}
示例#5
0
void idlefunc()
{
   int x , y    ;
   int fire = 0 ;
   //
   if( pause ) return ;
   //
   // first...
   //
   for( x = 0 ; x < N ; x++ )
   {
      for( y = 0 ; y < N ; y++ )
      { 
         if( t[y][x] == FIRE )
         {
            ck( y - 1 , x     ) ;
            ck( y + 1 , x     ) ;
            ck( y     , x - 1 ) ;
            ck( y     , x + 1 ) ;
         } 
      } 
   } 
   //
   // second...
   //
   for( x = 0 ; x < N ; x++ )
   {
      for( y = 0 ; y < N ; y++ )
      { 
         if( t[y][x] == FIRE )
         {
            t[y][x] = BURNT ;
         } 
         else if( t[y][x] == SPARK )
         {
            fire = 1;
            //
            t[y][x] = FIRE ;
         } 
      } 
   } 
   //
   if( fire )
   {
      ++step ;
      //
      glutPostRedisplay(); // calls displayfunc
   }
}
示例#6
0
int wb_dbms::del_family(wb_dbms_txn *txn, wb_dbms_cursor *cp, pwr_tOid poid)
{
    int ret = 0;
#if 0
    dbName name;
    name.poid = poid;
    name.normname = "";
    pwr_tOid oid = 0;

    FamilyKey  nk(po, );
    FamiltData nd(&oid, sizeof(oid));
    wb_dbms_cursor *ncp;
    cp->dup(*ncp, 0);

    while ((ret = cp->get(&nk, &nd, DB_NEXT)) != DB_NOTFOUND) {
        del_family(txn, ncp, oid);
        cp->del();
        oh_k ok(nd);
        oh_d od();
        m_dbms_ohead->get(txn, &ok, &od, 0);
        wb_DbClistK ck(od);
        m_db_class->del(txn, &ck, 0);
        wb_DbBodyK bk(od);
        m_db_obody->del(txn, &bk, 0);
        m_db_ohead->del(txn, &ok, 0);
    }
    ncp->close();

    ret = m_db_name->del(txn, &key, 0);
#endif
    return ret;
}
示例#7
0
int main()
{
        knob_ctl_img kc(1350, 512, 20, 20);
        number_writer nw(kc, 100, 200, 24, 20);
        mudd_hacks::clock ck(nw);
        
        ck.run();
}
void locDynOneEqEddy::updateSubGridScaleFields
(
    const volSymmTensorField& D,
    const volScalarField& KK
)
{
    nuSgs_ = ck(D, KK)*sqrt(k_)*delta();
    nuSgs_.correctBoundaryConditions();
}
示例#9
0
IGL_INLINE void igl::GeneralPolyVectorFieldFinder<DerivedV, DerivedF>::getGeneralCoeffConstraints(const Eigen::VectorXi &isConstrained,
                                                       const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
                                                       int k,
                                                       const Eigen::VectorXi &rootsIndex,
                                                       Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> &Ck)
{
  int numConstrained = isConstrained.sum();
  Ck.resize(numConstrained,1);
  // int n = rootsIndex.cols();

  Eigen::MatrixXi allCombs;
  {
    Eigen::VectorXi V = Eigen::VectorXi::LinSpaced(n,0,n-1);
    igl::nchoosek(V,k+1,allCombs);
  }

  int ind = 0;
  for (int fi = 0; fi <numF; ++fi)
  {
    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = B1.row(fi);
    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = B2.row(fi);
    if(isConstrained[fi])
    {
      std::complex<typename DerivedV::Scalar> ck(0);

      for (int j = 0; j < allCombs.rows(); ++j)
      {
        std::complex<typename DerivedV::Scalar> tk(1.);
        //collect products
        for (int i = 0; i < allCombs.cols(); ++i)
        {
          int index = allCombs(j,i);

          int ri = rootsIndex[index];
          Eigen::Matrix<typename DerivedV::Scalar, 1, 3> w;
          if (ri>0)
            w = cfW.block(fi,3*(ri-1),1,3);
          else
            w = -cfW.block(fi,3*(-ri-1),1,3);
          typename DerivedV::Scalar w0 = w.dot(b1);
          typename DerivedV::Scalar w1 = w.dot(b2);
          std::complex<typename DerivedV::Scalar> u(w0,w1);
          tk*= u;
        }
        //collect sum
        ck += tk;
      }
      Ck(ind) = ck;
      ind ++;
    }
  }


}
示例#10
0
static err_t testStruct_decode(buf_t *in, void *out) {
  struct testStruct *x = (struct testStruct *)out;

  vomControl ctl = controlNone;
  uint64_t index;

  while (true) {
    err_t err = decodeVar128(in, &index, &ctl); ck();
    if (ctl == controlEnd) {
      return ERR_OK;
    }
    if (ctl != controlNone) {
      // unexpected control message here
      err = ERR_DECVOM; ck();
    }

    switch (index) {
    case 0:
      err = decodeInt(in, &x->A); ck();
      break; 
    case 1:
      err = decodeDouble(in, &x->B); ck();
      break;
    case 2:
      err = inner_decode(in, &x->Inner); ck();
      break;
    default:
      // unexpected index number.
      err = ERR_DECVOM; ck();
    }
  }

  return ERR_OK;
};
示例#11
0
void CComGeneralClass::Register() {
#if UCFG_EXTENDED
	String moduleName = AfxGetModuleState()->FileName;
	String sClsid = StringFromCLSID(m_clsid);
	String sDesc;
	sDesc.Load(m_descID);
	if (!m_progID.IsEmpty()) {
		RegistryKey key(HKEY_CLASSES_ROOT, m_progID);
		key.SetValue("", sDesc);
		RegistryKey ck(key, "CLSID");
		ck.SetValue("", sClsid);
	}
	if (m_progID != m_indProgID) {
		RegistryKey key(HKEY_CLASSES_ROOT, m_indProgID);
		key.SetValue("", sDesc);
		RegistryKey ck(key, "CLSID");
		ck.SetValue("", sClsid);
	}
	RegistryKey key(HKEY_CLASSES_ROOT, "CLSID\\"+sClsid);
	key.SetValue("", sDesc);
	RegistryKey(key, "ProgID").SetValue("", m_progID);
	if (m_progID != m_indProgID)
		RegistryKey(key, "VersionIndependentProgID").SetValue("", m_indProgID);
	if (AfxGetModuleState()->m_hCurrentInstanceHandle == GetModuleHandle(0)) {
		RegistryKey lsk(key, "LocalServer32");
		lsk.SetValue("", moduleName);
	} else {
		RegistryKey isk(key, "InprocServer32");
		isk.SetValue("", moduleName);
		String tm;
		if (m_flags & THREADFLAGS_BOTH)
			tm = "both";
		else if (m_flags & THREADFLAGS_APARTMENT)
			tm = "Apartment";
		if (!tm.IsEmpty())
			isk.SetValue("ThreadingModel", tm);
	}
#endif
}
示例#12
0
static void
irt_rpf_mdim_nrm_rescale(const double *spec, double *param, const int *paramMask,
			 const double *mean, const double *cov)
{
  int numDims = spec[RPF_ISpecDims];
  int nzeta = spec[RPF_ISpecOutcomes] - 1;
  double *alpha = param + numDims;
  double *gamma = param + numDims + nzeta;
  const double *Ta  = spec + RPF_ISpecCount;
  const double *Tc  = spec + RPF_ISpecCount + nzeta * nzeta;
  const double *iTc = spec + RPF_ISpecCount + 3 * nzeta * nzeta;

  double madj = dotprod(param, mean, numDims);

  for (int d1=0; d1 < numDims; d1++) {
    if (paramMask[d1] < 0) continue;
    param[d1] = dotprod(param+d1, cov + d1 * numDims + d1, numDims-d1);
  }

  Eigen::VectorXd ak(nzeta);
  ak.setZero();
  Eigen::VectorXd ck(nzeta);
  ck.setZero();

  for (int kx=0; kx < nzeta; kx++) {
    for (int tx=0; tx < nzeta; tx++) {
      int Tcell = tx * nzeta + kx;
      ak[kx] += Ta[Tcell] * alpha[tx];
      ck[kx] += Tc[Tcell] * gamma[tx];
    }
  }

  for (int kx=0; kx < nzeta; kx++) {
    ck[kx] += madj * ak[kx];
  }

  for (int kx=0; kx < nzeta; kx++) {
    int px = numDims + nzeta + kx;
    if (paramMask[px] < 0) continue;

    param[px] = 0;

    for (int tx=0; tx < nzeta; tx++) {
      int Tcell = tx * nzeta + kx;
      param[px] += iTc[Tcell] * ck[tx];
    }
  }
}
示例#13
0
文件: a.c 项目: bitchbitch/ACM-ICPC
int main(){

   //freopen("/home/plac/problem/input.txt","r",stdin);
   //freopen("/home/plac/problem/output.txt","w",stdout);
   scanf("%lld %lld %lld",&p,&q,&n);
  
  for(ll i = 1; i <= n; i ++)
   {
      scanf("%lld",&a[i]);
	  
   }
   if(ck())
	   printf("YES\n");
   else
	   printf("NO\n");
return 0 ;
}
示例#14
0
IGL_INLINE void igl::PolyVectorFieldFinder<DerivedV, DerivedF>::getGeneralCoeffConstraints(const Eigen::VectorXi &isConstrained,
                                                       const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> &cfW,
                                                       int k,
                                                       Eigen::Matrix<std::complex<typename DerivedV::Scalar>, Eigen::Dynamic,1> &Ck)
{
  int numConstrained = isConstrained.sum();
  Ck.resize(numConstrained,1);
  int n = cfW.cols()/3;

  std::vector<std::vector<int>> allCombs;
  igl::nchoosek(0,k+1,n,allCombs);

  int ind = 0;
  for (int fi = 0; fi <numF; ++fi)
  {
    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b1 = B1.row(fi);
    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &b2 = B2.row(fi);
    if(isConstrained[fi])
    {
      std::complex<typename DerivedV::Scalar> ck(0);

      for (int j = 0; j < allCombs.size(); ++j)
      {
        std::complex<typename DerivedV::Scalar> tk(1.);
        //collect products
        for (int i = 0; i < allCombs[j].size(); ++i)
        {
          int index = allCombs[j][i];

          const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> &w = cfW.block(fi,3*index,1,3);
          typename DerivedV::Scalar w0 = w.dot(b1);
          typename DerivedV::Scalar w1 = w.dot(b2);
          std::complex<typename DerivedV::Scalar> u(w0,w1);
          tk*= u*u;
        }
        //collect sum
        ck += tk;
      }
      Ck(ind) = ck;
      ind ++;
    }
  }


}
示例#15
0
int dBezierSpline::CurveAllDerivatives (dFloat64 u, dBigVector* const derivatives) const
{
	u = dMod (u, 1.0f);
	dFloat64 basicsFuncDerivatives[D_BEZIER_LOCAL_BUFFER_SIZE];
	int span = GetSpan(u);
	BasicsFunctionsDerivatives (u, span, basicsFuncDerivatives);

	const int with = m_degree + 1;
	dBigVector point (0.0f, 0.0f, 0.0f, 0.0f);
	for (int j = 0; j <= m_degree; j ++) {
		dBigVector ck (0.0f, 0.0f, 0.0f, 0.0f);
		for (int i = 0; i <= m_degree; i ++) {
			ck += m_controlPoints[span - m_degree + i].Scale (basicsFuncDerivatives[with * j + i]);
		}
		derivatives[j] = ck;
	}

	return m_degree + 1;
}
示例#16
0
// send client key exchange
void sendClientKeyExchange(SSL& ssl, BufferOutput buffer)
{
    ssl.verifyState(serverHelloDoneComplete);
    if (ssl.GetError()) return;

    ClientKeyExchange ck(ssl);
    ck.build(ssl);
    ssl.makeMasterSecret();

    RecordLayerHeader rlHeader;
    HandShakeHeader   hsHeader;
    mySTL::auto_ptr<output_buffer> out(NEW_YS output_buffer);
    buildHeaders(ssl, hsHeader, rlHeader, ck);
    buildOutput(*out.get(), rlHeader, hsHeader, ck);
    hashHandShake(ssl, *out.get());

    if (buffer == buffered)
        ssl.addBuffer(out.release());
    else
        ssl.Send(out->get_buffer(), out->get_size());
}
    // --------========--------========--------========--------========--------========--------========
    void TweenedLinearCurve::loadFromXmlNode(xmlNodePtr root, float keyDifferenceToIgnore )
    {        
        // look for the curve asset (we only take the first one)
        xmlNodePtr child = root->children;
        while (child)
        {            
            if (xmlStrcmp( child->name, (const xmlChar*)"PreLoop") == 0)
            {
                std::string content = XML::parseString(child, "value");
                
                this->setPreLoop( curveLoopTypeFromString(content) );
#if _DEBUG
                printf("PreLoop -> got content! [%s] = preLoop[%d]\n", content.c_str(), (int)getPreLoop());
#endif
            }
            else if (xmlStrcmp( child->name, (const xmlChar*)"PostLoop") == 0)
            {
                std::string content = XML::parseString(child, "value");
                
                this->setPostLoop( curveLoopTypeFromString(content) );
#ifdef _DEBUG
                printf("PostLoop -> got content! [%s] = postLoop[%d]\n", content.c_str(), (int)getPostLoop());
#endif
            }
            if (xmlStrcmp( child->name, (const xmlChar*)"Keys") == 0)
            {
                xmlNodePtr key = child->children;
                
                float lastAddedCurveKeyValue=0;
                bool didNotAddLastCurveKey=false;
                CurveKey lastCurveKey;
                EasingFunction lastTweeningFunction;
                
                while(key)
                {
                    if(xmlStrcmp( key->name, (const xmlChar*)"Key") == 0)
                    {
                        float position = XML::parseFloat(key, "position");
                        float value = XML::parseFloat(key, "value");
                        
                        CurveKey ck(position, value, 0.0f, 0.0f);
                        
                        EasingFunction tweeningFunction;
                        
                        if(XML::attrExists(key, "tween"))
                        {
                            std::string tween = XML::parseString(key, "tween");
                            float tweenValue = XML::parseFloat(key, "tweenValue");
                            
                            tweeningFunction = Tweens::getEasingFunctionForString(tween,tweenValue);
                        }
                        else
                        {
                            tweeningFunction = &Tweens::linearTween;
                        }
                        
                        bool shouldAddCurveKey=true;                        

                        if(absf(value-lastAddedCurveKeyValue)<keyDifferenceToIgnore &&
                           mKeys.size() )
                        {
                            shouldAddCurveKey=false;
                            didNotAddLastCurveKey=true;
                            lastCurveKey=ck;
                            lastTweeningFunction=tweeningFunction;
                            
                            Logger::printf("Walaber", Logger::SV_DEBUG, "Keys -> not adding curvekey! value: [%f] last value: [%f] key difference to ignore: [%f]\n", value, lastAddedCurveKeyValue, keyDifferenceToIgnore);
                        }
                        else if(didNotAddLastCurveKey)
                        {
                            Logger::printf("Walaber", Logger::SV_DEBUG, "Keys -> got content! position: [%f] value: [%f]\n", lastCurveKey.getPosition(), lastCurveKey.getValue());
                            
                            addCurveKey(lastCurveKey);
                            
                            mTweeningFunctions.push_back(lastTweeningFunction);
                        }
                        
                        if(shouldAddCurveKey)
                        {
                            lastAddedCurveKeyValue=value;
                            
                            didNotAddLastCurveKey=false;
                            
#ifdef _DEBUG
                            printf("Keys -> got content! position: [%f] value: [%f]\n", position, value);
#endif
                            
                            addCurveKey(ck);
                            
                            mTweeningFunctions.push_back(tweeningFunction);
                        }
                        
                    }
                    key = key->next;
                }
                
                if( didNotAddLastCurveKey )
                {
                    addCurveKey( lastCurveKey );
                    mTweeningFunctions.push_back(lastTweeningFunction);
                }
                
                _computeDurations();
                computeTangents();
            }
            
            child = child->next;
        }
    }
示例#18
0
int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QGuiApplication::setApplicationName("Presentao");
    QGuiApplication::setOrganizationName("Embedded_Multimedia");

    QSettings settings;
    QString style = QQuickStyle::name();
    if (!style.isEmpty())
        settings.setValue("style", style);
    else
        QQuickStyle::setStyle(settings.value("style").toString());

    web_socket_client websocketclient;

    audioWindow audioengine;

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    PdfRenderer myPdfRenderer;
    handcontrol myhandcontrol;
    engine.addImageProvider(QLatin1String("pdfrenderer"), &myPdfRenderer);

    QObject *root = engine.rootObjects()[0];

    //QObject::connect(root, SIGNAL(nextpage()),&myPdfRenderer, SLOT(nextPage()));
    //QObject::connect(root, SIGNAL(prevpage()),&myPdfRenderer, SLOT(prevPage()));
    QObject::connect(root, SIGNAL(openfile(QUrl)),&myPdfRenderer, SLOT(OpenPDF(QUrl)));
    QObject::connect(&myPdfRenderer, SIGNAL(sendTotalPageCount(QVariant)),root, SLOT(setTotalPageCount(QVariant)));


    /*
     * signals from web_socket_client
     * void OpenPDF(QString)
     * void signal_setPage(int)
     * void connection_success()
    */

    QObject::connect(&websocketclient, SIGNAL(OpenPDF(QUrl)),
                     &myPdfRenderer, SLOT(OpenPDF(QUrl)));
    QObject::connect(&websocketclient, SIGNAL(signal_setPage(QVariant)),
                     root, SLOT(setCurrentPageNr(QVariant)));
    QObject::connect(&websocketclient, SIGNAL(connection_success()),
                     root, SLOT(connection_success()));

    /*
     * slots of web_socket_client
     * void connect(QString)
     * void onConnected()
     * void onBinaryMessage(QByteArray)
     * void onTextMessage(QString)
     * void sendFile(QString filename)
     * void registerMaster(QString)
     * void download_pdf(QString filename)
     * void getPage()
     * void setPage(QString)
     */

    QObject::connect(root, SIGNAL(connect(QString)),
                     &websocketclient, SLOT(connect(QString)));
    QObject::connect(root, SIGNAL(registerMaster(QString)),
                     &websocketclient, SLOT(registerMaster(QString)));
    QObject::connect(root, SIGNAL(sendFile(QUrl)),
                     &websocketclient, SLOT(sendFile(QUrl)));
    QObject::connect(root, SIGNAL(download_pdf(QString)),
                     &websocketclient, SLOT(download_pdf(QString)));
    QObject::connect(root, SIGNAL(setPage(QString)),
                     &websocketclient, SLOT(setPage(QString)));
    QObject::connect(root, SIGNAL(getPage()),
                     &websocketclient, SLOT(getPage()));


    //AUDIO
     QObject::connect(root, SIGNAL(startstopKlopfen()),&audioengine, SLOT(startStopRecording()));
     QObject::connect(&audioengine, SIGNAL(knock()),root, SLOT(klopf_weiter()));
     QObject::connect(&audioengine, SIGNAL(double_knock()),root,SLOT(klopf_zurück()));


    // Gestensteuerng
    QObject *cameraComponent = root->findChild<QObject*>("camera");
    QCamera *camera = qvariant_cast<QCamera*>(cameraComponent->property("mediaObject"));
    myhandcontrol.setCamera(camera);
    QObject::connect(root, SIGNAL(handcontrol_enable(int)),&myhandcontrol, SLOT(enable(int)));
    QObject::connect(&myhandcontrol, SIGNAL(debugMessage(QVariant)),root, SLOT(handcontrol_debugOut(QVariant)));
    QObject::connect(&myhandcontrol, SIGNAL(errorMessage(QVariant)),root, SLOT(handcontrol_debugOut(QVariant)));
    QObject::connect(&myhandcontrol, SIGNAL(change_page(QVariant)),root, SLOT(handcontrol_change_page(QVariant)));
    qDebug()<<"From main thread: "<<QThread::currentThreadId();
    return app.exec();
}
示例#19
0
int main(int argc, char **argv)
{
  QxtCommandOptions options;

  options.add(CL_HELP, "display this help message",
      QxtCommandOptions::NoValue);
  options.add(CL_NKEYS, "number of keys to generate",
      QxtCommandOptions::ValueRequired);
  options.add(CL_PUBDIR, "directory in which to put public keys (default=./keys/pub)",
      QxtCommandOptions::ValueRequired);
  options.add(CL_PRIVDIR, "directory in which to put private keys (default=./keys/priv)",
      QxtCommandOptions::ValueRequired);
  options.add(CL_KEYTYPE, "specify the key type (default=dsa, options=dsa|rsa)",
      QxtCommandOptions::ValueRequired);
  options.add(CL_LIB, "specify the library (default=cryptopp, options=cryptopp)",
      QxtCommandOptions::ValueRequired);
  options.add(CL_RAND, "specify the base properties for the key (default=NULL)",
      QxtCommandOptions::ValueRequired);
  options.add(CL_DEBUG, "enable debugging",
      QxtCommandOptions::NoValue);

  options.parse(argc, argv);

  if(options.count(CL_HELP) || options.showUnrecognizedWarning()) {
    options.showUsage();
    return -1;
  }

  QMultiHash<QString, QVariant> params = options.parameters();

  int key_count = params.value(CL_NKEYS, 1).toInt();
  if(key_count < 1) {
    ExitWithWarning(options, "Invalid nkeys");
  }

  QString pubdir_path = params.value(CL_PUBDIR, DEFAULT_PUBDIR).toString();
  QDir pubdir(pubdir_path);
  if(!pubdir.exists()) {
    pubdir.mkpath(".");
  }

  if(!pubdir.exists()) {
    ExitWithWarning(options, "Unable to create pubdir");
  }

  QString privdir_path = params.value(CL_PRIVDIR, DEFAULT_PRIVDIR).toString();
  QDir privdir(privdir_path);
  if(!privdir.exists()) {
    privdir.mkpath(".");
  }

  if(!privdir.exists()) {
    ExitWithWarning(options, "Unable to create privdir");
  }

  if(params.contains(CL_DEBUG)) {
    Logging::UseStderr();
  }

  QString lib_name = params.value(CL_LIB, "cryptopp").toString();
  QString key = params.value(CL_KEYTYPE, "dsa").toString();

  CryptoFactory &cf = CryptoFactory::GetInstance();
  QSharedPointer<CreateKey> ck(new CreateKey());
  if(lib_name == "cryptopp") {
    if(key == "dsa") {
      cf.SetLibrary(CryptoFactory::CryptoPPDsa);
      if(params.contains(CL_RAND)) {
        ck = QSharedPointer<CreateKey>(
            new CreateSeededDsaKey(params.value(CL_RAND).toString()));
      }
    } else if (key == "rsa") {
      cf.SetLibrary(CryptoFactory::CryptoPP);
    } else {
      ExitWithWarning(options, "Invalid key type");
    }
  } else {
    ExitWithWarning(options, "Invalid library");
  }

  Library *lib = cf.GetLibrary();
  QSharedPointer<Hash> hash(lib->GetHashAlgorithm());

  int count = 0;
  while(count < key_count) {
    QSharedPointer<AsymmetricKey> key((*ck)());
    QSharedPointer<AsymmetricKey> pubkey(key->GetPublicKey());
    QByteArray hvalue = hash->ComputeHash(pubkey->GetByteArray());
    QString id = Integer(hvalue).ToString();

    if(!key->Save(privdir_path + QDir::separator() + id)) {
      qFatal("Could not save private key");
    }

    if(!pubkey->Save(pubdir_path + QDir::separator() + id + ".pub")) {
      qFatal("Could not save private key");
    }

    count++;
  }

  return 0;
}
示例#20
0
void CalculateAngleDerivativesE2(vtkPolyData* mesh, const arma::sp_mat& edge_lengths, const arma::vec& radii) {
    //calculate the power center for each triangle as follows
    //for 2 circles centered at c1 and c2 solve for p:
    //|p-c1|^2 - r1^2 = |p-c2|^2 - r2^2    -- this is power line
    //add one more condition for the third circle to get one point
    //  Funny part: the paper says that the circle of radius sqrt(|c1-p|^2 - r1^2)
    //  is perpendicular to all three circles. But this works only when the 3 circles do not intersect
    const int npts = mesh->GetNumberOfPoints();
    const int ncells = mesh->GetNumberOfCells();

    vtkSmartPointer<vtkIdList> cellIdList = vtkSmartPointer<vtkIdList>::New();
    vtkSmartPointer<vtkIdList> pointIdList = vtkSmartPointer<vtkIdList>::New();

    //for every face calculate gamma_ijk
    arma::vec gamma_percell(ncells);
    for (vtkIdType i = 0; i < ncells; i++) {
        pointIdList->Reset();
        mesh->GetCellPoints(cellIdList->GetId(i), pointIdList);


        const int ind_i = pointIdList->GetId(0);
        const int ind_j = pointIdList->GetId(1);
        const int ind_k = pointIdList->GetId(2);

        const double ri = radii[ind_i];
        const double rj = radii[ind_j];
        const double rk = radii[ind_k];

        arma::vec ci(3), cj(3), ck(3);
        mesh->GetPoint(ind_i, ci.memptr());
        mesh->GetPoint(ind_j, cj.memptr());
        mesh->GetPoint(ind_k, ck.memptr());

        //create local 2D coordinates, and map vertices
        arma::vec vji = cj - ci;
        arma::vec v   = ck - ci;

        arma::vec n = arma::cross(vji, v); //normal
        arma::vec vki = arma::cross(n, vji); //creates local y' axis

        const double lenX = arma::norm(vji,2);
        const double lenY = arma::norm(vki,2);
        
        vji /= lenX; //normalize axes
        vki /= lenY;
        
        //2D coordinates
        arma::vec vi(3,0); //(0,0)
        arma::vec vj(3);
        arma::vec vk(3);

        vj(0) = lenX;
        vj(1) = 0.0;
        vk(0) = arma::dot(v, vji);
        vk(1) = arma::dot(v, vki);
        
        //form matrices for system of linear equations and solve
        //A = [2*(c2-c1)'; 2*(c2-c3)'];
        //B = [ c2'*c2 - c1'*c1 + r1^2 - r2^2; c2'*c2 - c3'*c3 + r3^2 - r2^2];
        //P = A\B;
        arma::mat A(2,2);
        arma::vec B(2);
        
        A.insert_rows( 0, 2.0*(cj-ci) );
        A.insert_rows( 1, 2.0*(cj-ck) );
        B(0) = arma::dot(cj, cj) - arma::dot(ci, ci) + ri*ri - rj*rj;
        B(1) = arma::dot(cj, cj) - arma::dot(ck, ck) + rk*rk - rj*rj;
        arma::vec P = arma::solve( A, B ); 
        
        //calculate distance from P to all the edges: hi, hj, hk
        //http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
        const double hi = arma::norm( arma::cross(cj-ck, ck-P), 2 ) / arma::norm(cj-ck, 2);
        const double hj = arma::norm( arma::cross(ci-ck, ck-P), 2 ) / arma::norm(ci-ck, 2);
        const double hk = arma::norm( arma::cross(cj-ci, ci-P), 2 ) / arma::norm(cj-ci, 2);
        
        const double li = edge_lengths(ind_j, ind_k);
        const double lj = edge_lengths(ind_i, ind_k);
        const double lk = edge_lengths(ind_i, ind_j);
        
        const double dTi_duj = hk/lk;
        const double dTj_duk = hi/li;
        const double dTk_dui = hj/lj;

        const double dTi_dui = - dTi_duj - dTk_dui;
        const double dTj_duj = - dTj_duk - dTi_duj;
        const double dTk_duk = - dTj_duk - dTk_dui;


    }
    
    
    
}