/* ****************************************************************************
*
* withoutAttribute -
*
*/
TEST(mongoQueryContextRequest_filters, withoutAttribute)
{
  HttpStatusCode         ms;
  QueryContextRequest   req;
  QueryContextResponse  res;

  /* Prepare database */
  prepareDatabase(true);

  /* Forge the request (from "inside" to "outside") */
  EntityId en(".*", "", "true");
  Scope sc(SCOPE_TYPE_SIMPLE_QUERY, "-S");
  req.entityIdVector.push_back(&en);
  req.restriction.scopeVector.push_back(&sc);

  /* Invoke the function in mongoBackend library */
  servicePathVector.clear();
  ms = mongoQueryContext(&req, &res, "", servicePathVector, uriParams);

  /* Check response is as expected */
  EXPECT_EQ(SccOk, ms);

  EXPECT_EQ(SccNone, res.errorCode.code);
  EXPECT_EQ("", res.errorCode.reasonPhrase);
  EXPECT_EQ("", res.errorCode.details);

  /* Only entitie IDs are check (we have a bunch of tests in other places to check the query response itself */
  ASSERT_EQ(6, res.contextElementResponseVector.size());
  EXPECT_EQ("C1", RES_CER(0).entityId.id);
  EXPECT_EQ("C2", RES_CER(1).entityId.id);
  EXPECT_EQ("C3", RES_CER(2).entityId.id);
  EXPECT_EQ("E6", RES_CER(3).entityId.id);
  EXPECT_EQ("E7", RES_CER(4).entityId.id);
  EXPECT_EQ("E8", RES_CER(5).entityId.id);

  /* Release dynamic memory used by response (mongoBackend allocates it) */
  res.contextElementResponseVector.release();

  /* Release connection */
  setMongoConnectionForUnitTest(NULL);
}
static void merge_meta(file_info & p_out,const pfc::list_base_const_t<const file_info*> & p_in) {
	pfc::map_t<const char *,meta_merge_entry,pfc::comparator_stricmp_ascii> map;
	for(t_size in_walk = 0; in_walk < p_in.get_count(); in_walk++) {
		const file_info & in = * p_in[in_walk];
		for(t_size meta_walk = 0, meta_count = in.meta_get_count(); meta_walk < meta_count; meta_walk++ ) {
			meta_merge_entry & entry = map.find_or_add(in.meta_enum_name(meta_walk));
			t_size rating = merge_tags_calc_rating_by_index(in,meta_walk);
			if (rating > entry.m_rating) {
				entry.m_rating = rating;
				const t_size value_count = in.meta_enum_value_count(meta_walk);
				entry.m_data.set_size(value_count);
				for(t_size value_walk = 0; value_walk < value_count; value_walk++ ) {
					entry.m_data[value_walk] = in.meta_enum_value(meta_walk,value_walk);
				}
			}
		}
	}

    meta_merge_map_enumerator en(p_out);
	map.enumerate(en);
}
Esempio n. 3
0
void HTMLButcherCSSFilesDialog::do_remove(unsigned long id)
{
    // get number of views using this mask
    ButcherProjectEventNotify en(GetProject(), ButcherProjectEvent::BPE_CSSFILEDELETED, id, 0, false);
    GetProject()->ExecuteEventNotify(en);

    wxString remmsg=_("Are you sure you want to remove this CSS?");
    if (en.GetRemoveCount()>0||en.GetChangeCount()>0)
        remmsg=wxString::Format(_("Removing this CSS will affect %d item(s). Are you sure?"), en.GetRemoveCount()+en.GetChangeCount());

    wxMessageDialog d(this, remmsg, _("Remove CSS"), wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION);
    if (d.ShowModal() != wxID_YES) return;

    ButcherProjectBaseAutoUpdate upd(GetProject());
    if (!GetProject()->CSSFiles().Delete(id))
    {
        butil_errordialog(_("This CSS cannot be deleted"), this);
        return;
    }
    item_remove(id);
}
Esempio n. 4
0
void tomdatp() {
    TMR2 = 0;
    en();
    delay_ms(1);
    delay_us(500);
    s1.tinit = IC1BUF;
    s1.th = IC1BUF - s1.tinit;
    s1.tt = IC1BUF - s1.tinit;
    s2.tinit = IC2BUF;
    s2.th = IC2BUF - s2.tinit;
    s2.tt = IC2BUF - s2.tinit;
    s3.tinit = IC3BUF;
    s3.th = IC3BUF - s3.tinit;
    s3.tt = IC3BUF - s3.tinit;
    s4.tinit = IC4BUF;
    s4.th = IC4BUF - s4.tinit;
    s4.tt = IC4BUF - s4.tinit;
    s5.tinit = IC5BUF;
    s5.th = IC5BUF - s5.tinit;
    s5.tt = IC5BUF - s5.tinit;
    s6.tinit = IC6BUF;
    s6.th = IC6BUF - s6.tinit;
    s6.tt = IC6BUF - s6.tinit;
    s7.tinit = IC7BUF;
    s7.th = IC7BUF - s7.tinit;
    s7.tt = IC7BUF - s7.tinit;
    s8.tinit = IC8BUF;
    s8.th = IC8BUF - s8.tinit;
    s8.tt = IC8BUF - s8.tinit;
    dis();
    formul(1, s1.tinit, s1.th, s1.tt);
    formul(2, s2.tinit, s2.th, s2.tt);
    formul(3, s3.tinit, s3.th, s3.tt);
    formul(4, s4.tinit, s4.th, s4.tt);
    formul(5, s5.tinit, s5.th, s5.tt);
    formul(6, s6.tinit, s6.th, s6.tt);
    formul(7, s7.tinit, s7.th, s7.tt);
    formul(8, s8.tinit, s8.th, s8.tt);
}
Esempio n. 5
0
int main(int argc, char* argv[]) {
	int SIZE = 2048;
	char k1[SIZE];
	char k2[SIZE];
	string filename;
	ifstream file;
	//Encrypt en;

	cout << "Enter key1: ";
	cin.getline(k1, SIZE);
	while (!validate(k1)) {
		cout << "Enter key1: ";
		cin.getline(k1, SIZE);
	}
	cout << "Enter key2: ";
	cin.getline(k2, SIZE);
	while (!validate(k2)) {
		cout << "Enter key2: ";
		cin.getline(k2, SIZE);
	}
	cout << "Enter filename: ";
	cin >> filename;
	file.open(filename.c_str());
	while (file.fail()) {
		cout << "File: \'" << filename << "\' does not exist, please enter a valid filename" << endl;
		cout << "Enter filename: ";
		cin >> filename;
		file.open(filename.c_str());
	}
	file.close();

	string newKey1(k1);
	string newKey2(k2);
	string mKey1 =	modify(newKey1);
	string mKey2 =	modify(newKey2);
	Encrypt en(mKey1, mKey2, filename);

	return 0;
}
Esempio n. 6
0
void HTMLButcherMasksDialog::do_remove(unsigned long id)
{
    // get number of views using this mask
    ButcherProjectEventNotify en(GetProject(), ButcherProjectEvent::BPE_MASKDELETED, id, 0, false);
    GetProject()->ExecuteEventNotify(en);

    wxString remmsg=_("Are you sure you want to remove this mask?");
    if (en.GetRemoveCount()>0)
        remmsg=wxString::Format(_("Removing this mask will remove %d view(s). Are you sure?"), en.GetRemoveCount());

    wxMessageDialog d(this, remmsg, _("Remove mask"), wxYES_NO | wxYES_DEFAULT | wxICON_QUESTION);
    if (d.ShowModal() != wxID_YES) return;

    ButcherProjectBaseAutoUpdate upd(GetProject());
    if (!GetProject()->Masks().Delete(id))
    {
        butil_errordialog(_("This mask cannot be deleted"), this);
        return;
    }
    item_remove(id);

	EnableAdd(!GetProject()->Masks().IsFull());
}
Esempio n. 7
0
CEspConfig::CEspConfig(IProperties* inputs, IPropertyTree* envpt, IPropertyTree* procpt, bool isDali)
{
    hsami_=0;
    serverstatus=NULL;
    useDali=false;
    
    if(inputs)
        m_inputs.setown(inputs);

    if(!envpt || !procpt)
        return;

    m_envpt.setown(envpt);
    m_cfg.setown(procpt);

    loadBuiltIns();   
   
    // load options
    const char* level = m_cfg->queryProp("@logLevel");
    m_options.logLevel = level ? atoi(level) : LogMin;
    m_options.logReq = m_cfg->getPropBool("@logRequests", true);
    m_options.logResp = m_cfg->getPropBool("@logResponses", false);
    m_options.frameTitle.set(m_cfg->queryProp("@name"));
    m_options.slowProcessingTime = m_cfg->getPropInt("@slowProcessingTime", 30) * 1000; //in msec

    if (!m_cfg->getProp("@name", m_process))
    {
        ERRLOG("EspProcess name not found");
    }
    else
    {
        DBGLOG("ESP process name [%s]", m_process.str());

        IPropertyTreeIterator *pt_iter = NULL;
        StringBuffer daliservers;
        if (m_cfg->getProp("@daliServers", daliservers))
            initDali(daliservers.str());

#ifndef _DEBUG
        startPerformanceMonitor(m_cfg->getPropInt("@perfReportDelay", 60)*1000);
#endif

        //get the local computer name:              
        m_cfg->getProp("@computer", m_computer);

        //get the local computer information:               
        StringBuffer xpath;
        xpath.appendf("Hardware/Computer[@name=\"%s\"]", m_computer.str());

        IPropertyTree *computer = m_envpt->queryPropTree(xpath.str());
        if (computer)
        {
            StringBuffer address;
            computer->getProp("@netAddress", address);

            int port = m_cfg->getPropInt("@port", 1500);
            if(strcmp(address.str(), ".") == 0)
            {
                GetHostName(address.clear());
            }
            m_address.set(address.str(), (unsigned short) port);
        }
      
        xpath.clear();
        xpath.append("EspService");
 
        pt_iter = m_cfg->getElements(xpath.str());

        if (pt_iter!=NULL)
        {
            IPropertyTree *ptree = NULL;

            pt_iter->first();

            while(pt_iter->isValid())
            {
                ptree = &pt_iter->query();
                if (ptree)
                {
                    srv_cfg *svcfg = new srv_cfg;

                    ptree->getProp("@name", svcfg->name);
                    ptree->getProp("@type", svcfg->type);
                    ptree->getProp("@plugin", svcfg->plugin);
                    fixPlugin(svcfg->plugin);

                    map<string, srv_cfg*>::value_type en(svcfg->name.str(), svcfg);
                    m_services.insert(en);
                }               
                pt_iter->next();
            }
    
            pt_iter->Release();
            pt_iter=NULL;
        }

        xpath.clear();
        xpath.append("EspProtocol");
 
        pt_iter = m_cfg->getElements(xpath.str());

        if (pt_iter!=NULL)
        {
            IPropertyTree *ptree = NULL;

            pt_iter->first();
    

            while(pt_iter->isValid())
            {
                ptree = &pt_iter->query();
                if (ptree)
                {
                    protocol_cfg *pcfg = new protocol_cfg;

                    ptree->getProp("@name", pcfg->name);
                    ptree->getProp("@plugin", pcfg->plugin);
                    fixPlugin(pcfg->plugin);
                    ptree->getProp("@type", pcfg->type);

                    map<string, protocol_cfg*>::value_type en(pcfg->name.str(), pcfg);
                    m_protocols.insert(en);
                }               

                pt_iter->next();
            }
    
            pt_iter->Release();
            pt_iter=NULL;
        }

        xpath.clear();
        xpath.append("EspBinding");
 
        pt_iter = m_cfg->getElements(xpath.str());

        if (pt_iter!=NULL)
        {
            IPropertyTree *ptree = NULL;

            pt_iter->first();
    

            while(pt_iter->isValid())
            {
                ptree = &pt_iter->query();
                if (ptree)
                {
                    binding_cfg *bcfg = new binding_cfg;
                    
                    ptree->getProp("@name", bcfg->name);
                    ptree->getProp("@type", bcfg->type);
                    ptree->getProp("@plugin", bcfg->plugin);
                    fixPlugin(bcfg->plugin);
                    bcfg->isDefault = ptree->getPropBool("@defaultBinding", false);
                    
                    StringBuffer addr;
                    ptree->getProp("@netAddress", addr);
                    if(strcmp(addr.str(), ".") == 0)
                    {
                        bcfg->address.append("0.0.0.0");
                    }
                    else
                    {
                        bcfg->address.append(addr.str());
                    }
                    
                    StringBuffer portstr;
                    ptree->getProp("@port", portstr);
                    bcfg->port = atoi(portstr.str());
                    ptree->getProp("@service", bcfg->service_name);
                    ptree->getProp("@protocol", bcfg->protocol_name);
                    
                    m_bindings.push_back(bcfg);
                }
                
                pt_iter->next();
            }
    
            pt_iter->Release();
            pt_iter=NULL;
        }
    }
}
Esempio n. 8
0
/**
 * Test the API of DecimalFormatSymbols; primarily a simple get/set set.
 */
void IntlTestDecimalFormatSymbols::testSymbols(/* char *par */)
{
    UErrorCode status = U_ZERO_ERROR;

    DecimalFormatSymbols fr(Locale::getFrench(), status);
    if(U_FAILURE(status)) {
        errcheckln(status, "ERROR: Couldn't create French DecimalFormatSymbols - %s", u_errorName(status));
        return;
    }

    status = U_ZERO_ERROR;
    DecimalFormatSymbols en(Locale::getEnglish(), status);
    if(U_FAILURE(status)) {
        errcheckln(status, "ERROR: Couldn't create English DecimalFormatSymbols - %s", u_errorName(status));
        return;
    }

    if(en == fr || ! (en != fr) ) {
        errln("ERROR: English DecimalFormatSymbols equal to French");
    }

    // just do some VERY basic tests to make sure that get/set work

    UnicodeString zero = en.getSymbol(DecimalFormatSymbols::kZeroDigitSymbol);
    fr.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, zero);
    if(fr.getSymbol(DecimalFormatSymbols::kZeroDigitSymbol) != en.getSymbol(DecimalFormatSymbols::kZeroDigitSymbol)) {
        errln("ERROR: get/set ZeroDigit failed");
    }

    UnicodeString group = en.getSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol);
    fr.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, group);
    if(fr.getSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol) != en.getSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol)) {
        errln("ERROR: get/set GroupingSeparator failed");
    }

    UnicodeString decimal = en.getSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol);
    fr.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, decimal);
    if(fr.getSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol) != en.getSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol)) {
        errln("ERROR: get/set DecimalSeparator failed");
    }

    UnicodeString perMill = en.getSymbol(DecimalFormatSymbols::kPerMillSymbol);
    fr.setSymbol(DecimalFormatSymbols::kPerMillSymbol, perMill);
    if(fr.getSymbol(DecimalFormatSymbols::kPerMillSymbol) != en.getSymbol(DecimalFormatSymbols::kPerMillSymbol)) {
        errln("ERROR: get/set PerMill failed");
    }

    UnicodeString percent = en.getSymbol(DecimalFormatSymbols::kPercentSymbol);
    fr.setSymbol(DecimalFormatSymbols::kPercentSymbol, percent);
    if(fr.getSymbol(DecimalFormatSymbols::kPercentSymbol) != en.getSymbol(DecimalFormatSymbols::kPercentSymbol)) {
        errln("ERROR: get/set Percent failed");
    }

    UnicodeString digit(en.getSymbol(DecimalFormatSymbols::kDigitSymbol));
    fr.setSymbol(DecimalFormatSymbols::kDigitSymbol, digit);
    if(fr.getSymbol(DecimalFormatSymbols::kDigitSymbol) != en.getSymbol(DecimalFormatSymbols::kDigitSymbol)) {
        errln("ERROR: get/set Percent failed");
    }

    UnicodeString patternSeparator = en.getSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol);
    fr.setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, patternSeparator);
    if(fr.getSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol) != en.getSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol)) {
        errln("ERROR: get/set PatternSeparator failed");
    }

    UnicodeString infinity(en.getSymbol(DecimalFormatSymbols::kInfinitySymbol));
    fr.setSymbol(DecimalFormatSymbols::kInfinitySymbol, infinity);
    UnicodeString infinity2(fr.getSymbol(DecimalFormatSymbols::kInfinitySymbol));
    if(infinity != infinity2) {
        errln("ERROR: get/set Infinity failed");
    }

    UnicodeString nan(en.getSymbol(DecimalFormatSymbols::kNaNSymbol));
    fr.setSymbol(DecimalFormatSymbols::kNaNSymbol, nan);
    UnicodeString nan2(fr.getSymbol(DecimalFormatSymbols::kNaNSymbol));
    if(nan != nan2) {
        errln("ERROR: get/set NaN failed");
    }

    UnicodeString minusSign = en.getSymbol(DecimalFormatSymbols::kMinusSignSymbol);
    fr.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, minusSign);
    if(fr.getSymbol(DecimalFormatSymbols::kMinusSignSymbol) != en.getSymbol(DecimalFormatSymbols::kMinusSignSymbol)) {
        errln("ERROR: get/set MinusSign failed");
    }

    UnicodeString exponential(en.getSymbol(DecimalFormatSymbols::kExponentialSymbol));
    fr.setSymbol(DecimalFormatSymbols::kExponentialSymbol, exponential);
    if(fr.getSymbol(DecimalFormatSymbols::kExponentialSymbol) != en.getSymbol(DecimalFormatSymbols::kExponentialSymbol)) {
        errln("ERROR: get/set Exponential failed");
    }

    // Test get currency spacing before the currency.
    status = U_ZERO_ERROR;
    for (int32_t i = 0; i < (int32_t)UNUM_CURRENCY_SPACING_COUNT; i++) {
        UnicodeString enCurrencyPattern = en.getPatternForCurrencySpacing(
             (UCurrencySpacing)i, TRUE, status);
        if(U_FAILURE(status)) {
            errln("Error: cannot get CurrencyMatch for locale:en");
            status = U_ZERO_ERROR;
        }
        UnicodeString frCurrencyPattern = fr.getPatternForCurrencySpacing(
             (UCurrencySpacing)i, TRUE, status);
        if(U_FAILURE(status)) {
            errln("Error: cannot get CurrencyMatch for locale:fr");
        }
        if (enCurrencyPattern != frCurrencyPattern) {
           errln("ERROR: get CurrencySpacing failed");
        }
    }
    // Test get currencySpacing after the currency.
    status = U_ZERO_ERROR;
    for (int32_t i = 0; i < UNUM_CURRENCY_SPACING_COUNT; i++) {
        UnicodeString enCurrencyPattern = en.getPatternForCurrencySpacing(
            (UCurrencySpacing)i, FALSE, status);
        if(U_FAILURE(status)) {
            errln("Error: cannot get CurrencyMatch for locale:en");
            status = U_ZERO_ERROR;
        }
        UnicodeString frCurrencyPattern = fr.getPatternForCurrencySpacing(
             (UCurrencySpacing)i, FALSE, status);
        if(U_FAILURE(status)) {
            errln("Error: cannot get CurrencyMatch for locale:fr");
        }
        if (enCurrencyPattern != frCurrencyPattern) {
            errln("ERROR: get CurrencySpacing failed");
        }
    }
    // Test set curerncySpacing APIs
    status = U_ZERO_ERROR;
    UnicodeString dash = UnicodeString("-");
    en.setPatternForCurrencySpacing(UNUM_CURRENCY_INSERT, TRUE, dash);
    UnicodeString enCurrencyInsert = en.getPatternForCurrencySpacing(
        UNUM_CURRENCY_INSERT, TRUE, status);
    if (dash != enCurrencyInsert) {
        errln("Error: Failed to setCurrencyInsert for locale:en");
    }

    status = U_ZERO_ERROR;
    DecimalFormatSymbols foo(status);

    DecimalFormatSymbols bar(foo);

    en = fr;

    if(en != fr || foo != bar) {
        errln("ERROR: Copy Constructor or Assignment failed");
    }

    // test get/setSymbol()
    if((int) UNUM_FORMAT_SYMBOL_COUNT != (int) DecimalFormatSymbols::kFormatSymbolCount) {
        errln("unum.h and decimfmt.h have inconsistent numbers of format symbols!");
        return;
    }

    int i;
    for(i = 0; i < (int)DecimalFormatSymbols::kFormatSymbolCount; ++i) {
        foo.setSymbol((DecimalFormatSymbols::ENumberFormatSymbol)i, UnicodeString((UChar32)(0x10330 + i)));
    }
    for(i = 0; i < (int)DecimalFormatSymbols::kFormatSymbolCount; ++i) {
        if(foo.getSymbol((DecimalFormatSymbols::ENumberFormatSymbol)i) != UnicodeString((UChar32)(0x10330 + i))) {
            errln("get/setSymbol did not roundtrip, got " +
                  foo.getSymbol((DecimalFormatSymbols::ENumberFormatSymbol)i) +
                  ", expected " +
                  UnicodeString((UChar32)(0x10330 + i)));
        }
    }

    DecimalFormatSymbols sym(Locale::getUS(), status);

    UnicodeString customDecSeperator("S");
    Verify(34.5, (UnicodeString)"00.00", sym, (UnicodeString)"34.50");
    sym.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, customDecSeperator);
    Verify(34.5, (UnicodeString)"00.00", sym, (UnicodeString)"34S50");
    sym.setSymbol(DecimalFormatSymbols::kPercentSymbol, (UnicodeString)"P");
    Verify(34.5, (UnicodeString)"00 %", sym, (UnicodeString)"3450 P");
    sym.setSymbol(DecimalFormatSymbols::kCurrencySymbol, (UnicodeString)"D");
    Verify(34.5, CharsToUnicodeString("\\u00a4##.##"), sym, (UnicodeString)"D34.5");
    sym.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, (UnicodeString)"|");
    Verify(3456.5, (UnicodeString)"0,000.##", sym, (UnicodeString)"3|456S5");

}
Esempio n. 9
0
/**
  * this should handle modifyOffset
  *@ coord, indicate direction of offset
  *@ distance of offset
  *
  *@Author, Dongxu Li
  */
bool RS_Polyline::offset(const RS_Vector& coord, const double& distance){
    double dist;
    //find the nearest one
    int length=count();
		std::vector<RS_Vector> intersections(length);
    if(length>1){//sort the polyline entity start/end point order
        int i(0);
        double d0,d1;
        RS_Entity* en0(entityAt(0));
        RS_Entity* en1(entityAt(1));

        RS_Vector vStart(en0->getStartpoint());
        RS_Vector vEnd(en0->getEndpoint());
        en1->getNearestEndpoint(vStart,&d0);
        en1->getNearestEndpoint(vEnd,&d1);
        if(d0<d1) en0->revertDirection();
        for(i=1;i<length;en0=en1){
                //linked to head-tail chain
            en1=entityAt(i);
            vStart=en1->getStartpoint();
            vEnd=en1->getEndpoint();
            en0->getNearestEndpoint(vStart,&d0);
            en0->getNearestEndpoint(vEnd,&d1);
            if(d0>d1) en1->revertDirection();
            intersections[i-1]=(en0->getEndpoint()+en1->getStartpoint())*0.5;
            i++;
        }

    }
    RS_Entity* en(getNearestEntity(coord, &dist, RS2::ResolveNone));
    if(en==NULL) return false;
    int indexNearest=findEntity(en);
    //        RS_Vector vp(en->getNearestPointOnEntity(coord,false));
    //        RS_Vector direction(en->getTangentDirection(vp));
    //        RS_Vector vp1(-direction.y,direction.x);//normal direction
    //        double a2(vp1.squared());
    //        if(a2<RS_TOLERANCE2) return false;
    //        vp1 *= distance/sqrt(a2);
    //        move(vp1);
    //        return true;

    RS_Polyline* pnew= static_cast<RS_Polyline*>(clone());
    int i;
    i=indexNearest;
    int previousIndex(i);
    pnew->entityAt(i)->offset(coord,distance);
    RS_Vector vp;
    //offset all
    //fixme, this is too ugly
    for(i=indexNearest-1;i>=0;i--){
        RS_VectorSolutions sol0=RS_Information::getIntersection(pnew->entityAt(previousIndex),entityAt(i),true);
//        RS_VectorSolutions sol1;
        double dmax(RS_TOLERANCE15);
        RS_Vector trimP(false);
		for(const RS_Vector& vp: sol0){

			double d0( (vp - pnew->entityAt(previousIndex)->getStartpoint()).squared());//potential bug, need to trim better
            if(d0>dmax) {
                dmax=d0;
				trimP=vp;
            }
        }
        if(trimP.valid){
            static_cast<RS_AtomicEntity*>(pnew->entityAt(previousIndex))->trimStartpoint(trimP);
            static_cast<RS_AtomicEntity*>(pnew->entityAt(i))->trimEndpoint(trimP);
            vp=pnew->entityAt(previousIndex)->getMiddlePoint();
        }else{
            vp=pnew->entityAt(previousIndex)->getStartpoint();
            vp.rotate(entityAt(previousIndex)->getStartpoint(),entityAt(i)->getDirection2()-entityAt(previousIndex)->getDirection1()+M_PI);
        }
        pnew->entityAt(i)->offset(vp,distance);
        previousIndex=i;
    }

    previousIndex=indexNearest;
    for(i=indexNearest+1;i<length;i++){
        RS_VectorSolutions sol0=RS_Information::getIntersection(pnew->entityAt(previousIndex),entityAt(i),true);
//        RS_VectorSolutions sol1;
        double dmax(RS_TOLERANCE15);
        RS_Vector trimP(false);
		for(const RS_Vector& vp: sol0){
			double d0( (vp - pnew->entityAt(previousIndex)->getEndpoint()).squared());//potential bug, need to trim better
            if(d0>dmax) {
                dmax=d0;
				trimP=vp;
            }
        }
        if(trimP.valid){
            static_cast<RS_AtomicEntity*>(pnew->entityAt(previousIndex))->trimEndpoint(trimP);
            static_cast<RS_AtomicEntity*>(pnew->entityAt(i))->trimStartpoint(trimP);
            vp=pnew->entityAt(previousIndex)->getMiddlePoint();
        }else{
            vp=pnew->entityAt(previousIndex)->getEndpoint();
            vp.rotate(entityAt(previousIndex)->getEndpoint(),entityAt(i)->getDirection1()-entityAt(previousIndex)->getDirection2()+M_PI);
        }
        pnew->entityAt(i)->offset(vp,distance);
        previousIndex=i;
    }
    //trim
    //connect and trim        RS_Modification m(*container, graphicView);
    for(i=0;i<length-1;i++){
        RS_VectorSolutions sol0=RS_Information::getIntersection(pnew->entityAt(i),pnew->entityAt(i+1),true);
        if(sol0.getNumber()==0) {
            sol0=RS_Information::getIntersection(pnew->entityAt(i),pnew->entityAt(i+1));
//            RS_Vector vp0(pnew->entityAt(i)->getEndpoint());
//            RS_Vector vp1(pnew->entityAt(i+1)->getStartpoint());
//            double a0(intersections.at(i).angleTo(vp0));
//            double a1(intersections.at(i).angleTo(vp1));
            RS_VectorSolutions sol1;
			for(const RS_Vector& vp: sol0){
				if(RS_Math::isAngleBetween(intersections.at(i).angleTo(vp),
                                           pnew->entityAt(i)->getDirection2(),
                                           pnew->entityAt(i+1)->getDirection1(),
                                           false)==false){
					sol1.push_back(vp);
                }
            }
            if(sol1.getNumber()==0) continue;
            RS_Vector trimP(sol1.getClosest(intersections.at(i)));
            static_cast<RS_AtomicEntity*>(pnew->entityAt(i))->trimEndpoint(trimP);
            static_cast<RS_AtomicEntity*>(pnew->entityAt(i+1))->trimStartpoint(trimP);
        }else{
            RS_Vector trimP(sol0.getClosest(pnew->entityAt(i)->getStartpoint()));
            static_cast<RS_AtomicEntity*>(pnew->entityAt(i))->trimEndpoint(trimP);
            static_cast<RS_AtomicEntity*>(pnew->entityAt(i+1))->trimStartpoint(trimP);
        }

    }

    *this = *pnew;
    return true;


}
Esempio n. 10
0
	void compute_splines()
	{
		// get point tangents first
		std::cout << "HermiteSpline2D: compute_splines(): Getting tangents of boundary points." << std::endl;
		for(int ipoin = 0; ipoin < m->gnbpoin(); ipoin++)
		{
			// in 2D, bpoints is not an array of stl std::vectors - we know there are only two faces surrounding each boundary point
			// if edge is bounded by (x1,y1) and (x2,y2), tangent to edge is (x2-x1)i + (y2-y1)j

			// first check if this point belongs to a face that needs to be reconstructed
			if(toRec(m->gbpoints(ipoin,1))==1  || toRec(m->gbpoints(ipoin,2))==1)
			{

				std::vector<int> en(2);

				// get intfac faces containing this point
				en[0] = m->gbpoints(ipoin,1);
				en[1] = m->gbpoints(ipoin,2);
				//std::cout << en[0] << " " << en[1] << std::endl;

				double xt, yt, dotx = 1, doty = 1, mag;

				// iterate over the two faces containing ipoin
				for(int i = 0; i < 2; i++)
				{
					xt = m->gcoords(m->gintfac(en[i],3),0) - m->gcoords(m->gintfac(en[i],2),0);
					yt = m->gcoords(m->gintfac(en[i],3),1) - m->gcoords(m->gintfac(en[i],2),1);
					mag = sqrt(xt*xt + yt*yt);
					ptangents(m->gbpoints(ipoin,0),0) += xt;
					ptangents(m->gbpoints(ipoin,0),1) += yt;
					dotx *= xt/mag;
					doty *= yt/mag;
				}
				ptangents(m->gbpoints(ipoin,0),0) /= 2.0;
				ptangents(m->gbpoints(ipoin,0),1) /= 2.0;

				// now normalize the averaged tangent std::vector
				mag = sqrt(ptangents(m->gbpoints(ipoin,0),0)*ptangents(m->gbpoints(ipoin,0),0) + ptangents(m->gbpoints(ipoin,0),1)*ptangents(m->gbpoints(ipoin,0),1));
				ptangents(m->gbpoints(ipoin,0),0) /= mag;
				ptangents(m->gbpoints(ipoin,0),1) /= mag;

				// check if this is a corner point
				double dotp = dotx+doty;			// dot product of tangents of the two faces
				if(dotp < cos(angle_threshold)) { 
					isCorner(m->gbpoints(ipoin,0)) = 1;				// set isCorner for global point number corresponding to boundary point ipoin
					std::cout << "Boundary point " << m->gbpoints(ipoin,0) << " is a corner point!" << std::endl;
				}
			}
		}

		// iterate over boundary faces of the mesh
		std::cout << "HermiteSpline2D: compute_splines(): Iterating over boundary faces to get tangents." << std::endl;
		std::vector<int> pnts(m->gnnofa());		// to store point numbers of points making up iface
		for(int iface = 0; iface < m->gnbface(); iface++)
		{
			if(toRec(iface) == 1)
			{
				// get tangent for this face
				for(int inofa = 0; inofa < m->gnnofa(); inofa++)
					pnts[inofa] = m->gintfac(iface,inofa+2);

				// magnitude of tangent (x2-x1)i + (y2-y1)j
				double mag = sqrt((m->gcoords(pnts[1],0)-m->gcoords(pnts[0],0))*(m->gcoords(pnts[1],0)-m->gcoords(pnts[0],0)) + (m->gcoords(pnts[1],1)-m->gcoords(pnts[0],1))*(m->gcoords(pnts[1],1)-m->gcoords(pnts[0],1)));
				
				for(int inofa = 0; inofa < m->gnnofa(); inofa++)
				{
					if(isCorner(pnts[inofa]) == 0)		// if not a corner
					{
						gallfa(iface,2*inofa) = ptangents(pnts[inofa],0);
						gallfa(iface,2*inofa+1) = ptangents(pnts[inofa],1);
					}
					else								// if pnts[inofa] is a corner, use this face's tangent at that point
					{
						gallfa(iface,2*inofa) = (m->gcoords(pnts[1],0) - m->gcoords(pnts[0],0))/mag;
						gallfa(iface,2*inofa+1) = (m->gcoords(pnts[1],1) - m->gcoords(pnts[0],1))/mag;
					}
				}

				/* Note that gallfa(*,0) contains x-component of tangent at point 1, gallfa(*,1) contains y-component of tangent at point 1,
				    gallfa(*,2) contains x-component of tangent at point 2, and gallfa(*,3) contains y-component of tangent at points 2. */
			}
		}

		// iterate over boundary faces of mesh again to calculate geometric spline coeffs from gallfa and intfac
		std::cout << "HermiteSpline2d: compute_splines(): Iterating over boundary faces again to compute geometric coefficients of the splines" << std::endl;
		for(int iface = 0; iface < m->gnbface(); iface++)
			if(toRec(iface) == 1)
			{
				for(int idim = 0; idim < m->gndim(); idim++)
				{
					cf[idim](iface,0) = m->gcoords(m->gintfac(iface,2),idim);
					cf[idim](iface,1) = m->gcoords(m->gintfac(iface,3),idim);
					cf[idim](iface,2) = gallfa(iface,idim);
					cf[idim](iface,3) = gallfa(iface,idim+2);
				}
			}
	}
Esempio n. 11
0
bool AdobeThumbnail(const char* adobe_filename , const char* savejpeg_filename)
{
    string file_ext(adobe_filename);
    string rs = "(.+)(\\.(?:ai|AI|indd|INDD|Indd|eps|EPS|Eps))";  // 正则字符串,exp开始的单词
    std::regex expression(rs);                   // 字符串传递给构造函数,建立正则表达式
    bool ret = std::regex_match(file_ext, expression);
    if (!ret) {
        //      cout << "文件格式不对!\n";
        return ret ;
    }

    if (!IsFileExist(adobe_filename))
        return false ;     // 文件不存在


    char* pch = NULL;
    const char* flag = "pGImg:image";  // AI 和 Indd 稍微不同

    /// ************* 获取 ID或者AI文档 的预览图 **************** ///
    FILE* adobe_file = fopen(adobe_filename, "rb");
    size_t file_size = get_fileSize(adobe_filename); // 获得文件大小

    size_t bufsize = 1 * MBsize;        // AI 和EPS 预览图在开头,INDD文件在末位
    char* filebuf = new char[bufsize];  // 文件读到缓冲

    //  文件小于2M 整个文件读,否则遍历读最后2M
    if (file_size < bufsize) {
        bufsize = file_size;
        fread(filebuf, 1, bufsize, adobe_file);
        if (0xF5ED0606 == *(DWORD*)filebuf) { // indd 文件开头好像都这样
            pch = memfind(filebuf, flag , bufsize);   // INDD 可能不只一个预览图
            if ((pch != NULL))
                while ((pch != NULL) && (strlen(pch) < 10 * 1024))
                    pch = memfind(pch + 1, flag , bufsize - (pch - filebuf));

        } else
            pch = memfind(filebuf, flag , bufsize);

    } else {
        fread(filebuf, 1, bufsize, adobe_file);
//        00000000h: 06 06 ED F5 D8 1D 46 E5 BD 31 EF E7 FE 74 B7 1D ; ..眭?F褰1镧?
//        00000010h: 44 4F 43 55 4D 45 4E 54 01 70 0F 00 00 05 00 00 ; DOCUMENT.p......
        if (0xF5ED0606 == *(DWORD*)filebuf) { // indd 文件开头好像都这样
            fseek(adobe_file, (file_size - bufsize), SEEK_SET);
            fread(filebuf, 1, bufsize, adobe_file);

            pch = memfind(filebuf, flag , bufsize);   // INDD 可能不只一个预览图
            if ((pch != NULL))
                while ((pch != NULL) && (strlen(pch) < 10 * 1024))
                    pch = memfind(pch + 1, flag , bufsize - (pch - filebuf));

        } else
            pch = memfind(filebuf, flag , bufsize);   // AI 应该只有一个预览信息,
    }
    // 读取文件结束,关闭
    fclose(adobe_file);

    if (pch == NULL) {
        flag = "%AI7_Thumbnail:";
        size_t width, height, bitCount, Hexsize;
        char AI7_Thumbnail[64]; char BeginData[64]; char Hex_Bytes[64];

        pch = memfind(filebuf, flag , bufsize);
        // 检测到AI低版本预览图标记
        if (pch != NULL) {
            sscanf(pch, "%s %d %d %d\n%s %d %s\n", AI7_Thumbnail, &width, &height, &bitCount , BeginData, &Hexsize , Hex_Bytes);

            pch = memfind(filebuf, "Hex Bytes" , bufsize);
        }

        if (pch != NULL) {  // 解码 AI7_Thumbnail 为 图片
            char savepng_filename[MAX_PATH]={0};    // 源图是 BMP,保存png 失真少一点
            strncpy(savepng_filename , savejpeg_filename, strlen(savejpeg_filename) - 4);
            strcat(savepng_filename, ".png");

            string AI7Thumb(pch + 10 , Hexsize + 1);
            decode_Ai7Thumb_toPng(AI7Thumb , width, height , savepng_filename);
            delete[] filebuf; // 释放文件缓冲
            return true;
        }
    };

    if (pch == NULL)   ret = false;
    if (!ret) {  // 没有找到,返回前
        delete[] filebuf; // 释放文件缓冲
        return ret;
    }


    strtok(pch, "\r\n");
    string Base64_str(pch);

    std::regex ex("pGImg:image>|<\\/x\\wpGImg:image>|pGImg:image=\"");
    std::regex en("&#xA;");
    // 正则删除 xmpGImg 标记和 转意换行替换回来
    Base64_str = std::regex_replace(Base64_str, ex, string(""));
    Base64_str = std::regex_replace(Base64_str, en, string("\n"));

#if(AITEST)
        printf( "pGImg:image标记偏移: %d 在文件%s\n" , pch - filebuf , adobe_filename);
#endif
/// =============================== 解码一个Base64 的JPEG文件 ==============================////

    int b64len = Base64_str.size();
    int jpglen = fromBase64_Decode(Base64_str.c_str() , b64len , filebuf , b64len);

    FILE* jpeg_file = fopen(savejpeg_filename, "wb");
    fwrite(filebuf, 1 , jpglen , jpeg_file);


    delete[] filebuf; // 释放文件缓冲

    fclose(jpeg_file);

    return true;
}
Esempio n. 12
0
int main(int argc, char **argv)
{
  try{
    std::istream * inp;
    
    if (argc > 1)
      inp = new std::ifstream(argv[1]);
    else
      inp = & std::cin;
    
    //inp = new std::ifstream("2.qpp");

    std::vector<qpp::qpp_object*> decls;
    qpp::qpp_read(*inp,decls);

    std::vector<qpp::geometry<DIM> *> geom;
    std::vector<qpp::xtr_geometry<DIM> *> xgeom;
    std::vector<qpp::periodic_cell<DIM> *> cell;
    std::vector<qpp::zpattern<DIM>* > zpt;

    int nat;

    for (int i=0; i<decls.size(); i++)
      if (decls[i]->gettype() & qpp::qtype_geometry)
	geom.push_back((qpp::geometry<DIM>*)decls[i]);
      else if (decls[i]->gettype() & qpp::qtype_vectors)
	cell.push_back((qpp::periodic_cell<DIM>*)decls[i]);
      else if (decls[i]-> category() == "zpattern")
	zpt.push_back(qpp::decl2zpt<DIM,REAL,qpp::periodic_cell<DIM,REAL> >((qpp::qpp_declaration*)decls[i]));

    for (int i=0; i<geom.size(); i++)
      if (geom[i]->gettype() & qpp::qtype_xgeometry)
	xgeom.push_back((qpp::xtr_geometry<DIM>*)geom[i]);
      else
	xgeom.push_back(NULL);

    if (DIM==0)
      for (int i=0; i<geom.size(); i++)
	geom[i] -> cell = * new qpp::periodic_cell<0>;
    else
      for (int i=0; i<geom.size(); i++)
	geom[i] -> cell = *(cell[i]);
    
    for (int i=0; i<zpt.size(); i++)
      {

	zpt[i] -> write(std::cout);

	STRING pizda = zpt[i]->name() + ".xyz";
	std::ofstream xyz(pizda.c_str());

	for (int j=0; j<geom.size(); j++)
	  {
	    std::vector<double> en(geom[j]->nat(),0e0);

	    if (xgeom[j]!=NULL)
	      for (int k=0; k<xgeom[j]->nat(); k++)
		en[k] = xgeom[j] -> xtr_real(0,k);

	    // Energy correction to remedy Tersoff potentials 
	    /*
	    lace::vector3d<double> r0(0e0);
	    
	    for (int k=0; k<geom[j]->nat(); k++)
	      r0 += geom[j] -> position(i);

	    r0 /= geom[j]->nat();

	    double dist0,dist1;
	    for (int k=0; k<geom[j]->nat(); k++)
	      {
		double dist = norm(geom[j]->position(k)-r0);
		if (k==0)
		  {
		    dist0 = dist1 = dist;
		  }
		if (dist0>dist)
		  dist0 = dist;
		if (dist1 < dist)
		  dist1 = dist;
	      }
	    
	    for (int k=0; k<geom[j]->nat(); k++)
	      {
		en[k] -= coef * (norm(geom[j]->position(k)-r0)-dist0)/(dist1-dist0);
		xgeom[j] -> xtr_real(0,k) = en[k];
	      }
	    */
	    
	    zpt[i] -> init(*(geom[j]));

	    std::vector<std::vector<int> > matches;
	    std::vector<std::vector<double> > vals;
	    std::vector<double> cost;

	    zpt[i] -> search(matches,vals,cost);
	    
	    for (int k=0; k<matches.size(); k++)
	      //if (cost[k]<-32.)
	      {
		std::stringstream ss;
		
		ss << cost[k];
		
		for (int l=0; l<vals[k].size(); l++)
		  ss << " " << vals[k][l];
		
		for (int l=0; l< matches[k].size(); l++)
		  ss << " " << matches[k][l];
		
		std::cout << ss.str() << "\n";
	    
		qpp::geometry<DIM> g;
		g.copy(*geom[j]);

		// Colorize		
		for (int l=0; l<g.nat(); l++)
		  if (en[l] < good)
		    g.atom(l) = "N";
		  else if (en[l] > bad)
		    g.atom(l) = "O";
		
		// Show pattern
		for (int l=0; l< matches[k].size(); l++)
		  g.atom(matches[k][l]) = "B";
		
		g.setname(ss.str());
		
		qpp::write_xyz(xyz,g);
	      }

	    matches.clear();
	    vals.clear();
	    cost.clear();
	  }

	xyz.close();
      }    
  }
  catch (qpp::qpp_exception & e)
    {
      std::cout << e.what() << "\n";
      exit(1);
    }
}
Esempio n. 13
0
main()
{
	int i,j,key,num,b[20],p;
 	char ch;
aa: 
	window(1,1,25,80);
	textbackground(LIGHTGREEN);
	textcolor(YELLOW);
	clrscr();
	fu(b);
	num=0;
	p=0;
	textcolor(LIGHTRED);
	gotoxy(18,1);
	cprintf("%c(UP) %c(DOWN) %c(LEFT) %c(RIGHT)",24,25,27,26);
	gotoxy(16,2);
	cprintf("Eat the numbers in your road whose sum is 7,");
	gotoxy(14,3);
	cprintf("and eat 7 in the end, then you will win the game!");
	textcolor(MAGENTA);
	for(i=4;i<21;i++)
		for(j=20;j<44;j++)
			if(k[i-4][j-20]==0)
			{
				gotoxy(j,i);
				cprintf("%c",219);
			}
			else if(k[i-4][j-20]!=1)
			{
				gotoxy(j,i);
				cprintf("%d",k[i-4][j-20]);
			}
	textcolor(YELLOW);
	i=5;
	j=21;
	gotoxy(j,i);
	cprintf("\1");
	gotoxy(33,5);
	cprintf("7");
	gotoxy(7,7);
	cprintf("num:%d",num);
	textcolor(WHITE);
	gotoxy(11,22);
	cprintf("Press any key to start game, Q key to quit...");
	ch=getch();
	if(ch=='Q'||ch=='q')
	{
		window(1,1,25,80);
		textbackground(BLACK);
		textcolor(LIGHTGRAY);
		clrscr();
		exit(0);
	}
	else
	{
		textcolor(YELLOW);
		gotoxy(11,22);
		cprintf("                                             ");
	}
	do
	{
		key=bioskey(0);
		sound(200);
		delay(1000);
		nosound();
		switch(key)
		{
			case DOWN:
			{
				if(k[i-4+1][j-20]==0)
					continue;
				if(k[i-4+1][j-20]!=1&&k[i-4+1][j-20]!=7&&en(b,i+j+1))
				{
					num+=k[i-4+1][j-20];
					b[p++]=i+j+1;
					gotoxy(7,7);
					cprintf("num:%d",num);
				}
				textcolor(YELLOW);
				gotoxy(j,i++);
				printf(" ");
				gotoxy(j,i);
				cprintf("\1");
				gotoxy(33,5);
				if(k[i-4][j-20]==7&&num==7)
					wingame();
				else if(num!=7&&k[i-4][j-20]==7)
				{
					lostgame(num);
					goto aa;
				}
				break; 
			}
			case UP:
			{
				if(k[i-4-1][j-20]==0)
					continue;
				if(k[i-4-1][j-20]!=1&&k[i-4-1][j-20]!=7&&en(b,i+j-1))
				{
					num+=k[i-4-1][j-20];
					b[p++]=i+j-1;
					gotoxy(7,7);
					cprintf("num:%d",num);
				}
				textcolor(YELLOW);
				gotoxy(j,i--);
				printf(" ");
				gotoxy(j,i);
				cprintf("\1");
				gotoxy(33,5);
				if(k[i-4][j-20]==7&&num==7)
					wingame();
				else if(num!=7&&k[i-4][j-20]==7)
				{
					lostgame(num);
					goto aa;
				}
				break; 
			}
			case LEFT:
			{
				if(k[i-4][j-20-1]==0)
					continue;
				if(k[i-4][j-20-1]!=1&&k[i-4][j-20-1]!=7&&en(b,i+j-1))
				{
					num+=k[i-4][j-20-1];
					b[p++]=i+j-1;
					gotoxy(7,7);
					cprintf("num:%d",num);
				}
				textcolor(YELLOW);
				gotoxy(j--,i);
				printf(" ");
				gotoxy(j,i);
				cprintf("\1");
				gotoxy(33,5);
				if(k[i-4][j-20]==7&&num==7)
					wingame();
				else if(num!=7&&k[i-4][j-20]==7)
				{
					lostgame(num);
					goto aa;
				}
				break; 
			}
			case RIGHT:
			{
				if(k[i-4][j-20+1]==0)
					continue;
				if(k[i-4][j-20+1]!=1&&k[i-4][j-20+1]!=7&&en(b,i+j+1))
				{
					num+=k[i-4][j-20+1];
					b[p++]=i+j+1;
					gotoxy(7,7);
					cprintf("num:%d",num);
				}
				textcolor(YELLOW);
				gotoxy(j++,i);
				printf(" ");
				gotoxy(j,i);
				cprintf("\1");gotoxy(33,5);
				if(k[i-4][j-20]==7&&num==7)
					wingame();
				else if(num!=7&&k[i-4][j-20]==7)
				{
					lostgame(num);
					goto aa;
				}
				break; 
			}
			default:
				continue;
		}
	}while(1);
}
Esempio n. 14
0
RcppExport SEXP benchmarkEvals(SEXP bmS, SEXP parS, SEXP funS, SEXP envS) {

    Rcpp::List bm(bmS);
    int nsim = Rcpp::as<int>(bm["nsim"]);

    long neval = 0;
    Rcpp::NumericVector x(parS);

    Timer t;
    double v1 = 0, v2 = 0, v3 = 0, v4 = 0, v5 = 0, v6 = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v1 = evaluate1(&neval, x.begin(), x.size(), funS, envS);
    t.Stop();
    double t1 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v2 = evaluate2(&neval, x.begin(), x.size(), funS, envS);
    t.Stop();
    double t2 = t.ElapsedTime();

    Rcpp::Function fun(funS);
    Rcpp::Environment env(envS);

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v3 = evaluate3(&neval, x.begin(), x.size(), fun, env);
    t.Stop();
    double t3 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v4 = evaluate4(&neval, x.begin(), x.size(), fun, env);
    t.Stop();
    double t4 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    t.Start();
    for (int i=0; i<nsim; i++)
        v5 = evaluate5(neval, x, fun, env);
    t.Stop();
    double t5 = t.ElapsedTime();

    t.Reset();
    neval = 0;
    Rcpp::Function fc(fun);
    Rcpp::Environment en(env);
    t.Start();
    for (int i=0; i<nsim; i++)
        v6 = evaluate6(neval, x, fc, en);
    t.Stop();
    double t6 = t.ElapsedTime();

    return Rcpp::DataFrame::create(Rcpp::Named("times", Rcpp::NumericVector::create(t1, t2, t3, t4, t5, t6)),
                                   Rcpp::Named("values", Rcpp::NumericVector::create(v1, v2, v3, v4, v5, v6)));

}
/**
 * Test various generic API methods of PluralRules for API coverage.
 */
void PluralRulesTest::testAPI(/*char *par*/)
{
    UnicodeString pluralTestData[PLURAL_TEST_NUM] = {
            UNICODE_STRING_SIMPLE("a: n is 1"),
            UNICODE_STRING_SIMPLE("a: n mod 10 is 2"),
            UNICODE_STRING_SIMPLE("a: n is not 1"),
            UNICODE_STRING_SIMPLE("a: n mod 3 is not 1"),
            UNICODE_STRING_SIMPLE("a: n in 2..5"),
            UNICODE_STRING_SIMPLE("a: n within 2..5"),
            UNICODE_STRING_SIMPLE("a: n not in 2..5"),
            UNICODE_STRING_SIMPLE("a: n not within 2..5"),
            UNICODE_STRING_SIMPLE("a: n mod 10 in 2..5"),
            UNICODE_STRING_SIMPLE("a: n mod 10 within 2..5"),
            UNICODE_STRING_SIMPLE("a: n mod 10 is 2 and n is not 12"),
            UNICODE_STRING_SIMPLE("a: n mod 10 in 2..3 or n mod 10 is 5"),
            UNICODE_STRING_SIMPLE("a: n mod 10 within 2..3 or n mod 10 is 5"),
            UNICODE_STRING_SIMPLE("a: n is 1 or n is 4 or n is 23"),
            UNICODE_STRING_SIMPLE("a: n mod 2 is 1 and n is not 3 and n in 1..11"),
            UNICODE_STRING_SIMPLE("a: n mod 2 is 1 and n is not 3 and n within 1..11"),
            UNICODE_STRING_SIMPLE("a: n mod 2 is 1 or n mod 5 is 1 and n is not 6"),
            "",
    };
    static const int32_t pluralTestResult[PLURAL_TEST_NUM][30] = {
        {1, 0},
        {2,12,22, 0},
        {0,2,3,4,5,0},
        {0,2,3,5,6,8,9,0},
        {2,3,4,5,0},
        {2,3,4,5,0},
        {0,1,6,7,8, 0},
        {0,1,6,7,8, 0},
        {2,3,4,5,12,13,14,15,22,23,24,25,0},
        {2,3,4,5,12,13,14,15,22,23,24,25,0},
        {2,22,32,42,0},
        {2,3,5,12,13,15,22,23,25,0},
        {2,3,5,12,13,15,22,23,25,0},
        {1,4,23,0},
        {1,5,7,9,11,0},
        {1,5,7,9,11,0},
        {1,3,5,7,9,11,13,15,16,0},
    };
    UErrorCode status = U_ZERO_ERROR;

    // ======= Test constructors
    logln("Testing PluralRules constructors");


    logln("\n start default locale test case ..\n");

    PluralRules defRule(status);
    LocalPointer<PluralRules> test(new PluralRules(status));
    LocalPointer<PluralRules> newEnPlural(test->forLocale(Locale::getEnglish(), status));
    if(U_FAILURE(status)) {
        dataerrln("ERROR: Could not create PluralRules (default) - exitting");
        return;
    }

    // ======= Test clone, assignment operator && == operator.
    LocalPointer<PluralRules> dupRule(defRule.clone());
    if (dupRule==NULL) {
        errln("ERROR: clone plural rules test failed!");
        return;
    } else {
        if ( *dupRule != defRule ) {
            errln("ERROR:  clone plural rules test failed!");
        }
    }
    *dupRule = *newEnPlural;
    if (dupRule!=NULL) {
        if ( *dupRule != *newEnPlural ) {
            errln("ERROR:  clone plural rules test failed!");
        }
    }

    // ======= Test empty plural rules
    logln("Testing Simple PluralRules");

    LocalPointer<PluralRules> empRule(test->createRules(UNICODE_STRING_SIMPLE("a:n"), status));
    UnicodeString key;
    for (int32_t i=0; i<10; ++i) {
        key = empRule->select(i);
        if ( key.charAt(0)!= 0x61 ) { // 'a'
            errln("ERROR:  empty plural rules test failed! - exitting");
        }
    }

    // ======= Test simple plural rules
    logln("Testing Simple PluralRules");

    char result[100];
    int32_t max;

    for (int32_t i=0; i<PLURAL_TEST_NUM-1; ++i) {
       LocalPointer<PluralRules> newRules(test->createRules(pluralTestData[i], status));
       setupResult(pluralTestResult[i], result, &max);
       if ( !checkEqual(*newRules, result, max) ) {
            errln("ERROR:  simple plural rules failed! - exitting");
            return;
        }
    }

    // ======= Test complex plural rules
    logln("Testing Complex PluralRules");
    // TODO: the complex test data is hard coded. It's better to implement
    // a parser to parse the test data.
    UnicodeString complexRule = UNICODE_STRING_SIMPLE("a: n in 2..5; b: n in 5..8; c: n mod 2 is 1");
    UnicodeString complexRule2 = UNICODE_STRING_SIMPLE("a: n within 2..5; b: n within 5..8; c: n mod 2 is 1");
    char cRuleResult[] =
    {
       0x6F, // 'o'
       0x63, // 'c'
       0x61, // 'a'
       0x61, // 'a'
       0x61, // 'a'
       0x61, // 'a'
       0x62, // 'b'
       0x62, // 'b'
       0x62, // 'b'
       0x63, // 'c'
       0x6F, // 'o'
       0x63  // 'c'
    };
    LocalPointer<PluralRules> newRules(test->createRules(complexRule, status));
    if ( !checkEqual(*newRules, cRuleResult, 12) ) {
         errln("ERROR:  complex plural rules failed! - exitting");
         return;
    }
    newRules.adoptInstead(test->createRules(complexRule2, status));
    if ( !checkEqual(*newRules, cRuleResult, 12) ) {
         errln("ERROR:  complex plural rules failed! - exitting");
         return;
    }

    // ======= Test decimal fractions plural rules
    UnicodeString decimalRule= UNICODE_STRING_SIMPLE("a: n not in 0..100;");
    UnicodeString KEYWORD_A = UNICODE_STRING_SIMPLE("a");
    status = U_ZERO_ERROR;
    newRules.adoptInstead(test->createRules(decimalRule, status));
    if (U_FAILURE(status)) {
        dataerrln("ERROR: Could not create PluralRules for testing fractions - exitting");
        return;
    }
    double fData[] =     {-101, -100, -1,     -0.0,  0,     0.1,  1,     1.999,  2.0,   100,   100.001 };
    UBool isKeywordA[] = {TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE,   FALSE, FALSE, TRUE };
    for (int32_t i=0; i<LENGTHOF(fData); i++) {
        if ((newRules->select(fData[i])== KEYWORD_A) != isKeywordA[i]) {
             errln("File %s, Line %d, ERROR: plural rules for decimal fractions test failed!\n"
                   "  number = %g, expected %s", __FILE__, __LINE__, fData[i], isKeywordA[i]?"TRUE":"FALSE");
        }
    }

    // ======= Test Equality
    logln("Testing Equality of PluralRules");

    if ( !testEquality(*test) ) {
         errln("ERROR:  complex plural rules failed! - exitting");
         return;
     }


    // ======= Test getStaticClassID()
    logln("Testing getStaticClassID()");

    if(test->getDynamicClassID() != PluralRules::getStaticClassID()) {
        errln("ERROR: getDynamicClassID() didn't return the expected value");
    }
    // ====== Test fallback to parent locale
    LocalPointer<PluralRules> en_UK(test->forLocale(Locale::getUK(), status));
    LocalPointer<PluralRules> en(test->forLocale(Locale::getEnglish(), status));
    if (en_UK.isValid() && en.isValid()) {
        if ( *en_UK != *en ) {
            errln("ERROR:  test locale fallback failed!");
        }
    }

    LocalPointer<PluralRules> zh_Hant(test->forLocale(Locale::getTaiwan(), status));
    LocalPointer<PluralRules> zh(test->forLocale(Locale::getChinese(), status));
    if (zh_Hant.isValid() && zh.isValid()) {
        if ( *zh_Hant != *zh ) {
            errln("ERROR:  test locale fallback failed!");
        }
    }
}
Esempio n. 16
0
// Prints the client info
string CNSClient::Print(const string &               node_name,
                        const CQueue *               queue,
                        const CNSAffinityRegistry &  aff_registry,
                        const set< string > &        wn_gc_clients,
                        const set< string > &        read_gc_clients,
                        bool                         verbose) const
{
    string      buffer;

    buffer += "OK:CLIENT: '" + node_name + "'\n"
              "OK:  STATUS: " + x_StateAsString() + "\n"
              "OK:  PREFERRED AFFINITIES RESET: ";
    if (m_WNData.m_AffReset) buffer += "TRUE\n";
    else                     buffer += "FALSE\n";

    buffer += "OK:  READER PREFERRED AFFINITIES RESET: ";
    if (m_ReaderData.m_AffReset) buffer += "TRUE\n";
    else                         buffer += "FALSE\n";

    if (m_LastAccess == kTimeZero)
        buffer += "OK:  LAST ACCESS: n/a\n";
    else
        buffer += "OK:  LAST ACCESS: " +
                  NS_FormatPreciseTime(m_LastAccess) + "\n";

    if (m_SessionStartTime == kTimeZero)
        buffer += "OK:  SESSION START TIME: n/a\n";
    else
        buffer += "OK:  SESSION START TIME: " +
                  NS_FormatPreciseTime(m_SessionStartTime) + "\n";

    if (m_RegistrationTime == kTimeZero)
        buffer += "OK:  REGISTRATION TIME: n/a\n";
    else
        buffer += "OK:  REGISTRATION TIME: " +
                  NS_FormatPreciseTime(m_RegistrationTime) + "\n";

    if (m_SessionResetTime == kTimeZero)
        buffer += "OK:  SESSION RESET TIME: n/a\n";
    else
        buffer += "OK:  SESSION RESET TIME: " +
                  NS_FormatPreciseTime(m_SessionResetTime) + "\n";

    buffer += "OK:  PEER ADDRESS: " + CSocketAPI::gethostbyaddr(m_Addr) + "\n";

    buffer += "OK:  CLIENT HOST: ";
    if (m_ClientHost.empty())
        buffer += "n/a\n";
    else
        buffer += m_ClientHost + "\n";

    buffer += "OK:  WORKER NODE CONTROL PORT: ";
    if (m_ControlPort == 0)
       buffer += "n/a\n";
    else
       buffer += NStr::NumericToString(m_ControlPort) + "\n";

    if (m_Session.empty())
        buffer += "OK:  SESSION: n/a\n";
    else
        buffer += "OK:  SESSION: '" + m_Session + "'\n";

    buffer += "OK:  TYPE: " + x_TypeAsString() + "\n";

    buffer += "OK:  NUMBER OF SUBMITTED JOBS: " +
              NStr::NumericToString(m_NumberOfSubmitted) + "\n";

    // The Print() member is called under a lock in the client registry so it
    // is safe here to get access to a const reference of the blacklisted jobs
    // vector
    const TNSBitVector &    wn_blacklist = m_WNData.GetBlacklistedJobsRef();
    buffer += "OK:  NUMBER OF BLACKLISTED JOBS: " +
              NStr::NumericToString(wn_blacklist.count()) + "\n";
    if (verbose && wn_blacklist.any()) {
        buffer += "OK:  BLACKLISTED JOBS:\n";

        TNSBitVector::enumerator    en(wn_blacklist.first());
        for ( ; en.valid(); ++en) {
            unsigned int    job_id = *en;
            TJobStatus      status = queue->GetJobStatus(job_id);
            buffer += "OK:    " + queue->MakeJobKey(job_id) + " " +
                      m_WNData.GetBlacklistLimit(job_id) + " " +
                      CNetScheduleAPI::StatusToString(status) + "\n";
        }
    }

    // The Print() member is called under a lock in the client registry so it
    // is safe here to get access to a const reference of the blacklisted jobs
    // vector
    const TNSBitVector &  rd_blacklist = m_ReaderData.GetBlacklistedJobsRef();
    buffer += "OK:  NUMBER OF READ BLACKLISTED JOBS: " +
              NStr::NumericToString(rd_blacklist.count()) + "\n";
    if (verbose && rd_blacklist.any()) {
        buffer += "OK:  READ BLACKLISTED JOBS:\n";

        TNSBitVector::enumerator    en(rd_blacklist.first());
        for ( ; en.valid(); ++en) {
            unsigned int    job_id = *en;
            TJobStatus      status = queue->GetJobStatus(job_id);
            buffer += "OK:    " + queue->MakeJobKey(job_id) + " " +
                      m_ReaderData.GetBlacklistLimit(job_id) + " " +
                      CNetScheduleAPI::StatusToString(status) + "\n";
        }
    }

    buffer += "OK:  NUMBER OF RUNNING JOBS: " +
              NStr::NumericToString(m_WNData.m_Jobs.count()) + "\n";
    if (verbose && m_WNData.m_Jobs.any()) {
        buffer += "OK:  RUNNING JOBS:\n";

        TNSBitVector::enumerator    en(m_WNData.m_Jobs.first());
        for ( ; en.valid(); ++en)
            buffer += "OK:    " + queue->MakeJobKey(*en) + "\n";
    }

    buffer += "OK:  NUMBER OF JOBS GIVEN FOR EXECUTION: " +
              NStr::NumericToString(m_WNData.m_NumberOfGiven) + "\n";

    buffer += "OK:  NUMBER OF READING JOBS: " +
              NStr::NumericToString(m_ReaderData.m_Jobs.count()) + "\n";
    if (verbose && m_ReaderData.m_Jobs.any()) {
        buffer += "OK:  READING JOBS:\n";

        TNSBitVector::enumerator    en(m_ReaderData.m_Jobs.first());
        for ( ; en.valid(); ++en)
            buffer += "OK:    " + queue->MakeJobKey(*en) + "\n";
    }

    buffer += "OK:  NUMBER OF JOBS GIVEN FOR READING: " +
              NStr::NumericToString(m_ReaderData.m_NumberOfGiven) + "\n";

    buffer += "OK:  NUMBER OF PREFERRED AFFINITIES: " +
              NStr::NumericToString(m_WNData.m_PrefAffinities.count()) + "\n";
    if (verbose && m_WNData.m_PrefAffinities.any()) {
        buffer += "OK:  PREFERRED AFFINITIES:\n";

        TNSBitVector::enumerator    en(m_WNData.m_PrefAffinities.first());
        for ( ; en.valid(); ++en)
            buffer += "OK:    '" + aff_registry.GetTokenByID(*en) + "'\n";
    }

    buffer += "OK:  NUMBER OF REQUESTED AFFINITIES: " +
              NStr::NumericToString(m_WNData.m_WaitAffinities.count()) + "\n";
    if (verbose && m_WNData.m_WaitAffinities.any()) {
        buffer += "OK:  REQUESTED AFFINITIES:\n";

        TNSBitVector::enumerator    en(m_WNData.m_WaitAffinities.first());
        for ( ; en.valid(); ++en)
            buffer += "OK:    '" + aff_registry.GetTokenByID(*en) + "'\n";
    }

    buffer += "OK:  NUMBER OF READER PREFERRED AFFINITIES: " +
              NStr::NumericToString(m_ReaderData.m_PrefAffinities.count()) +
              "\n";
    if (verbose && m_ReaderData.m_PrefAffinities.any()) {
        buffer += "OK:  READER PREFERRED AFFINITIES:\n";

        TNSBitVector::enumerator    en(m_ReaderData.m_PrefAffinities.first());
        for ( ; en.valid(); ++en)
            buffer += "OK:    '" + aff_registry.GetTokenByID(*en) + "'\n";
    }

    buffer += "OK:  NUMBER OF READER REQUESTED AFFINITIES: " +
              NStr::NumericToString(m_ReaderData.m_WaitAffinities.count()) +
              "\n";
    if (verbose && m_ReaderData.m_WaitAffinities.any()) {
        buffer += "OK:  READER REQUESTED AFFINITIES:\n";

        TNSBitVector::enumerator    en(m_ReaderData.m_WaitAffinities.first());
        for ( ; en.valid(); ++en)
            buffer += "OK:    '" + aff_registry.GetTokenByID(*en) + "'\n";
    }

    buffer += "OK:  NUMBER OF SOCKET WRITE ERRORS: " +
              NStr::NumericToString(m_NumberOfSockErrors) + "\n"
              "OK:  DATA: '" + NStr::PrintableString(m_ClientData) + "'\n"
              "OK:  DATA VERSION: " +
                    NStr::NumericToString(m_ClientDataVersion) + "\n";

    if (wn_gc_clients.find(node_name) == wn_gc_clients.end())
        buffer += "OK:  WN AFFINITIES GARBAGE COLLECTED: FALSE\n";
    else
        buffer += "OK:  WN AFFINITIES GARBAGE COLLECTED: TRUE\n";

    if (read_gc_clients.find(node_name) == read_gc_clients.end())
        buffer += "OK:  READER AFFINITIES GARBAGE COLLECTED: FALSE\n";
    else
        buffer += "OK:  READER AFFINITIES GARBAGE COLLECTED: TRUE\n";
    buffer += "OK:  LAST SCOPE: '" + m_LastScope + "'\n";

    return buffer;
}