Esempio n. 1
0
std::time_t
vishnu::string_lc_to_utc_time_t(const std::string& ts,const std::string& utcOffset) {

  // two aliases for convenience
  namespace bps= boost::posix_time;
  namespace bg=boost::gregorian;
  namespace blt=boost::local_time;

  std::cout << " convert " << ts << " " << utcOffset << " in utc time\n";

  boost::local_time::time_zone_ptr tz(new boost::local_time::posix_time_zone(utcOffset));

  bps::ptime t;

  if (std::string::npos==ts.find(":")){
    t=bps::ptime(bg::from_string(ts));

  }
  else{
    t= bps::ptime (bps::time_from_string(ts));
  }

  bps::ptime epoch(bg::date(1970,1,1));

  blt::local_date_time ldt(t.date(), t.time_of_day(),tz,blt::local_date_time::NOT_DATE_TIME_ON_ERROR);

  bps::time_duration::sec_type x = (ldt.utc_time() - epoch).total_seconds();

  return std::time_t(x);

}
Esempio n. 2
0
void LClock::LocaleChange(){
  //Refresh all the time zone information
  TZMenu->clear();
    TZMenu->addAction(tr("Use System Time"));
    TZMenu->addSeparator();
  QList<QByteArray> TZList = QTimeZone::availableTimeZoneIds();
  //Orgnize time zones for smaller menus (Continent/Country/City)
  // Note: id = Continent/City
  QStringList info;
  for(int i=0; i<TZList.length(); i++){
    QTimeZone tz(TZList[i]);
    if(!QString(tz.id()).contains("/")){ continue; }
    info << "::::"+QString(tz.id()).section("/",0,0)+"::::"+QLocale::countryToString(tz.country())+"::::"+QString(tz.id()).section("/",1,100).replace("_"," ")+"::::"+QString(tz.id());
  }
  //Now sort alphabetically
  info.sort();
  //Now create the menu tree
  QString continent, country; //current continent/country
  QMenu *tmpC=0; //continent menu
  QMenu *tmpCM=0; //country menu
  for(int i=0; i<info.length(); i++){
    //Check if different continent
    if(info[i].section("::::",1,1)!=continent){
      if(tmpC!=0){
        if(tmpCM!=0 && !tmpCM->isEmpty()){
	  tmpC->addMenu(tmpCM);
	}
	if(!tmpC->isEmpty()){ TZMenu->addMenu(tmpC); }
      }
      tmpC = new QMenu(this);
	tmpC->setTitle(info[i].section("::::",1,1));
      tmpCM = new QMenu(this);
	  tmpCM->setTitle(info[i].section("::::",2,2));
    //Check if different country
    }else if(info[i].section("::::",2,2)!=country){
        if(tmpC!=0 && tmpCM!=0 && !tmpCM->isEmpty()){
	  tmpC->addMenu(tmpCM);
	}
	tmpCM = new QMenu(this);
	  tmpCM->setTitle(info[i].section("::::",2,2));
    }
    //Now create the entry within the country menu
    if(tmpCM!=0){
      QAction *act = new QAction(info[i].section("::::",3,3), this);
	act->setWhatsThis(info[i].section("::::",4,4) );
      tmpCM->addAction(act);
    }
    //Save the values for the next run
    continent = info[i].section("::::",1,1);
    country = info[i].section("::::",2,2);

    if(i== info.length()-1){
      //last go through - save all menus
      if(tmpCM!=0 && tmpC!=0 && !tmpCM->isEmpty()){ tmpC->addMenu(tmpCM); }
      if(tmpC!=0 && !tmpC->isEmpty()){ TZMenu->addMenu(tmpC); }
    }
  }
  
}
int ONVIF::SystemDateAndTime::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 6)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 6;
    } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
        if (_id < 6)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 6;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< DateTimeType*>(_v) = dateTimeType(); break;
        case 1: *reinterpret_cast< bool*>(_v) = daylightSavings(); break;
        case 2: *reinterpret_cast< QString*>(_v) = tz(); break;
        case 3: *reinterpret_cast< QDateTime*>(_v) = utcTime(); break;
        case 4: *reinterpret_cast< QDateTime*>(_v) = localTime(); break;
        case 5: *reinterpret_cast< bool*>(_v) = result(); break;
        default: break;
        }
        _id -= 6;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: setDateTimeType(*reinterpret_cast< DateTimeType*>(_v)); break;
        case 1: setDaylightSavings(*reinterpret_cast< bool*>(_v)); break;
        case 2: setTz(*reinterpret_cast< QString*>(_v)); break;
        case 3: setutcTime(*reinterpret_cast< QDateTime*>(_v)); break;
        case 4: setlocalTime(*reinterpret_cast< QDateTime*>(_v)); break;
        case 5: setResult(*reinterpret_cast< bool*>(_v)); break;
        default: break;
        }
        _id -= 6;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 6;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 6;
    } else if (_c == QMetaObject::RegisterPropertyMetaType) {
        if (_id < 6)
            *reinterpret_cast<int*>(_a[0]) = -1;
        _id -= 6;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
Esempio n. 4
0
void mmReportBudget::SetBudgetMonth(wxString budgetYearStr, wxDateTime& startDate, wxDateTime& endDate) const
{
    wxStringTokenizer tz(budgetYearStr,"-");
    wxString yearStr = tz.GetNextToken();
    wxString monthStr = tz.GetNextToken();
    int month = wxAtoi(monthStr) - 1;
    startDate.SetMonth((wxDateTime::Month)month);
    SetDateToEndOfMonth(month,endDate);
}
Esempio n. 5
0
/*
 Update a single route segment lengths
 Also, compute total route length by summing segment distances.
 */
void Route::UpdateSegmentDistance( RoutePoint *prp0, RoutePoint *prp, double planspeed )
{
    double slat1 = prp0->m_lat, slon1 = prp0->m_lon;
    double slat2 = prp->m_lat, slon2 = prp->m_lon;

//    Calculate the absolute distance from 1->2

    double dd;
    // why are we using mercator rather than great circle here?? [sean 8-11-2015]
    DistanceBearingMercator( slat1, slon1, slat2, slon2, 0, &dd );

//    And store in Point 2
    prp->m_seg_len = dd;

    m_route_length += dd;

//    If Point1 Description contains VMG, store it for Properties Dialog in Point2
//    If Point1 Description contains ETD, store it in Point1

    if( planspeed > 0. ) {
        double vmg = 0.0;
        wxDateTime etd;

        if( prp0->m_MarkDescription.Find( _T("VMG=") ) != wxNOT_FOUND ) {
            wxString s_vmg = ( prp0->m_MarkDescription.Mid(
                                   prp0->m_MarkDescription.Find( _T("VMG=") ) + 4 ) ).BeforeFirst( ';' );
            if( !s_vmg.ToDouble( &vmg ) ) vmg = planspeed;
        }

        double legspeed = planspeed;
        if( vmg > 0.1 && vmg < 1000. ) legspeed = vmg;
        if( legspeed > 0.1 && legspeed < 1000. ) {
            m_route_time += 3600. * dd / legspeed;
            prp->m_seg_vmg = legspeed;
        }

        prp0->m_seg_etd = wxInvalidDateTime;
        if( prp0->m_MarkDescription.Find( _T("ETD=") ) != wxNOT_FOUND ) {
            wxString s_etd = ( prp0->m_MarkDescription.Mid(
                                   prp0->m_MarkDescription.Find( _T("ETD=") ) + 4 ) ).BeforeFirst( ';' );
            const wxChar *parse_return = etd.ParseDateTime( s_etd );
            if( parse_return ) {
                wxString tz( parse_return );

                if( tz.Find( _T("UT") ) != wxNOT_FOUND ) prp0->m_seg_etd = etd;
                else
                    if( tz.Find( _T("LMT") ) != wxNOT_FOUND ) {
                        prp0->m_seg_etd = etd;
                        long lmt_offset = (long) ( ( prp0->m_lon * 3600. ) / 15. );
                        wxTimeSpan lmt( 0, 0, (int) lmt_offset, 0 );
                        prp0->m_seg_etd -= lmt;
                    } else
                        prp0->m_seg_etd = etd.ToUTC();
            }
        }
    }
}
bool MrPlotter::setTimeZone(QByteArray timezone)
{
    QTimeZone tz(timezone);
    if (!tz.isValid())
    {
        return false;
    }
    this->timeaxis.setTimeZone(tz);
    return false;
}
Esempio n. 7
0
 inline auto make_parameter_memory_pair(
   onnx::NodeProto const& node, int param_index,
   mkldnn::memory::format format,
   std::unordered_map<std::string, instant::array> const& parameter_table,
   mkldnn::engine const& engine) {
     auto const& name = node.input(param_index);
     auto const& arr = find_value(parameter_table, name);
     mkldnn::memory::dims tz(arr.dims().begin(), arr.dims().end());
     auto mem = mkldnn::memory(
       {{{tz}, mkldnn::memory::data_type::f32, format}, engine},
       const_cast<void*>(arr.data()));
     return std::make_pair(name, mem);
 }
Esempio n. 8
0
static void init_env (void)
{
#ifndef USE_PAM
	char *cp;
#endif
	char *tmp;

	tmp = getenv ("LANG");
	if (NULL != tmp) {
		addenv ("LANG", tmp);
	}

	/*
	 * Add the timezone environmental variable so that time functions
	 * work correctly.
	 */
	tmp = getenv ("TZ");
	if (NULL != tmp) {
		addenv ("TZ", tmp);
	}
#ifndef USE_PAM
	else {
		cp = getdef_str ("ENV_TZ");
		if (NULL != cp) {
			addenv (('/' == *cp) ? tz (cp) : cp, NULL);
		}
	}
#endif				/* !USE_PAM */
	/* 
	 * Add the clock frequency so that profiling commands work
	 * correctly.
	 */
	tmp = getenv ("HZ");
	if (NULL != tmp) {
		addenv ("HZ", tmp);
	}
#ifndef USE_PAM
	else {
		cp = getdef_str ("ENV_HZ");
		if (NULL != cp) {
			addenv (cp, NULL);
		}
	}
#endif				/* !USE_PAM */
}
Esempio n. 9
0
void Fractal::Mandel2Init (void)
{
    static const char *info[] = {
      "\ebMandelbrot set for\eb",
      mandel2_size, (const char *) mandel2_bits,
      "",
      "",
      "The image plane of the complex valued parameter \etmu\et",
      "with Re=(x1..x2) and Im=(y1..y2) is drawn.",
      "The complex start value \etz(0)\et of the iteration can be",
      "set in the Args(Re,Im) field (default is 0).",
      NULL
    };
    Info = info;
    FractalMethod = &Fractal::Mandel2;
    xLo = -2.5, xHi = 1.5;  yLo = -1.5; yHi = 1.5;
    xParm = yParm = 0;	// usually start with z(0) = (0,0)
}
Esempio n. 10
0
//---------------------------------------------------------
void NDG3D::Normals3D()
//---------------------------------------------------------
{
  // function [nx, ny, nz, sJ] = Normals3D()
  // Purpose : Compute outward pointing normals at
  //	    elements faces as well as surface Jacobians

  GeometricFactors3D();

  // interpolate geometric factors to face nodes
  DMat frx=rx(Fmask,All),  fsx=sx(Fmask,All),  ftx=tx(Fmask,All);
  DMat fry=ry(Fmask,All),  fsy=sy(Fmask,All),  fty=ty(Fmask,All);
  DMat frz=rz(Fmask,All),  fsz=sz(Fmask,All),  ftz=tz(Fmask,All);

  // build normals
  nx.resize(4*Nfp, K); ny.resize(4*Nfp, K); nz.resize(4*Nfp, K);
  Index1D fid1(1,Nfp), fid2(Nfp+1,2*Nfp), fid3(2*Nfp+1,3*Nfp), fid4(3*Nfp+1,4*Nfp);

  // face 1
  nx(fid1, All) = -ftx(fid1,All);
  ny(fid1, All) = -fty(fid1,All);
  nz(fid1, All) = -ftz(fid1,All);

  // face 2
  nx(fid2, All) = -fsx(fid2,All);
  ny(fid2, All) = -fsy(fid2,All);
  nz(fid2, All) = -fsz(fid2,All);

  // face 3
  nx(fid3, All) = frx(fid3,All) + fsx(fid3,All) + ftx(fid3,All);
  ny(fid3, All) = fry(fid3,All) + fsy(fid3,All) + fty(fid3,All);
  nz(fid3, All) = frz(fid3,All) + fsz(fid3,All) + ftz(fid3,All);

  // face 4
  nx(fid4, All) = -frx(fid4,All);
  ny(fid4, All) = -fry(fid4,All);
  nz(fid4, All) = -frz(fid4,All);

  // normalise
  sJ = sqrt(sqr(nx) + sqr(ny) + sqr(nz));
  
  nx.div_element(sJ); ny.div_element(sJ); nz.div_element(sJ);
  sJ.mult_element(J(Fmask, All));  //sJ=sJ.*J(Fmask(:),:);
}
Esempio n. 11
0
 inline auto make_variable_memory_table(
   std::vector<std::tuple<std::string, instant::array,
                          mkldnn::memory::format>>& input_list,
   mkldnn::engine const& engine) {
     std::unordered_map<
       std::string, std::tuple<const mkldnn::memory, mkldnn::memory::format>>
       memory_table;
     for(auto& input : input_list) {
         auto& arr = std::get<1>(input);
         auto format = std::get<2>(input);
         mkldnn::memory::dims tz(arr.dims().begin(), arr.dims().end());
         auto mem = mkldnn::memory(
           {{{tz}, mkldnn::memory::data_type::f32, format}, engine},
           arr.data());
         auto const& name = std::get<0>(input);
         memory_table.insert({name, std::make_tuple(mem, format)});
     }
     return memory_table;
 }
Esempio n. 12
0
void read_temperature(VectorScalar &T0, VectorScalar &Tz, const std::string &file)
{
  T0.clear();
  Tz.clear();
  std::string line;
  std::ifstream temp(file);
  getline(temp,line);
  while(!temp.eof())
  {
     Scalar t(0.),tz(0.);
     temp >> t >> tz;
     if(temp.good())
     {
       T0.push_back(t);
       Tz.push_back(tz);
     }
  }
  temp.close();
  return;
}
Esempio n. 13
0
void ZDAmsg::setMsg(std::string msg){
    boost::regex reg("^(\\d{2})(\\d{2})(\\d{2})(\\.\\d{1,3})?,(\\d{2}),(\\d{2}),(\\d{4}),(\\d{2}),(\\d{2})$");
    boost::cmatch matches;
    if(boost::regex_search(msg.c_str(), matches, reg)){
        std::string ts(matches[MATCH_YEAR]+"-"+matches[MATCH_MONTH]+"-"+matches[MATCH_DAY]+" "+matches[MATCH_HOUR]+":"+matches[MATCH_MINUTE]+":"+matches[MATCH_SECOND]+matches[MATCH_SUBSECOND]);
        try{
            std::string sign = (boost::lexical_cast<int>(matches[MATCH_ZONE_HOURS])>=0?"+":"-");
            std::string tz("UTC"+sign+matches[MATCH_ZONE_HOURS]+":"+matches[MATCH_ZONE_MINUTES]);
            zone = boost::local_time::posix_time_zone(tz);
            time_date = boost::posix_time::time_from_string(ts);
        }
        catch(const boost::bad_lexical_cast&){
            std::cerr << "Problem with command format. Cannot parse date:" << ts << std::endl;
            return;
        }
    }
    else{
        throw std::invalid_argument("Cannot parse RMC message!");
    }
}
Esempio n. 14
0
void DateTimeTester::timeZones()
{
    QByteArray tz("TZ=Europe/Copenhagen");
    putenv(tz.data());
    
    QTimeZone testZone("Europe/London");
    
    DateTime dt1(QDate(2006, 1, 1), QTime(8, 0, 0, 0 ), testZone);
    
    DateTime dt2 = dt1;
    qDebug()<<dt1<<dt2;
    QCOMPARE(dt1.timeZone(), dt2.timeZone());
    
    dt2 += Duration(1, 0, 0, 0, 0);
    qDebug()<<dt2;
    QCOMPARE(dt1.timeZone(), dt2.timeZone());
    
    dt2 -= Duration(1, 0, 0, 0, 0);
    qDebug()<<dt1<<dt2;
    QCOMPARE(dt1.timeZone(), dt2.timeZone());
    QCOMPARE(dt2, dt1);
    
    dt2 = dt1 + Duration(1, 0, 0, 0, 0);
    qDebug()<<dt1<<dt2;
    QCOMPARE(dt1.timeZone(), dt2.timeZone());

    dt2 = dt2 - Duration(1, 0, 0, 0, 0);
    qDebug()<<dt1<<dt2;
    QCOMPARE(dt1.timeZone(), dt2.timeZone());
    QCOMPARE(dt2, dt1);
    
    DateTime dt3 = QDateTime(QDate(2006, 1, 1), QTime(8, 0, 0, 0 ), testZone);
    qDebug()<<dt3;
    QCOMPARE(dt3.timeZone(), testZone);
    
    DateTime dt4(QDateTime(QDate(2006, 1, 1), QTime(8, 0, 0, 0 ), Qt::UTC));
    dt4 += Duration(1, 0, 0, 0, 0);
    qDebug()<<dt4;
    QCOMPARE(dt4.timeSpec(), Qt::UTC);
    
}
Esempio n. 15
0
wxDateTime RoutePoint::GetETD()
{
    if( m_seg_etd.IsValid() ) {
        if(!GetETA().IsValid() || m_seg_etd > GetETA()) {
            return m_seg_etd;
        } else {
            return GetETA();
        }
    } else {
        if( m_MarkDescription.Find( _T("ETD=") ) != wxNOT_FOUND ) {
            wxDateTime etd = wxInvalidDateTime;
            wxString s_etd = ( m_MarkDescription.Mid(m_MarkDescription.Find( _T("ETD=") ) + 4 ) ).BeforeFirst( ';' );
            const wxChar *parse_return = etd.ParseDateTime( s_etd );
            if( parse_return ) {
                wxString tz( parse_return );
                
                if( tz.Find( _T("UT") ) != wxNOT_FOUND ) {
                    m_seg_etd = etd;
                }
                else {
                    if( tz.Find( _T("LMT") ) != wxNOT_FOUND ) {
                        m_seg_etd = etd;
                        long lmt_offset = (long) ( ( m_lon * 3600. ) / 15. );
                        wxTimeSpan lmt( 0, 0, (int) lmt_offset, 0 );
                        m_seg_etd -= lmt;
                    } else {
                        m_seg_etd = etd.ToUTC();
                    }
                }
                if( etd.IsValid() && (!GetETA().IsValid() || etd > GetETA()) ) {
                    m_MarkDescription.Replace( s_etd, wxEmptyString);
                    m_seg_etd = etd;
                    return m_seg_etd;
                } else {
                    return GetETA();
                }
            }
        }
    }
    return wxInvalidDateTime;
}
Esempio n. 16
0
icu::TimeZone *get_time_zone(std::string const &time_zone)
{

    if(!time_zone.empty()) {
        return icu::TimeZone::createTimeZone(time_zone.c_str());
    }
    std::auto_ptr<icu::TimeZone> tz(icu::TimeZone::createDefault());
    icu::UnicodeString id;
    tz->getID(id);
    // Check if there is a bug?
    if(id != icu::UnicodeString("localtime"))
        return tz.release();
    // Now let's deal with the bug and run the fixed
    // search loop as that of ICU
    std::string real_id = get_time_zone_name();
    if(real_id.empty()) {
        // if we failed fallback to ICU's time zone
        return tz.release();
    }
    return icu::TimeZone::createTimeZone(real_id.c_str());
}
static jstring TimeZoneNames_getExemplarLocation(JNIEnv* env, jclass, jstring javaLocaleName, jstring javaTz) {
  ScopedIcuLocale icuLocale(env, javaLocaleName);
  if (!icuLocale.valid()) {
    return NULL;
  }

  UErrorCode status = U_ZERO_ERROR;
  UniquePtr<TimeZoneNames> names(TimeZoneNames::createInstance(icuLocale.locale(), status));
  if (maybeThrowIcuException(env, "TimeZoneNames::createInstance", status)) {
    return NULL;
  }

  ScopedJavaUnicodeString tz(env, javaTz);
  if (!tz.valid()) {
    return NULL;
  }

  UnicodeString s;
  const UDate now(Calendar::getNow());
  names->getDisplayName(tz.unicodeString(), UTZNM_EXEMPLAR_LOCATION, now, s);
  return env->NewString(s.getBuffer(), s.length());
}
long inst(long dat,long pp,long b)
{
	long s;
	s=0;
	if (p[b][pp]==0)
	{
		fre++;
		p[b][pp]=fre;
		f[fre]=pp;
		d[fre]=dat;
		ss[fre]=1;
		tz(fre);
		return 0;
	}
	pp=p[b][pp];
	if (dat<d[pp])
	{
		ss[pp]++;
		s+=inst(dat,pp,0);
	}
	else
		s+=(inst(dat,pp,1)+ss[pp]);
	return s;
}
Esempio n. 19
0
/*
 Update the route segment lengths, storing each segment length in <destination> point.
 Also, compute total route length by summing segment distances.
 */
void Route::UpdateSegmentDistances( double planspeed )
{
    wxPoint rpt, rptn;
    float slat1, slon1, slat2, slon2;

    double route_len = 0.0;
    double route_time = 0.0;

    wxRoutePointListNode *node = pRoutePointList->GetFirst();

    if( node ) {
        RoutePoint *prp0 = node->GetData();
        slat1 = prp0->m_lat;
        slon1 = prp0->m_lon;

        node = node->GetNext();

        while( node ) {
            RoutePoint *prp = node->GetData();
            slat2 = prp->m_lat;
            slon2 = prp->m_lon;

//    Calculate the absolute distance from 1->2

            double brg, dd;
            DistanceBearingMercator( slat1, slon1, slat2, slon2, &brg, &dd );

//    And store in Point 2
            prp->m_seg_len = dd;

            route_len += dd;

            slat1 = slat2;
            slon1 = slon2;

//    If Point1 Description contains VMG, store it for Properties Dialog in Point2
//    If Point1 Description contains ETD, store it in Point1

            if( planspeed > 0. ) {
                double vmg = 0.0;
                wxDateTime etd;

                if( prp0->m_MarkDescription.Find( _T("VMG=") ) != wxNOT_FOUND ) {
                    wxString s_vmg = ( prp0->m_MarkDescription.Mid(
                            prp0->m_MarkDescription.Find( _T("VMG=") ) + 4 ) ).BeforeFirst( ';' );
                    if( !s_vmg.ToDouble( &vmg ) ) vmg = planspeed;
                }

                double legspeed = planspeed;
                if( vmg > 0.1 && vmg < 1000. ) legspeed = vmg;
                if( legspeed > 0.1 && legspeed < 1000. ) {
                    route_time += dd / legspeed;
                    prp->m_seg_vmg = legspeed;
                }

                prp0->m_seg_etd = wxInvalidDateTime;
                if( prp0->m_MarkDescription.Find( _T("ETD=") ) != wxNOT_FOUND ) {
                    wxString s_etd = ( prp0->m_MarkDescription.Mid(
                            prp0->m_MarkDescription.Find( _T("ETD=") ) + 4 ) ).BeforeFirst( ';' );
                    const wxChar *parse_return = etd.ParseDateTime( s_etd );
                    if( parse_return ) {
                        wxString tz( parse_return );

                        if( tz.Find( _T("UT") ) != wxNOT_FOUND ) prp0->m_seg_etd = etd;
                        else
                            if( tz.Find( _T("LMT") ) != wxNOT_FOUND ) {
                                prp0->m_seg_etd = etd;
                                long lmt_offset = (long) ( ( prp0->m_lon * 3600. ) / 15. );
                                wxTimeSpan lmt( 0, 0, (int) lmt_offset, 0 );
                                prp0->m_seg_etd -= lmt;
                            } else
                                prp0->m_seg_etd = etd.ToUTC();
                    }
                }
            }

            prp0 = prp;

            node = node->GetNext();
        }
    }

    m_route_length = route_len;
    m_route_time = route_time * 3600.;
}
Esempio n. 20
0
/*
 * Find the location of the zoneinfo files and store in mZoneinfoDir.
 * Parse zone.tab and for each time zone, create a KSystemTimeZone instance.
 */
void KSystemTimeZonesPrivate::readZoneTab(bool update)
{
    kDebug(161) << "readZoneTab(" << m_zonetab<< ")";
    QStringList newZones;
    QFile f;
    f.setFileName(m_zonetab);
    if (!f.open(QIODevice::ReadOnly))
        return;
    QTextStream str(&f);
    QRegExp lineSeparator("[ \t]");
    QRegExp ordinateSeparator("[+-]");
    if (!m_source)
        m_source = new KSystemTimeZoneSource;
    while (!str.atEnd())
    {
        QString line = str.readLine();
        if (line.isEmpty() || line[0] == '#')
            continue;
        QStringList tokens = KStringHandler::perlSplit(lineSeparator, line, 4);
        int n = tokens.count();
        if (n < 3)
        {
            kError(161) << "readZoneTab(): invalid record: " << line << endl;
            continue;
        }

        // Got three tokens. Now check for two ordinates plus first one is "".
        int i = tokens[1].indexOf(ordinateSeparator, 1);
        if (i < 0)
        {
            kError(161) << "readZoneTab() " << tokens[2] << ": invalid coordinates: " << tokens[1] << endl;
            continue;
        }

        float latitude = convertCoordinate(tokens[1].left(i));
        float longitude = convertCoordinate(tokens[1].mid(i));

        // Add entry to list.
        if (tokens[0] == "??")
            tokens[0] = "";
        // Solaris sets the empty Comments field to '-', making it not empty.
        // Clean it up.
        if (n > 3  &&  tokens[3] == "-")
            tokens[3] = "";
        KSystemTimeZone tz(m_source, tokens[2], tokens[0], latitude, longitude, (n > 3 ? tokens[3] : QString()));
        if (update)
        {
            // Update the existing collection with the new zone definition
            newZones += tz.name();
            KTimeZone oldTz = zone(tz.name());
            if (oldTz.isValid())
                oldTz.updateBase(tz);   // the zone previously existed, so update its definition
            else
                add(tz);   // the zone didn't previously exist, so add it
        }
        else
            add(tz);
    }
    f.close();

    if (update)
    {
        // Remove any zones from the collection which no longer exist
        const ZoneMap oldZones = zones();
        for (ZoneMap::ConstIterator it = oldZones.constBegin();  it != oldZones.constEnd();  ++it)
        {
            if (newZones.indexOf(it.key()) < 0)
                remove(it.value());
        }
    }
}
Esempio n. 21
0
 /*ARGSUSED*/ int main (int argc, char **argv)
{
#ifndef USE_PAM
	const char *env;
#endif				/* !USE_PAM */
	char **envp = environ;
	TERMIO termio;
	int err = 0;

#ifdef	USE_TERMIO
	ioctl (0, TCGETA, &termio);
	termio.c_iflag |= (ICRNL | IXON);
	termio.c_oflag |= (OPOST | ONLCR);
	termio.c_cflag |= (CREAD);
	termio.c_lflag |= (ISIG | ICANON | ECHO | ECHOE | ECHOK);
	ioctl (0, TCSETAF, &termio);
#endif
#ifdef	USE_TERMIOS
	tcgetattr (0, &termio);
	termio.c_iflag |= (ICRNL | IXON);
	termio.c_oflag |= (CREAD);
	termio.c_lflag |= (ECHO | ECHOE | ECHOK | ICANON | ISIG);
	tcsetattr (0, TCSANOW, &termio);
#endif

	Prog = Basename (argv[0]);
	(void) setlocale (LC_ALL, "");
	(void) bindtextdomain (PACKAGE, LOCALEDIR);
	(void) textdomain (PACKAGE);

#ifdef	USE_SYSLOG
	OPENLOG ("sulogin");
#endif
	initenv ();
	if (argc > 1) {
		close (0);
		close (1);
		close (2);

		if (open (argv[1], O_RDWR) >= 0) {
			dup (0);
			dup (0);
		} else {
#ifdef	USE_SYSLOG
			SYSLOG (LOG_WARN, "cannot open %s\n", argv[1]);
			closelog ();
#endif
			exit (1);
		}
	}
	if (access (PASSWD_FILE, F_OK) == -1) {	/* must be a password file! */
		(void) puts (_("No password file"));
#ifdef	USE_SYSLOG
		SYSLOG (LOG_WARN, "No password file\n");
		closelog ();
#endif
		exit (1);
	}
#if !defined(DEBUG) && defined(SULOGIN_ONLY_INIT)
	if (getppid () != 1) {	/* parent must be INIT */
#ifdef	USE_SYSLOG
		SYSLOG (LOG_WARN, "Pid == %d, not 1\n", getppid ());
		closelog ();
#endif
		exit (1);
	}
#endif
	if ((isatty (0) == 0) || (isatty (1) == 0) || (isatty (2) == 0)) {
#ifdef	USE_SYSLOG
		closelog ();
#endif
		exit (1);	/* must be a terminal */
	}
	/* If we were init, we need to start a new session */
	if (getppid() == 1) {
		setsid();
		if (ioctl(0, TIOCSCTTY, 1) != 0) {
			(void) fputs (_("TIOCSCTTY failed"), stderr);
		}
	}
	while (NULL != *envp) {		/* add inherited environment, */
		addenv (*envp, NULL);	/* some variables change later */
		envp++;
	}

#ifndef USE_PAM
	env = getdef_str ("ENV_TZ");
	if (NULL != env) {
		addenv (('/' == *env) ? tz (env) : env, NULL);
	}
	env = getdef_str ("ENV_HZ");
	if (NULL != env) {
		addenv (env, NULL);	/* set the default $HZ, if one */
	}
#endif				/* !USE_PAM */

	(void) strcpy (name, "root");	/* KLUDGE!!! */

	(void) signal (SIGALRM, catch_signals);	/* exit if the timer expires */
	(void) alarm (ALARM);		/* only wait so long ... */

	while (true) {		/* repeatedly get login/password pairs */
		char *cp;
		pw_entry (name, &pwent);	/* get entry from password file */
		if (pwent.pw_name == (char *) 0) {
			/*
			 * Fail secure
			 */
			(void) puts (_("No password entry for 'root'"));
#ifdef	USE_SYSLOG
			SYSLOG (LOG_WARN, "No password entry for 'root'\n");
			closelog ();
#endif
			exit (1);
		}

		/*
		 * Here we prompt for the root password, or if no password
		 * is given we just exit.
		 */

		/* get a password for root */
		cp = getpass (_(
"\n"
"Type control-d to proceed with normal startup,\n"
"(or give root password for system maintenance):"));
		/*
		 * XXX - can't enter single user mode if root password is
		 * empty.  I think this doesn't happen very often :-). But
		 * it will work with standard getpass() (no NULL on EOF). 
		 * --marekm
		 */
		if ((NULL == cp) || ('\0' == *cp)) {
#ifdef	USE_SYSLOG
			SYSLOG (LOG_INFO, "Normal startup\n");
			closelog ();
#endif
			(void) puts ("");
#ifdef	TELINIT
			execl (PATH_TELINIT, "telinit", RUNLEVEL, (char *) 0);
#endif
			exit (0);
		} else {
			STRFCPY (pass, cp);
			strzero (cp);
		}
		if (valid (pass, &pwent)) {	/* check encrypted passwords ... */
			break;	/* ... encrypted passwords matched */
		}

#ifdef	USE_SYSLOG
		SYSLOG (LOG_WARN, "Incorrect root password\n");
#endif
		sleep (2);
		(void) puts (_("Login incorrect"));
	}
	strzero (pass);
	(void) alarm (0);
	(void) signal (SIGALRM, SIG_DFL);
	environ = newenvp;	/* make new environment active */

	(void) puts (_("Entering System Maintenance Mode"));
#ifdef	USE_SYSLOG
	SYSLOG (LOG_INFO, "System Maintenance Mode\n");
#endif

#ifdef	USE_SYSLOG
	closelog ();
#endif
	/* exec the shell finally. */
	err = shell (pwent.pw_shell, (char *) 0, environ);

	return ((err == ENOENT) ? E_CMD_NOTFOUND : E_CMD_NOEXEC);
}
Esempio n. 22
0
//-----------------------------------------------------------------------------
HADT MGL_EXPORT mgl_datac_subdata_ext(HCDT d, HCDT xx, HCDT yy, HCDT zz)
{
	if(!xx || !yy || !zz)
	{
		mglData tmp;	tmp.a[0]=-1;
		return mgl_datac_subdata_ext(d,xx?xx:&tmp,yy?yy:&tmp,zz?zz:&tmp);
	}
	
	long n=0,m=0,l=0,j,k;
	bool ix=false, iy=false, iz=false;
	if(xx->GetNz()>1)	// 3d data
	{
		n = xx->GetNx();	m = xx->GetNy();	l = xx->GetNz();
		j = yy->GetNN();	if(j>1 && j!=n*m*l)	return 0;	// wrong sizes
		k = zz->GetNN();	if(k>1 && k!=n*m*l)	return 0;	// wrong sizes
		ix = true;	iy = j>1;	iz = k>1;
	}
	else if(yy->GetNz()>1)
	{
		n = yy->GetNx();	m = yy->GetNy();	l = yy->GetNz();
		j = xx->GetNN();	if(j>1 && j!=n*m*l)	return 0;	// wrong sizes
		k = zz->GetNN();	if(k>1 && k!=n*m*l)	return 0;	// wrong sizes
		iy = true;	ix = j>1;	iz = k>1;
	}
	else if(zz->GetNz()>1)
	{
		n = zz->GetNx();	m = zz->GetNy();	l = zz->GetNz();
		j = yy->GetNN();	if(j>1 && j!=n*m*l)	return 0;	// wrong sizes
		k = xx->GetNN();	if(k>1 && k!=n*m*l)	return 0;	// wrong sizes
		iz = true;	iy = j>1;	ix = k>1;
	}
	else if(xx->GetNy()>1)	// 2d data
	{
		n = xx->GetNx();	m = xx->GetNy();	l = 1;
		j = yy->GetNx()*yy->GetNy();	if(j>1 && j!=n*m)	return 0;	// wrong sizes
		k = zz->GetNx()*zz->GetNy();	if(k>1 && k!=n*m)	return 0;	// wrong sizes
		ix = true;	iy = j>1;	iz = k>1;
	}
	else if(yy->GetNy()>1)
	{
		n = yy->GetNx();	m = yy->GetNy();	l = 1;
		j = xx->GetNx()*xx->GetNy();	if(j>1 && j!=n*m)	return 0;	// wrong sizes
		k = zz->GetNx()*zz->GetNy();	if(k>1 && k!=n*m)	return 0;	// wrong sizes
		iy = true;	ix = j>1;	iz = k>1;
	}
	else if(zz->GetNy()>1)
	{
		n = zz->GetNx();	m = zz->GetNy();	l = 1;
		j = yy->GetNx()*yy->GetNy();	if(j>1 && j!=n*m)	return 0;	// wrong sizes
		k = xx->GetNx()*xx->GetNy();	if(k>1 && k!=n*m)	return 0;	// wrong sizes
		iz = true;	iy = j>1;	ix = k>1;
	}
	long nx=d->GetNx(),ny=d->GetNy(),nz=d->GetNz();
	long vx=long(xx->v(0)), vy=long(yy->v(0)), vz=long(zz->v(0));
	const mglDataC *dd = dynamic_cast<const mglDataC *>(d);
	if(n*m*l>1)	// this is 2d or 3d data
	{
		mglDataV tx(n,m,l),ty(n,m,l),tz(n,m,l);
		if(!ix)	{	xx = &tx;	if(vx>=0)	tx.Fill(vx);	else tx.All();	}
		if(!iy)	{	yy = &ty;	if(vy>=0)	ty.Fill(vy);	else ty.All();	}
		if(!iz)	{	zz = &tz;	if(vz>=0)	tz.Fill(vz);	else tz.All();	}
		mglDataC *r=new mglDataC(n,m,l);
		if(dd)
#pragma omp parallel for
			for(long i0=0;i0<n*m*l;i0++)
			{
				register long x=long(0.5+xx->vthr(i0)), y=long(0.5+yy->vthr(i0)), z=long(0.5+zz->vthr(i0));
				r->a[i0] = (x>=0 && x<nx && y>=0 && y<ny && z>=0 && z<nz)?dd->a[x+nx*(y+ny*z)]:NAN;
			}
		else
#pragma omp parallel for
			for(long i0=0;i0<n*m*l;i0++)
			{
				register long x=long(0.5+xx->vthr(i0)), y=long(0.5+yy->vthr(i0)), z=long(0.5+zz->vthr(i0));
				r->a[i0] = (x>=0 && x<nx && y>=0 && y<ny && z>=0 && z<nz)?d->v(x,y,z):NAN;
			}
		return r;
	}
	// this is 1d data -> try as normal SubData()
	mglDataV tx(nx),ty(ny),tz(nz);	tx.Fill(0,nx-1);	ty.Fill(0,ny-1);	tz.Fill(0,nz-1);
	if(xx->GetNx()>1 || vx>=0)	n=xx->GetNx();	else	{	n=nx;	xx = &tx;	}
	if(yy->GetNx()>1 || vy>=0)	m=yy->GetNx();	else	{	m=ny;	yy = &ty;	}
	if(zz->GetNx()>1 || vz>=0)	l=zz->GetNx();	else	{	l=nz;	zz = &tz;	}
	mglDataC *r=new mglDataC(n,m,l);
	if(dd)
#pragma omp parallel for collapse(3)
		for(long k=0;k<l;k++)	for(long j=0;j<m;j++)	for(long i=0;i<n;i++)
		{
			register long x=long(0.5+xx->v(i)), y=long(0.5+yy->v(j)), z=long(0.5+zz->v(k));
			r->a[i+n*(j+m*k)] = (x>=0 && x<nx && y>=0 && y<ny && z>=0 && z<nz)?dd->a[x+nx*(y+ny*z)]:NAN;
		}
	else
#pragma omp parallel for collapse(3)
		for(long k=0;k<l;k++)	for(long j=0;j<m;j++)	for(long i=0;i<n;i++)
		{
			register long x=long(0.5+xx->v(i)), y=long(0.5+yy->v(j)), z=long(0.5+zz->v(k));
			r->a[i+n*(j+m*k)] = (x>=0 && x<nx && y>=0 && y<ny && z>=0 && z<nz)?d->v(x,y,z):NAN;
		}
	if(m==1)	{	r->ny=r->nz;	r->nz=1;	}// "squeeze" dimensions
	if(n==1)	{	r->nx=r->ny;	r->ny=r->nz;	r->nz=1;	r->NewId();}
	return r;
}
Esempio n. 23
0
// test wxDateTime -> text conversion
void DateTimeTestCase::TestTimeFormat()
{
    // some information may be lost during conversion, so store what kind
    // of info should we recover after a round trip
    enum CompareKind
    {
        CompareNone,        // don't try comparing
        CompareBoth,        // dates and times should be identical
        CompareYear,        // don't compare centuries (fails for 2 digit years)
        CompareDate,        // dates only
        CompareTime         // time only
    };

    static const struct
    {
        CompareKind compareKind;
        const char *format;
    } formatTestFormats[] =
    {
       { CompareYear, "---> %c" }, // %c could use 2 digit years
       { CompareDate, "Date is %A, %d of %B, in year %Y" },
       { CompareYear, "Date is %x, time is %X" }, // %x could use 2 digits
       { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
       { CompareNone, "The day of year: %j, the week of year: %W" },
       { CompareDate, "ISO date without separators: %Y%m%d" },
       { CompareBoth, "RFC 2822 string: %Y-%m-%d %H:%M:%S.%l %z" },

    };

    const long timeZonesOffsets[] =
    {
        wxDateTime::TimeZone(wxDateTime::Local).GetOffset(),

        // Fictitious TimeZone offsets to ensure time zone formating and
        // interpretation works
        -(3600 + 2*60),
        3*3600 + 30*60
    };

    static const Date formatTestDates[] =
    {
        { 29, wxDateTime::May, 1976, 18, 30, 00, 0.0, wxDateTime::Inv_WeekDay },
        { 31, wxDateTime::Dec, 1999, 23, 30, 00, 0.0, wxDateTime::Inv_WeekDay },
        {  6, wxDateTime::Feb, 1937, 23, 30, 00, 0.0, wxDateTime::Inv_WeekDay },
        {  6, wxDateTime::Feb, 1856, 23, 30, 00, 0.0, wxDateTime::Inv_WeekDay },
        {  6, wxDateTime::Feb, 1857, 23, 30, 00, 0.0, wxDateTime::Inv_WeekDay },
        { 29, wxDateTime::May, 2076, 18, 30, 00, 0.0, wxDateTime::Inv_WeekDay },

        // FIXME: the test with 02:15:25 time doesn't pass because of DST
        //        computation problems, we get back 03:15:25
        { 29, wxDateTime::Feb, 2400, 04, 15, 25, 0.0, wxDateTime::Inv_WeekDay },
#if 0
        // Need to add support for BCE dates.
        { 01, wxDateTime::Jan,  -52, 03, 16, 47, 0.0, wxDateTime::Inv_WeekDay },
#endif
    };

    for ( unsigned idxtz = 0; idxtz < WXSIZEOF(timeZonesOffsets); ++idxtz )
    {
        wxDateTime::TimeZone tz(timeZonesOffsets[idxtz]);
        const bool isLocalTz = tz.GetOffset() == -wxGetTimeZone();

        for ( size_t d = 0; d < WXSIZEOF(formatTestDates); d++ )
        {
            wxDateTime dt = formatTestDates[d].DT();
            for ( unsigned n = 0; n < WXSIZEOF(formatTestFormats); n++ )
            {
                const char *fmt = formatTestFormats[n].format;

                // skip the check with %p for those locales which have empty AM/PM strings:
                // for those locales it's impossible to pass the test with %p...
                wxString am, pm;
                wxDateTime::GetAmPmStrings(&am, &pm);
                if (am.empty() && pm.empty() && wxStrstr(fmt, "%p") != NULL)
                    continue;

                // what can we recover?
                CompareKind kind = formatTestFormats[n].compareKind;

                // When using a different time zone we must perform a time zone
                // conversion below which doesn't always work correctly, check
                // for the cases when it doesn't.
                if ( !isLocalTz )
                {
                    // DST computation doesn't work correctly for dates above
                    // 2038 currently on the systems with 32 bit time_t.
                    if ( dt.GetYear() >= 2038 )
                        continue;

                    // We can't compare just dates nor just times when doing TZ
                    // conversion as both are affected by the DST: for the
                    // dates, the DST can switch midnight to 23:00 of the
                    // previous day while for the times DST can be different
                    // for the original date and today.
                    if ( kind == CompareDate || kind == CompareTime )
                        continue;
                }

                // do convert date to string
                wxString s = dt.Format(fmt, tz);

                // convert back
                wxDateTime dt2;
                const char *result = dt2.ParseFormat(s, fmt);
                if ( !result )
                {
                    // conversion failed - should it have?
                    WX_ASSERT_MESSAGE(
                        ("Test #%u failed: failed to parse \"%s\"", n, s),
                        kind == CompareNone
                    );
                }
                else // conversion succeeded
                {
                    // currently ParseFormat() doesn't support "%Z" and so is
                    // incapable of parsing time zone part used at the end of date
                    // representations in many (but not "C") locales, compensate
                    // for it ourselves by simply consuming and ignoring it
                    while ( *result && (*result >= 'A' && *result <= 'Z') )
                        result++;

                    WX_ASSERT_MESSAGE(
                        ("Test #%u failed: \"%s\" was left unparsed in \"%s\"",
                         n, result, s),
                        !*result
                    );

                    // Without "%z" we can't recover the time zone used in the
                    // call to Format() so we need to call MakeFromTimezone()
                    // explicitly.
                    if ( !strstr(fmt, "%z") && !isLocalTz )
                        dt2.MakeFromTimezone(tz);

                    switch ( kind )
                    {
                        case CompareYear:
                            if ( dt2.GetCentury() != dt.GetCentury() )
                            {
                                CPPUNIT_ASSERT_EQUAL(dt.GetYear() % 100,
                                                     dt2.GetYear() % 100);

                                dt2.SetYear(dt.GetYear());
                            }
                            // fall through and compare everything

                        case CompareBoth:
                            CPPUNIT_ASSERT_EQUAL( dt, dt2 );
                            break;

                        case CompareDate:
                            CPPUNIT_ASSERT( dt.IsSameDate(dt2) );
                            break;

                        case CompareTime:
                            CPPUNIT_ASSERT( dt.IsSameTime(dt2) );
                            break;

                        case CompareNone:
                            wxFAIL_MSG( wxT("unexpected") );
                            break;
                    }
                }
            }
        }
    }

    wxDateTime dt;

#if 0
    // special case which was known to fail
    CPPUNIT_ASSERT( dt.ParseFormat("02/06/1856", "%x") );
    CPPUNIT_ASSERT_EQUAL( 1856, dt.GetYear() );
#endif

    // also test %l separately
    CPPUNIT_ASSERT( dt.ParseFormat("12:23:45.678", "%H:%M:%S.%l") );
    CPPUNIT_ASSERT_EQUAL( 678, dt.GetMillisecond() );

    // test special case of %l matching 0 milliseconds
    CPPUNIT_ASSERT( dt.ParseFormat("12:23:45.000", "%H:%M:%S.%l") );
    CPPUNIT_ASSERT_EQUAL( 0, dt.GetMillisecond() );

    // test partially specified dates too
    wxDateTime dtDef(26, wxDateTime::Sep, 2008);
    CPPUNIT_ASSERT( dt.ParseFormat("17", "%d") );
    CPPUNIT_ASSERT_EQUAL( 17, dt.GetDay() );

    // test some degenerate cases
    CPPUNIT_ASSERT( !dt.ParseFormat("", "%z") );
    CPPUNIT_ASSERT( !dt.ParseFormat("", "%%") );

    // test compilation of some calls which should compile (and not result in
    // ambiguity because of char*<->wxCStrData<->wxString conversions)
    wxString s("foo");
    CPPUNIT_ASSERT( !dt.ParseFormat("foo") );
    CPPUNIT_ASSERT( !dt.ParseFormat(wxT("foo")) );
    CPPUNIT_ASSERT( !dt.ParseFormat(s) );
    dt.ParseFormat(s.c_str()); // Simply test compilation of this one.

    CPPUNIT_ASSERT( !dt.ParseFormat("foo", "%c") );
    CPPUNIT_ASSERT( !dt.ParseFormat(wxT("foo"), "%c") );
    CPPUNIT_ASSERT( !dt.ParseFormat(s, "%c") );
    dt.ParseFormat(s.c_str(), "%c");

    CPPUNIT_ASSERT( !dt.ParseFormat("foo", wxT("%c")) );
    CPPUNIT_ASSERT( !dt.ParseFormat(wxT("foo"), wxT("%c")) );
    CPPUNIT_ASSERT( !dt.ParseFormat(s, "%c") );
    dt.ParseFormat(s.c_str(), wxT("%c"));

    wxString spec("%c");
    CPPUNIT_ASSERT( !dt.ParseFormat("foo", spec) );
    CPPUNIT_ASSERT( !dt.ParseFormat(wxT("foo"), spec) );
    CPPUNIT_ASSERT( !dt.ParseFormat(s, spec) );
    dt.ParseFormat(s.c_str(), spec);
}
Esempio n. 24
0
File: VEF.cpp Progetto: Raegon/MARS
// we use a tree architecture to build the subzones
int VEF::divideIntoZones(Zone z, int nbZones){

    TreeZone tz(z);
    TreeZone *father;
    int flag, flag2, depth; // used to determine the cutting axis
    flag = flag2 = depth = 0;
    Vertex bottom, middle_bottom, middle_top, top;
    bottom = middle_bottom = z.getZoneBottomVertex();
    top = middle_top = z.getZoneTopVertex();
    int id = 0;
    int rootFlag = 0;

    std::vector<TreeZone> parents; // store the parent trees relative to the one we manipulate

    for (int i = 0; i < nbZones; i++){
        if (!(i % 2)){
            if (flag % 3 == 0) // we cut along the x axis
            {
                Vertex vx(middle_top.getX() - (middle_top.getX() / 2), middle_top.getY(), middle_top.getZ());
                Zone zl(bottom, vx, -1);
                TreeZone *l = new TreeZone(zl);

                tz.addLeftChild(l);
                //top.setX(vx.getX());
                middle_top = vx;
            }

            if (flag % 3 == 1) // we cut along the y axis
            {
                Vertex vy(middle_top.getX(), middle_top.getY() - middle_top.getY() / 2, middle_top.getZ());
                Zone zl(bottom, vy, -1);
                TreeZone *l = new TreeZone(zl);

                tz.addLeftChild(l);
                //top.setY(vy.getY());
                middle_top = vy;
            }

            if (flag % 3 == 2) // we cut along the z axis
            {
                Vertex vz(middle_top.getX(), middle_top.getY(), middle_top.getZ() - middle_top.getZ() / 2);
                Zone zl(bottom, vz, -1);
                TreeZone *l = new TreeZone(zl);

                tz.addLeftChild(l);
                //top.setZ(vz.getZ());
                middle_top = vz;
            }
        }
        else
        {
            if (flag2 % 3 == 0) // we cut along the x axis
            {
                Vertex vx(middle_bottom.getX() + (middle_bottom.getX() / 2), middle_bottom.getY(), middle_bottom.getZ());
                Zone zr(vx, top, -1);
                TreeZone *r = new TreeZone(zr);

                tz.addRightChild(r);
                middle_bottom = vx;
            }

            if (flag2 % 3 == 1) // we cut along the y axis
            {
                Vertex vy(middle_bottom.getX(), middle_bottom.getY() + (middle_bottom.getY() / 2), middle_bottom.getZ());
                Zone zr(vy, top, -1);
                TreeZone *r = new TreeZone(zr);

                tz.addRightChild(r);
                middle_bottom = vy;
            }

            if (flag2 % 3 == 2) // we cut along the z axis
            {
                Vertex vz(middle_bottom.getX(), middle_bottom.getY(), middle_bottom.getZ() + (middle_bottom.getZ() / 2));
                Zone zr(vz, top, -1);
                TreeZone *r = new TreeZone(zr);

                tz.addRightChild(r);
            }

            if (depth){
                if (!(*(father->getRightChild()) == tz))
                {
                    if (father->getRightChild()->getLeftChild() == NULL)
                    { // the brother of t doesn't exist yet
                        tz = *(father->getRightChild());
                        father = &(parents.back());
                        parents.pop_back();
                    }
                }
            }

            parents.push_back(*father);
            father = &tz;
            tz = *(tz.getLeftChild());
            depth++;

        }
    }

    // depth-first search to add the zones we created (the leaves) into the zone vector
    while (tz.hasLeftChild()){
        father = &tz;
        tz = *(tz.getLeftChild());
    }

    tz.getRoot().setZoneId(id);
    m_zones.push_back(tz.getRoot());
    id++;

    // we stop when we reach the root for the second time, i.e, when all the leaves have been found
    /*while(rootFlag != 1){
        if (father->hasRightChild()){
            father->getRightChild()->getRoot().setZoneId(id);
            m_zones.push_back(father->getRightChild()->getRoot());
        }

        tz = father;
        if (depth){
            father = parents.back();
            parents.pop_back();
        }
        depth--;
    }*/


    return 0;
}
Esempio n. 25
0
//---------------------------------------------------------
void NDG3D::PoissonIPDG3D(CSd& spOP, CSd& spMM)
//---------------------------------------------------------
{
  // function [OP,MM] = PoissonIPDG3D()
  //
  // Purpose: Set up the discrete Poisson matrix directly
  //          using LDG. The operator is set up in the weak form


  DVec faceR("faceR"), faceS("faceS"), faceT("faceT");
  DMat V2D;  IVec Fm("Fm");  IVec i1_Nfp = Range(1,Nfp);
  double opti1=0.0, opti2=0.0; int i=0; 

  umLOG(1, "\n ==> {OP,MM} assembly: ");
  opti1 = timer.read(); // time assembly

  // build local face matrices
  DMat massEdge[5]; // = zeros(Np,Np,Nfaces);
  for (i=1; i<=Nfaces; ++i) {
    massEdge[i].resize(Np,Np);
  }

  // face mass matrix 1
  Fm = Fmask(All,1); faceR=r(Fm); faceS=s(Fm); 
  V2D = Vandermonde2D(N, faceR, faceS);
  massEdge[1](Fm,Fm) = inv(V2D*trans(V2D));

  // face mass matrix 2
  Fm = Fmask(All,2); faceR = r(Fm); faceT = t(Fm);
  V2D = Vandermonde2D(N, faceR, faceT);
  massEdge[2](Fm,Fm) = inv(V2D*trans(V2D));

  // face mass matrix 3
  Fm = Fmask(All,3); faceS = s(Fm); faceT = t(Fm);
  V2D = Vandermonde2D(N, faceS, faceT); 
  massEdge[3](Fm,Fm) = inv(V2D*trans(V2D));

  // face mass matrix 4
  Fm = Fmask(All,4); faceS = s(Fm); faceT = t(Fm);
  V2D = Vandermonde2D(N, faceS, faceT); 
  massEdge[4](Fm,Fm) = inv(V2D*trans(V2D));

  // build local volume mass matrix
  MassMatrix = trans(invV)*invV;

  DMat Dx("Dx"),Dy("Dy"),Dz("Dz"), Dx2("Dx2"),Dy2("Dy2"),Dz2("Dz2");
  DMat Dn1("Dn1"),Dn2("Dn2"), mmE("mmE"), OP11("OP11"), OP12("OP12");
  DMat mmE_All_Fm1, mmE_Fm1_Fm1, Dn2_Fm2_All;
  IMat rows1,cols1,rows2,cols2;  int k1=0,f1=0,k2=0,f2=0,id=0;
  Index1D entries, entriesMM, idsM;  IVec fidM,vidM,Fm1,vidP,Fm2;
  double lnx=0.0,lny=0.0,lnz=0.0,lsJ=0.0,hinv=0.0,gtau=0.0;
  double N1N1 = double((N+1)*(N+1)); int NpNp = Np*Np;

  // build DG derivative matrices
  int max_OP = (K*Np*Np*(1+Nfaces));
  int max_MM = (K*Np*Np);

  // "OP" triplets (i,j,x), extracted to {Ai,Aj,Ax}
  IVec OPi(max_OP), OPj(max_OP), Ai,Aj; DVec OPx(max_OP), Ax;
  // "MM" triplets (i,j,x)
  IVec MMi(max_MM), MMj(max_MM); DVec MMx(max_MM);
  IVec OnesNp = Ones(Np);

  // global node numbering
  entries.reset(1,NpNp); entriesMM.reset(1,NpNp);

  OP12.resize(Np,Np);

  for (k1=1; k1<=K; ++k1)
  {
    if (! (k1%250)) { umLOG(1, "%d, ",k1); }

    rows1 = outer( Range((k1-1)*Np+1,k1*Np), OnesNp );
    cols1 = trans(rows1);

    // Build local operators  
    Dx = rx(1,k1)*Dr + sx(1,k1)*Ds + tx(1,k1)*Dt;   
    Dy = ry(1,k1)*Dr + sy(1,k1)*Ds + ty(1,k1)*Dt;
    Dz = rz(1,k1)*Dr + sz(1,k1)*Ds + tz(1,k1)*Dt;

    OP11 = J(1,k1)*(trans(Dx)*MassMatrix*Dx + 
                    trans(Dy)*MassMatrix*Dy + 
                    trans(Dz)*MassMatrix*Dz);

    // Build element-to-element parts of operator
    for (f1=1; f1<=Nfaces; ++f1) {
      k2 = EToE(k1,f1); f2 = EToF(k1,f1); 

      rows2 = outer( Range((k2-1)*Np+1, k2*Np), OnesNp );
      cols2 = trans(rows2);

      fidM  = (k1-1)*Nfp*Nfaces + (f1-1)*Nfp + i1_Nfp;
      vidM = vmapM(fidM); Fm1 = mod(vidM-1,Np)+1;
      vidP = vmapP(fidM); Fm2 = mod(vidP-1,Np)+1;

      id = 1+(f1-1)*Nfp + (k1-1)*Nfp*Nfaces;
      lnx = nx(id);  lny = ny(id);  lnz = nz(id); lsJ = sJ(id); 
      hinv = std::max(Fscale(id), Fscale(1+(f2-1)*Nfp, k2));    

      Dx2 = rx(1,k2)*Dr + sx(1,k2)*Ds + tx(1,k2)*Dt;   
      Dy2 = ry(1,k2)*Dr + sy(1,k2)*Ds + ty(1,k2)*Dt;
      Dz2 = rz(1,k2)*Dr + sz(1,k2)*Ds + tz(1,k2)*Dt;
      
      Dn1 = lnx*Dx  + lny*Dy  + lnz*Dz;
      Dn2 = lnx*Dx2 + lny*Dy2 + lnz*Dz2;

      mmE = lsJ*massEdge[f1];

      gtau = 2.0 * N1N1 * hinv; // set penalty scaling

      if (EToE(k1,f1)==k1) {
        OP11 += ( gtau*mmE - mmE*Dn1 - trans(Dn1)*mmE ); // ok
      }
      else 
      {
        // interior face variational terms
        OP11 += 0.5*( gtau*mmE - mmE*Dn1 - trans(Dn1)*mmE );

        // extract mapped regions:
        mmE_All_Fm1 = mmE(All,Fm1);
        mmE_Fm1_Fm1 = mmE(Fm1,Fm1);
        Dn2_Fm2_All = Dn2(Fm2,All);

        OP12 = 0.0;   // reset to zero
        OP12(All,Fm2)  = -0.5*(       gtau*mmE_All_Fm1 );
        OP12(Fm1,All) -=  0.5*(            mmE_Fm1_Fm1*Dn2_Fm2_All );
      //OP12(All,Fm2) -=  0.5*(-trans(Dn1)*mmE_All_Fm1 );
        OP12(All,Fm2) +=  0.5*( trans(Dn1)*mmE_All_Fm1 );

        // load this set of triplets
#if (1)
        OPi(entries)=rows1; OPj(entries)=cols2, OPx(entries)=OP12;
        entries += (NpNp);
#else
        //###########################################################
        // load only the lower triangle (after droptol test?)
        sk=0; start=entries(1);
        for (int i=1; i<=NpNp; ++i) {
          eid = start+i;
          id=entries(eid); rid=rows1(i); cid=cols2(i);
          if (rows1(rid) >= cid) {          // take lower triangle
            if ( fabs(OP12(id)) > 1e-15) {  // drop small entries
              ++sk; OPi(id)=rid; OPj(id)=cid, OPx(id)=OP12(id);
            }
          }
        }
        entries += sk;
        //###########################################################
#endif
      }
    }

    OPi(entries  )=rows1; OPj(entries  )=cols1, OPx(entries  )=OP11;
    MMi(entriesMM)=rows1; MMj(entriesMM)=cols1; MMx(entriesMM)=J(1,k1)*MassMatrix;
    entries += (NpNp); entriesMM += (NpNp);
  }
  umLOG(1, "\n ==> {OP,MM} to sparse\n");

  entries.reset(1, entries.hi()-Np*Np);

  // Extract triplets from the large buffers. Note: this 
  // requires copying each array, and since these arrays 
  // can be HUGE(!), we force immediate deallocation:

  Ai=OPi(entries);  OPi.Free();
  Aj=OPj(entries);  OPj.Free();
  Ax=OPx(entries);  OPx.Free();
  umLOG(1, " ==> triplets ready (OP) nnz = %10d\n", entries.hi());

  // adjust triplet indices for 0-based sparse operators
  Ai -= 1; Aj -= 1; MMi -= 1; MMj -= 1;  int npk=Np*K;

#if defined(NDG_USE_CHOLMOD) || defined(NDG_New_CHOLINC)
  // load only the lower triangle tril(OP)        free args?
  spOP.load(npk,npk, Ai,Aj,Ax, sp_LT, false,1e-15, true);  // {LT, false} -> TriL
#else
  // select {upper,lower,both} triangles
//spOP.load(npk,npk, Ai,Aj,Ax, sp_LT, true,1e-15,true);   // LT -> enforce symmetry
//spOP.load(npk,npk, Ai,Aj,Ax, sp_All,true,1e-15,true);   // All-> includes "noise"
//spOP.load(npk,npk, Ai,Aj,Ax, sp_UT, false,1e-15,true);  // UT -> triu(OP) only
#endif

  Ai.Free();  Aj.Free();  Ax.Free();

  umLOG(1, " ==> triplets ready (MM) nnz = %10d\n", entriesMM.hi());

  //-------------------------------------------------------
  // The mass matrix operator will NOT be factorised, 
  // Load ALL elements (both upper and lower triangles):
  //-------------------------------------------------------
  spMM.load(npk,npk, MMi,MMj,MMx, sp_All,false,1.00e-15,true);
  MMi.Free(); MMj.Free(); MMx.Free();

  opti2 = timer.read(); // time assembly
  umLOG(1, " ==> {OP,MM} converted to csc.  (%g secs)\n", opti2-opti1);
}