コード例 #1
0
int main()
{
    while(scanf("%d", &n) != EOF)
    {

        init();
        if(n>=20)
        {
            cur = n;
            //get 2  -> n+3
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(n+1, n+2, '+');
            //get 3  -> n+8
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(9, 10, '/');
            cal(n+4, n+5, '+');
            cal(n+7, n+6, '+');
            //get 4  -> n+15
            cal(11, 12, '/');
            cal(13, 14, '/');
            cal(15, 16, '/');
            cal(17, 18, '/');
            cal(n+9, n+10, '+');
            cal(n+13, n+11, '+');
            cal(n+14, n+12, '+');
            //get 2*3*4  -> let it last
            //get 0  -> n+16
            cal(19, 20, '-');
            //printf ( "get 0 : %d, cur: %d\n", n+16, cur );
            for(int i=21; i<=n; i++)
            {
                cal(i, cur, '*');
                //printf ( "i: %d , cur: %d\n", i, cur );
            }
            cal(cur, n+3, '+');
            cal(cur, n+8, '*');
            cal(cur, n+15, '*');
            //printf ( "cur: %d\n", cur );
        }
        else if(n<=3)
        {
            printf ( "-1\n" );
        }
        else if(n == 4)
        {
            cal(1, 2, '*');
            cal(5, 3, '+');
            cal(6, 4, '+');
        }
        else if(n == 5)
        {
            cal(1, 2, '*');
            cal(3, 6, '*');
            cal(7, 4, '-');
            cal(8, 5, '/');
        }
        else if(n == 6)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 7, '-');
            cal(9, 8, '-');
            cal(10, 6, '*');
        }
        else if(n == 7)
        {
            //pass, Æäʵ¿ÉÒÔ
            cal(1, 2, '+');
            cal(3, 8, '+');
            cal(9, 4, '/');
            cal(5, 10, '+');
            cal(6, 11, '+');
            cal(7, 12, '+');
        }
        else if(n == 8)
        {
            cal(1, 2, '-');
            cal(3, 9, '*');
            cal(4, 10, '*');
            cal(5, 11, '*');
            cal(6, 7, '+');
            cal(8, 13, '+');
            cal(14, 12, '+');
        }
        else if(n == 9)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(10, 11, '+');
            cal(14, 12, '+');
            cal(9, 13, '-');
            cal(15, 16, '*');
        }
        else if(n == 10)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(11, 12, '+');
            cal(13, 15, '+');
            cal(14, 16, '+');
            cal(9, 17, '+');
            cal(10, 18, '+');
        }
        else if(n == 11)
        {
            //maybe problem
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '-');
            cal(9, 15, '*');
            cal(10, 16, '*');
            cal(12, 13, '+');
            cal(14, 11, '+');
            cal(18, 19, '*');
            cal(20, 17, '+');
        }
        else if(n == 12)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '-');
            cal(13, 14, '+');
            cal(7, 16, '*');
            cal(8, 15, '*');
            cal(9, 18, '*');
            cal(10, 19, '*');
            cal(11, 20, '*');
            cal(12, 21, '*');
            cal(22, 17, '+');
        }
        else if(n == 13)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '-');
            cal(9, 14, '-');
            cal(15, 16, '+');
            cal(18, 19, '*');
            cal(10, 17, '*');
            cal(11, 21, '*');
            cal(12, 22, '*');
            cal(13, 23, '*');
            cal(24, 20, '+');
        }
        else if(n == 14)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(9, 10, '-');
            cal(11, 15, '-');
            cal(20, 16, '-');
            cal(17, 18, '+');
            cal(21, 22, '*');
            cal(12, 19, '*');
            cal(13, 24, '*');
            cal(14, 25, '*');
            cal(26, 23, '+');
        }
        else if(n == 15)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(9, 10, '/');
            cal(11, 12, '-');
            cal(16, 17, '+');
            cal(18, 22, '+');
            cal(13, 23, '-');
            cal(19, 20, '+');
            cal(24, 25, '*');
            cal(14, 21, '*');
            cal(15, 27, '*');
            cal(26, 28, '+');
        }
        else if(n == 16)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(9, 10, '/');
            cal(11, 12, '/');
            cal(13, 14, '-');
            cal(17, 18, '+');
            cal(19, 20, '+');
            cal(24, 25, '+');
            cal(15, 26, '-');
            cal(21, 22, '+');
            cal(16, 23, '*');
            cal(28, 29, '+');
            cal(27, 30, '*');
        }
        else if(n == 17)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(9, 10, '/');
            cal(11, 12, '/');
            cal(13, 14, '/');
            cal(15, 16, '-');
            cal(18, 19, '+');
            cal(20, 26, '+');
            cal(21, 27, '+');
            cal(22, 28, '+');
            cal(17, 29, '-');
            cal(23, 24, '+');
            cal(25, 31, '+');
            cal(30, 32, '*');
        }
        else if(n == 18)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(9, 10, '/');
            cal(11, 12, '/');
            cal(13, 14, '/');
            cal(15, 16, '/');
            cal(17, 18, '/');
            cal(19, 20, '+');
            cal(21, 22, '+');
            cal(23, 29, '+');
            cal(24, 25, '+');
            cal(26, 27, '+');
            cal(31, 32, '+');
            cal(28, 30, '*');
            cal(33, 34, '*');
        }
        else if(n == 19)
        {
            cal(1, 2, '/');
            cal(3, 4, '/');
            cal(5, 6, '/');
            cal(7, 8, '/');
            cal(9, 10, '/');
            cal(11, 12, '-');
            cal(20, 21, '+');
            cal(22, 26, '+');
            cal(23, 27, '+');
            cal(24, 28, '+');
            cal(13, 29, '+');
            cal(14, 25, '*');
            cal(15, 31, '*');
            cal(16, 32, '*');
            cal(17, 33, '*');
            cal(18, 34, '*');
            cal(19, 35, '*');
            cal(30, 36, '+');
        }
    }
}
コード例 #2
0
ファイル: vm2tac.c プロジェクト: tctsigemura/C--
// まず、スタックから整数を二つ取り出し差を計算する
// 次に、計算結果をスタックに積む
void vmSub() {
  cal("SUB");                                   // 左右逆順なしのコード生成
}
コード例 #3
0
ファイル: vm2tac.c プロジェクト: tctsigemura/C--
// まず、スタックからシフトするビット数、シフトされるデータの順で取り出す。
// 次に、右シフトした結果をスタックに積む
void vmShr() {
  cal("SHRA");                                  // 左右逆順なしのコード生成
}
コード例 #4
0
ファイル: erarulestest.cpp プロジェクト: winlibs/icu4c
void EraRulesTest::testAPIs() {
    const char * calTypes[] = {
        "gregorian",
        //"iso8601",
        "buddhist",
        "chinese",
        "coptic",
        "dangi",
        "ethiopic",
        "ethiopic-amete-alem",
        "hebrew",
        "indian",
        "islamic",
        "islamic-civil",
        "islamic-rgsa",
        "islamic-tbla",
        "islamic-umalqura",
        "japanese",
        "persian",
        "roc",
        //"unknown",
        NULL
    };

    for (int32_t i = 0; calTypes[i] != NULL; i++) {
        UErrorCode status = U_ZERO_ERROR;
        const char *calId = calTypes[i];

        LocalPointer<EraRules> rules1(EraRules::createInstance(calId, FALSE, status));
        if (U_FAILURE(status)) {
            errln(UnicodeString("Era rules for ") + calId + " is not available.");
            continue;
        }

        LocalPointer<EraRules> rules2(EraRules::createInstance(calId, TRUE, status));
        if (U_FAILURE(status)) {
            errln(UnicodeString("Era rules for ") + calId + " (including tentative eras) is not available.");
            continue;
        }

        int32_t numEras1 = rules1->getNumberOfEras();
        if (numEras1 <= 0) {
            errln(UnicodeString("Number of era rules for ") + calId + " is " + numEras1);
        }

        int32_t numEras2 = rules2->getNumberOfEras();
        if (numEras2 < numEras1) {
            errln(UnicodeString("Number of era including tentative eras is fewer than one without tentative eras in calendar: ")
                    + calId);
        }

        LocalPointer<Calendar> cal(Calendar::createInstance("en", status));
        if (U_FAILURE(status)) {
            errln("Failed to create a Calendar instance.");
            continue;
        }
        int32_t currentIdx = rules1->getCurrentEraIndex();
        int32_t currentYear = cal->get(UCAL_YEAR, status);
        int32_t idx = rules1->getEraIndex(
                currentYear, cal->get(UCAL_MONTH, status) + 1,
                cal->get(UCAL_DATE, status), status);
        if (U_FAILURE(status)) {
            errln("Error while getting index of era.");
            continue;
        }
        if (idx != currentIdx) {
            errln(UnicodeString("Current era index:") + currentIdx + " is different from era index of now:" + idx
                    + " in calendar:" + calId);
        }

        int32_t eraStartYear = rules1->getStartYear(currentIdx, status);
        if (U_FAILURE(status)) {
            errln(UnicodeString("Failed to get the start year of era index: ") + currentIdx + " in calendar: " + calId);
        }
        if (currentYear < eraStartYear) {
            errln(UnicodeString("Current era's start year is after the current year in calendar:") + calId);
        }
    }
}
コード例 #5
0
int main()
{
  int i , x , a , bb , m;
  int ori[100003];
  char ss[100003];
  // box b[10000];
  scanf("%d %d" , &n , &m);
  scanf("%s" , ss);
  ori[0] = ss[0] -'0';
  arr[0] = ( ss[0] -'0' ) % 3;
  i = sqrt(n)+  3;
  while(i--)
  {
    b[i].rem[0] = 0;
    b[i].rem[1] = 0;
    b[i].rem[2] = 0;
    b[i].a = 0;
  }
  b[0].rem[arr[0]]++;
  s = sqrt(n);
  int p , q;
  p = 1;
  q = 0;
  for( i = 1 ; i < n ; i++ )
  {
    ori[i] = ss[i] -'0';
    arr[i] = ( arr[i-1] + ss[i] - '0' ) % 3;
    ++b[q].rem[ arr[i] ];
    p++;
    if( p == s )
    {
      p = 0;
      q++;
    }
  }
  tbox = q + 1;
  while( m-- )
  {
    scanf("%d %d %d" , &x , &a , &bb);
    a--;
    if( x == 2 )
    {
      bb--;
      ans[0] = 0;
      ans[1] = 0;
      ans[2] = 0;
      if( a != 0 )
        query( a-1 , bb);
      else
      {
        query(a , bb );
        ans[0]++;
      }
      long long int ans1 = 0;
      for( i = 0 ; i < 3 ; i++)
        ans1 +=  cal( ans[i] );
      printf("%lld\n" , ans1 );
    }
    else
    {
      update( a , ( bb - ori[a] )%3 );
      ori[a] = bb;
    }
  }
  return 0;
}
コード例 #6
0
void
avtWellBorePlot::SetColors()
{
    if (atts.GetColorType() == WellBoreAttributes::ColorBySingleColor)
    {
        const ColorAttribute ca = atts.GetSingleColor();
        ColorAttributeList cal;
        cal.AddColors(atts.GetSingleColor());
        avtLUT->SetLUTColorsWithOpacity(ca.GetColor(), 1);
        levelsMapper->SetColors(cal);
    }
    else if (atts.GetColorType() == WellBoreAttributes::ColorByMultipleColors)
    {
        const ColorAttributeList &cal = atts.GetMultiColor();
        unsigned char *colors = new unsigned char[atts.GetNWellBores() * 4];
        unsigned char *cptr = colors;
        for(int i = 0; i < atts.GetNWellBores(); i++)
        {
            *cptr++ = (char)cal[i].Red();
            *cptr++ = (char)cal[i].Green();
            *cptr++ = (char)cal[i].Blue();
            *cptr++ = (char)cal[i].Alpha();
        }

        avtLUT->SetLUTColorsWithOpacity(colors, atts.GetNWellBores());
        levelsMapper->SetColors(cal);

        delete [] colors;
    }
    else // ColorByColorTable
    {
        ColorAttributeList cal(atts.GetMultiColor());
        unsigned char *colors = new unsigned char[atts.GetNWellBores() * 4];
        unsigned char *cptr = colors;
        avtColorTables *ct = avtColorTables::Instance();
        const int opacity = 255;

        //
        // Detect if we're using the default color table or a color table
        // that does not exist anymore.
        //
        std::string ctName(atts.GetColorTableName());
        if(ctName == "Default")
            ctName = std::string(ct->GetDefaultDiscreteColorTable());
        else if(!ct->ColorTableExists(ctName.c_str()))
        {
            delete [] colors;
            EXCEPTION1(InvalidColortableException, ctName);
        }

        bool invert = atts.GetInvertColorTable();

        //
        // Add a color for each subset name.
        //
        if(ct->IsDiscrete(ctName.c_str()))
        {
            // The CT is discrete, get its color color control points.
            for(int i = 0; i < atts.GetNWellBores(); ++i)
            {
                unsigned char rgb[3] = {0,0,0};
                ct->GetControlPointColor(ctName.c_str(), i, rgb, invert);
                *cptr++ = rgb[0];
                *cptr++ = rgb[1];
                *cptr++ = rgb[2];
                *cptr++ = opacity;

                cal[i].SetRgba(rgb[0], rgb[1], rgb[2], opacity);
            }
        }
        else
        {
            // The CT is continuous, sample the CT so we have a unique color
            // for each element.
            unsigned char *rgb = ct->GetSampledColors(ctName.c_str(),
                                                      atts.GetNWellBores(),
                                                      invert);
            if(rgb)
            {
                for(int i = 0; i < atts.GetNWellBores(); ++i)
                {
                     int j = i * 3;
                     *cptr++ = rgb[j];
                     *cptr++ = rgb[j+1];
                     *cptr++ = rgb[j+2];
                     *cptr++ = opacity;

                     cal[i].SetRgba(rgb[j], rgb[j+1], rgb[j+2], opacity);
                }
                delete [] rgb;
            }
        }

        avtLUT->SetLUTColorsWithOpacity(colors, atts.GetNWellBores());
        levelsMapper->SetColors(cal);

        delete [] colors;
    }
}
コード例 #7
0
bool
ICalReport::generate()
{
#if KDE_IS_VERSION(3,4,89)
    KCal::CalendarLocal cal("UTC");
#else
    KCal::CalendarLocal cal;
#endif

    if( !open())
    {
        tjWarning(i18n("Can not open ICal File '%1' for writing!")
                 .arg(fileName));
        return false;
    }

    TaskList filteredList;
    if (!filterTaskList(filteredList, 0, getHideTask(), getRollUpTask()))
        return false;

    // Make sure that parents are in front of childs. We need this later to set
    // the relation.
    filteredList.setSorting(CoreAttributesList::TreeMode, 0);
    filteredList.setSorting(CoreAttributesList::StartUp, 1);
    sortTaskList(filteredList);

    ResourceList filteredResourceList;
    if (!filterResourceList(filteredResourceList, 0, hideResource,
                            rollUpResource))
        return false;
    sortResourceList(filteredResourceList);

    QPtrDict<KCal::Todo> toDoDict;
    QPtrDict<KCal::Event> eventDict;
    for (TaskListIterator tli(filteredList); *tli != 0; ++tli)
    {
        // Generate a TODO item for each task.
        KCal::Todo* todo = generateTODO(*tli, filteredResourceList);

        // In case we have the parent in the list set the relation pointer.
        if((*tli)->getParent() && toDoDict.find((*tli)->getParent()))
            todo->setRelatedTo(toDoDict[(*tli)->getParent()]);

        // Insert the just created TODO into the calendar.
        cal.addTodo(todo);

        // Insert the TODO into the dict. We might need it as a parent.
        toDoDict.insert(*tli, todo);

        if ((*tli)->isLeaf() && !(*tli)->isMilestone())
        {
            // Generate an event item for each task.
            KCal::Event* event = generateEvent(*tli, filteredResourceList);

            // In case we have the parent in the list set the relation pointer.
            if((*tli)->getParent() && eventDict.find((*tli)->getParent()))
                event->setRelatedTo(eventDict[(*tli)->getParent()]);

            // Insert the just created EVENT into the calendar.
            cal.addEvent(event);

            // Insert the EVENT into the dict. We might need it as a parent.
            eventDict.insert(*tli, event);
        }
    }

    // Dump the calendar in ICal format into a text file.
    KCal::ICalFormat format;
    s << format.toString(&cal) << endl;

    return close();
}
コード例 #8
0
int main(){
	printf("%d",cal(10, 5));
	return 0;
}
コード例 #9
0
ファイル: SinmapSI.cpp プロジェクト: CI-WATER/TauDEM-LFS-Test
int sindexcombined(char *slopefile,  char *scaterrainfile, char *scarminroadfile, char* scarmaxroadfile,
           char *tergridfile, char *terparfile, char *satfile, char* sincombinedfile, double Rminter, double Rmaxter, 
		   double *par)
{	
	MPI_Init(NULL,NULL);{
	FILE *fp;
	int i, j, mter, err, filetype, index, rno, nx, ny;
	float ndva, ndvs;
	short *ndvter;
	int nor;
	double X1, X2, cellsat, dx, dy;
	float rs, rw, g;
	float tmin, tmax, cmin, cmax, tphimin, tphimax;
  
	const double PI = 3.14159265358979;

	struct calreg{
		float tmin;
		float tmax;
		float cmin;
		float cmax;
		float tphimin;
		float tphimax;
		float r;
	} ;  /* this could be malloced or should be checked
                    to ensure fewer than 100 regions */
	g=par[0];
	rw=par[1];
	nor = 0;
	
	struct calreg *region;	

	char headers[MAXLN];

	// find number of regions
	fp = fopen(terparfile, "r");
	if (fp == NULL)return 15;

	// Pabitra (9/10/2015): the following code to count the number of lines 
	// handles if the last line does not end with end of line character
	while ( fgets ( headers, sizeof headers, fp) != NULL)
	{
		nor++;
	}
	/*while (readline(fp,headers) != EOF)
	{
		nor++;
	}*/
	(std::fclose)(fp);

	// number of regions is  total lines in the file minus 1 (for the header text line)
	nor = nor - 1;
		
	region = (calreg*)calloc(nor, sizeof(calreg));
	getRegionIndex(terparfile, nor);

	fp = fopen(terparfile, "r");	
	readline(fp,headers);
	//  i = -1;  DGT 12/31/14 Not needed
	index = 0;
	do
	{
		j = fscanf(fp,"%i,%f,%f,%f,%f,%f,%f,%f \n", &rno, &tmin,
					&tmax, &cmin, &cmax,  &tphimin, &tphimax, &rs);
		
		region[index].tmin = tmin;
		region[index].tmax = tmax;
		region[index].cmin  = cmin;
		region[index].cmax  = cmax;
		region[index].tphimin =tphimin * PI/180 ;
		region[index].tphimax = tphimax * PI/180;
		region[index].r = rw/rs;
		index++;
	}while (index < nor);

	(std::fclose)(fp);

	//MPI_Init(NULL,NULL);{

	int rank, size;
	MPI_Comm_rank(MCW, &rank);
	MPI_Comm_size(MCW, &size);
	if(rank == 0) printf("SinmapSI version %s\n", TDVERSION);

	double begin,end;
	//Begin timer
	begin = MPI_Wtime();

	//Create tiff object, read and store header info
	tiffIO slp(slopefile, FLOAT_TYPE);
	long totalX = slp.getTotalX();
	long totalY = slp.getTotalY();
	dx = slp.getdxA();
	dy = slp.getdyA();	
	
	tiffIO sca(scaterrainfile, FLOAT_TYPE);

	tiffIO *sca_min = NULL;
	if (*scarminroadfile != NULL)
	{
		sca_min = new tiffIO(scarminroadfile, FLOAT_TYPE);		
	}
	
	tiffIO *sca_max = NULL;
	if (*scarmaxroadfile != NULL)
	{
		sca_max = new tiffIO(scarmaxroadfile, FLOAT_TYPE);		
	}
		
	tiffIO cal(tergridfile, SHORT_TYPE);

	if(rank==0)
	{
		float timeestimate=(1e-7*totalX*totalY/pow((double) size,1))/60+1;  // Time estimate in minutes
		fprintf(stderr,"This run may take on the order of %.0f minutes to complete.\n",timeestimate);
		fprintf(stderr,"This estimate is very approximate. \nRun time is highly uncertain as it depends on the complexity of the input data \nand speed and memory of the computer. This estimate is based on our testing on \na dual quad core Dell Xeon E5405 2.0GHz PC with 16GB RAM.\n");
		fflush(stderr);
	}

	
	//Create partition and read data from slope file
	tdpartition *slpData;
	slpData = CreateNewPartition(slp.getDatatype(), totalX, totalY, dx, dy, slp.getNodata());
	nx = slpData->getnx();
	ny = slpData->getny();
	ndvs = *(float*)slp.getNodata();	
	int xstart, ystart;
	slpData->localToGlobal(0, 0, xstart, ystart);
	// TODO: put similar comments for the other savedxdyc() function used in this function
	// for a complete slpData partition would need to run slpData->savedxdyc(slp) to save lat variable cell sizes
	// here not done as cell size not needed
	//slpData->savedxdyc(slp);

	slp.read(xstart, ystart, ny, nx, slpData->getGridPointer());

	//Create partition and read data from clibration grid file
	tdpartition *calData;
	calData = CreateNewPartition(cal.getDatatype(), totalX, totalY, dx, dy, -1);
	calData->localToGlobal(0, 0, xstart, ystart);
	calData->savedxdyc(cal);
	cal.read(xstart, ystart, ny, nx, calData->getGridPointer());
			
	ndvter = (short*)cal.getNodata();	
			
	//Create partition and read data from sca grid file
	tdpartition *scaData;
	scaData = CreateNewPartition(sca.getDatatype(), totalX, totalY, dx, dy, sca.getNodata());
	scaData->localToGlobal(0, 0, xstart, ystart);
	scaData->savedxdyc(sca);
	sca.read(xstart, ystart, ny, nx, scaData->getGridPointer());

	//Create partition and read data from sca min grid file
	tdpartition *scaMinData = NULL;
	if (sca_min != NULL)
	{		
		scaMinData = CreateNewPartition(sca_min->getDatatype(), totalX, totalY, dx, dy, sca_min->getNodata());
		scaMinData->localToGlobal(0, 0, xstart, ystart);
		scaMinData->savedxdyc(*sca_min);
		sca_min->read(xstart, ystart, ny, nx, scaMinData->getGridPointer());
	}
	
	//Create partition and read data from sca max grid file
	tdpartition *scaMaxData = NULL;
	if(sca_max != NULL)
	{		
		scaMaxData = CreateNewPartition(sca_max->getDatatype(), totalX, totalY, dx, dy, sca_max->getNodata());
		scaMaxData->localToGlobal(0, 0, xstart, ystart);
		scaMaxData->savedxdyc(*sca_max);
		sca_max->read(xstart, ystart, ny, nx, scaMaxData->getGridPointer());
	}
	

	short cal_cell_value = 0;
	float slope_cell_value = 0;
	float sca_cell_value = 0;
	float sca_min_cell_value = 0;
	float sca_max_cell_value = 0;
	float csi_data = 0;
	int region_index = 0;

	//Create empty partition to store csi data
	tdpartition *csiData;
	csiData = CreateNewPartition(FLOAT_TYPE, totalX, totalY, dx, dy, -1.0f);

	//Create empty partition to store sat data
	tdpartition *satData;
	satData = CreateNewPartition(FLOAT_TYPE, totalX, totalY, dx, dy, -1.0f);

	//Share information and set borders to zero
	slpData->share();
	scaData->share();
	if(scaMinData != NULL)
	{
		scaMinData->share();
	}
	
	if(scaMaxData != NULL)
	{
		scaMaxData->share();
	}

	calData->share();
	csiData->clearBorders();
	satData->clearBorders();	
	
	for(j = 0; j < ny; j++) {
		for(i = 0; i < nx; i++ ) {
			calData->getData(i, j, cal_cell_value);
			slpData->getData(i, j, slope_cell_value);
			scaData->getData(i, j, sca_cell_value);
			if(scaMinData != NULL)
			{
				scaMinData->getData(i, j, sca_min_cell_value);
			}

			if(scaMaxData != NULL)
			{
				scaMaxData->getData(i, j, sca_max_cell_value);
			}
			
			region_index = findRegIndex(cal_cell_value, nor, *ndvter);
			
			//  DGT 12/31/14.  Changed the logic below from region_index < *ndvter to region_index < 0 to allow for *ndvter to be positive
			if (region_index < 0 || sca_cell_value < 0 || sca_min_cell_value < 0 || sca_max_cell_value < 0 || slope_cell_value == ndvs){
				csiData->setToNodata(i, j);
				satData->setToNodata(i, j);				
			}
			else{
				
				if(Rmaxter != 0 || sca_max_cell_value != 0){
					X2 = (sca_cell_value * Rmaxter + sca_max_cell_value)/region[region_index].tmin;
					X1 = (sca_cell_value * Rminter + sca_min_cell_value)/region[region_index].tmax;	
					csi_data = (float)sindexcell(slope_cell_value, 1,
								region[region_index].cmin, region[region_index].cmax, 
								region[region_index].tphimin, region[region_index].tphimax,
								X1, X2, region[region_index].r, &cellsat);
				
									
					csiData->setData(i, j, csi_data);
					satData->setData(i, j, float(cellsat));
					
				}				
			}				
		}
	}
	
	//  DGT 12/31/14 commented passing of borders.  This function acts locally so does not need any border sharing
	//Pass information
	//csiData->addBorders();		
	//satData->addBorders();	

	//Clear out borders
	//csiData->clearBorders();
	//satData->clearBorders();

	//Stop timer
	end = MPI_Wtime();
 	double compute, temp;
    compute = end-begin;

    MPI_Allreduce (&compute, &temp, 1, MPI_DOUBLE, MPI_SUM, MCW);
    compute = temp/size;

    if( rank == 0)
	{
		printf("Compute time: %f\n",compute);		
	}

	//Create and write to the csi TIFF file
	float aNodata = -1.0f;
	tiffIO csi(sincombinedfile, FLOAT_TYPE, &aNodata, slp);
	csi.write(xstart, ystart, ny, nx, csiData->getGridPointer());
	//Create and write to the sat TIFF file
	tiffIO sat(satfile, FLOAT_TYPE, &aNodata, slp);
	sat.write(xstart, ystart, ny, nx, satData->getGridPointer());

	}MPI_Finalize();

	return 0;
}
コード例 #10
0
// {sfb} will this work using a Calendar?
void TimeZoneRegressionTest:: Test4073215() 
{
    UErrorCode status = U_ZERO_ERROR;
    UnicodeString str, str2;
    SimpleTimeZone *z = new SimpleTimeZone(0, "GMT");
    if (z->useDaylightTime())
        errln("Fail: Fix test to start with non-DST zone");
    z->setStartRule(UCAL_FEBRUARY, 1, UCAL_SUNDAY, 0, status);
    failure(status, "z->setStartRule()");
    z->setEndRule(UCAL_MARCH, -1, UCAL_SUNDAY, 0, status);
    failure(status, "z->setStartRule()");
    if (!z->useDaylightTime())
        errln("Fail: DST not active");

    GregorianCalendar cal(1997, UCAL_JANUARY, 31, status);
    if(U_FAILURE(status)) {
      dataerrln("Error creating calendar %s", u_errorName(status));
      return;
    }
    failure(status, "new GregorianCalendar");
    cal.adoptTimeZone(z);

    SimpleDateFormat sdf((UnicodeString)"E d MMM yyyy G HH:mm", status); 
    if(U_FAILURE(status)) {
      dataerrln("Error creating date format %s", u_errorName(status));
      return;
    }
    sdf.setCalendar(cal); 
    failure(status, "new SimpleDateFormat");

    UDate jan31, mar1, mar31;

    UBool indt = z->inDaylightTime(jan31=cal.getTime(status), status);
    failure(status, "inDaylightTime or getTime call on Jan 31");
    if (indt) {
        errln("Fail: Jan 31 inDaylightTime=TRUE, exp FALSE");
    }
    cal.set(1997, UCAL_MARCH, 1);
    indt = z->inDaylightTime(mar1=cal.getTime(status), status);
    failure(status, "inDaylightTime or getTime call on Mar 1");
    if (!indt) {
        UnicodeString str;
        sdf.format(cal.getTime(status), str);
        failure(status, "getTime");
        errln((UnicodeString)"Fail: " + str + " inDaylightTime=FALSE, exp TRUE");
    }
    cal.set(1997, UCAL_MARCH, 31);
    indt = z->inDaylightTime(mar31=cal.getTime(status), status);
    failure(status, "inDaylightTime or getTime call on Mar 31");
    if (indt) {
        errln("Fail: Mar 31 inDaylightTime=TRUE, exp FALSE");
    }

    /*
    cal.set(1997, Calendar::DECEMBER, 31);
    UDate dec31 = cal.getTime(status);
    failure(status, "getTime");
    UDate trans = findTransitionStepwise(*z, jan31, dec31);
    logln((UnicodeString)"Stepwise from " +
          sdf.format(jan31, str.remove()) + "; transition at " +
          (trans?sdf.format(trans, str2.remove()):(UnicodeString)"NONE"));
    trans = findTransitionStepwise(*z, mar1, dec31);
    logln((UnicodeString)"Stepwise from " +
          sdf.format(mar1, str.remove()) + "; transition at " +
          (trans?sdf.format(trans, str2.remove()):(UnicodeString)"NONE"));
    trans = findTransitionStepwise(*z, mar31, dec31);
    logln((UnicodeString)"Stepwise from " +
          sdf.format(mar31, str.remove()) + "; transition at " +
          (trans?sdf.format(trans, str2.remove()):(UnicodeString)"NONE"));
    */
}
コード例 #11
0
ファイル: 1001-wa.cpp プロジェクト: gjmingsg/Code
int main()
{
    char R[7],*p;
    long long ans[50];
    int i,plength,pindex,length,n,numlength,ppindex,endindex,temp;
   
    while(scanf("%s%d",R,&n)!=-1)
    {
        if(n==0)
        {
            printf("1\n");
            continue;          
        }
        length = strlen(R);
        if(length == 0 && R[0] == '0' && n == 1)
        {
            printf("1\n");
            continue;        
        } 
        p = strchr(R,'.');
      
        if(p == NULL)
            pindex = length;
        else
            pindex = p - R;
        
        plength = (length - pindex - 1) * n;
        for(i = 0 ; i < 50; i ++)
            ans[i] = 0l;
        length = cal(R,n,ans);
        numlength = length * 4;
        ///如果小数点的格式是.xxxxxx .001
        if(plength >= numlength + getLength(ans[length]))
        {
            endindex = chechEnd(ans,length);
            printf(".");
            temp = plength - numlength - getLength(ans[length]);
            for(i = 0 ; i < temp; i ++)
                printf("0");
            if(endindex == length)
            {
                 temp = (int) ans[length];
                 while(temp%10 == 0)
                     temp/=10;
                 printf("%d\n",temp);
            }
            else
            {
                for(i = length - 1; i > endindex; i --)
                    printf("%04ld",ans[i]);
                printEnd(ans[endindex]);
            }

        }
        else
        {
            ///如果小数点是xxxx. 
            if(plength == 0)
            {
                printf("%ld",ans[length]);        
                for(i = length - 1; i >= 0; i --)
                    printf("%04ld",ans[i]);
                printf("\n");        
            }
            else
            {
                ///如果小数点是xxxx.xxxx 
                 pindex = plength % 4;
                 ppindex = plength /4;
               
                 endindex = chechEnd(ans,length);
                 temp = (endindex>ppindex?ppindex:endindex);
                 for(i = length; i > temp; i --)
                 {
                     if(ppindex == i)
                     {
                         if(i == length)
                             printPoint(ans[i],pindex,'h');
                         else
                             printPoint(ans[i],pindex,'m');      
                     }
                     else
                     {
                         if(i == length)
                            printf("%ld",ans[i]); 
                         else
                            printf("%04ld",ans[i]); 
                         
                     }
                 }
                 ///如果小数点xxxx000.,XXXX000.01
                 if(ppindex < endindex)
                 {
                      if(pindex == 0)
                          printf("0000\n");
                      if(pindex == 1)
                          printf("000\n");
                      else if(pindex == 2)
                          printf("00\n");
                      else if(pindex == 3)
                          printf("0\n");
                 }    
                 else if(ppindex == endindex)
                 {
                      if(pindex == 0)
                          printf("%04ld\n",ans[endindex]);
                      else
                      {
                          printPoint(ans[endindex],pindex,'m'); 
                          printf("\n");
                      }
                 }
                 else
                     printEnd(ans[endindex]);
                 
            }       
        }      
    } 
    return 0;    
}
コード例 #12
0
ファイル: data.cpp プロジェクト: yuany12/tree
void Data::setMstType(char type)
{
    mst->setType(type);
    cal();
}
コード例 #13
0
ファイル: 4_10.c プロジェクト: wxiaodong0829/aka_edu_learned
int calculator(int a, int b, int (*cal)(int a, int b))
{
	return cal(a, b);
}
コード例 #14
0
ファイル: main.c プロジェクト: ajmas/NewSRT
int main(int argc, char *argv[])
{
    GtkWidget *window;
    GtkWidget *button_clear, *button_azel, *button_freq, *button_offset;
    GtkWidget *button_help;
    GdkColor color;
    int i, ii;
    int yr, da, hr, mn, sc;
    double secstart;
    char buf[64];
    GdkGeometry geometry;
    GdkWindowHints geo_mask;
//    GdkRectangle update_rect;
    sprintf(d1.catnam, "srt.cat");
    sprintf(d1.hlpnam, "srt.hlp");
    for (i = 0; i < argc - 1; i++) {
        sscanf(argv[i], "%63s", buf);
        if (strstr(buf, "-c") && strlen(buf) == 2)
            sscanf(argv[i + 1], "%63s", d1.catnam);
        if (strstr(buf, "-h") && strlen(buf) == 2)
            sscanf(argv[i + 1], "%63s", d1.hlpnam);
    }
//    d1.azelport = 0x3f8;        // com1 default for old SRT 
    d1.ver = 4;  // SRT software version
    d1.secs = readclock();
    d1.run = 1;
    d1.record = 0;
    d1.entry1 = d1.entry2 = d1.entry3 = d1.entry5 = d1.entry6 = d1.entry8 = d1.helpwindow = d1.vwindow = 0;
    d1.plot = 0;
    d1.start_time = 0.0;
    d1.start_sec = 0.0;
    d1.speed_up = 0;
    d1.ppos = 0;
    d1.printout = 1;
    d1.debug = 0;
    d1.freq = 1420.4;           // default
    d1.bw = 0;                  // set to 2.4 for TV dongle 10 MHz for ADC card in init
    d1.fbw = 0;                 // set in init or srt.cat
    d1.nblk = 5;                // number of blocks in vspectra
    d1.record_int_sec = 0;
    d1.freqcorr = 0;            // frequency correction for L.O. may be needed for TV dongle
    d1.freqchng = 0;
    d1.clearint = 0;
    d1.record_clearint = 0;
    d1.noclearint = 0;
    d1.nfreq = NSPEC;
    d1.plotsec = 1;
    d1.displ = 1;
    d1.noisecal = 0;
//    used for old SRT mount and controller
//    d1.ptoler = 1;
//    d1.countperstep = 10000;    // default large number for no stepping 
//    d1.elcounts_per_deg = (52.0 * 27.0 / 120.0); // default for H-180
//    d1.azcounts_per_deg = 8.0 * 32.0 * 60.0 / (360.0 * 9.0); // default for CASSIMOUNT
//    d1.rod = 1;                 // default to rod as on CASSIMOUNT
//    d1.rod1 = 14.25;            // rigid arm length
//    d1.rod2 = 16.5;             // distance from pushrod upper joint to el axis
//    d1.rod3 = 2.0;              // pushrod collar offset
//    d1.rod4 = 110.0;            // angle at horizon
//    d1.rod5 = 30.0;             // pushrod counts per inch
    d1.azelsim = d1.radiosim = d1.fftsim = 0;
    d1.mainten = 0;
    d1.stowatlim = 1;
    d1.rms = -1;                // display max not rms 
    d1.calcons = 1.0;
    d1.caldone = 0;
    d1.nrfi = 0;
    d1.rfisigma = 6;            // level for RFI reporting to screen
    d1.tload = 300.0;
    d1.tspill = 20.0;
    d1.beamw = 5.0;
    d1.comerr = 0;
    d1.limiterr = 0;
    d1.restfreq = 1420.406;     /* H-line restfreq */
    d1.delay = 0;
    d1.azoff = 0.0;
    d1.eloff = 0.0;
    d1.drift = 0;
    d1.tstart = 0;
    d1.tsys = 100.0;            // expected on cold sky
    d1.pwroff = 0.0;
    d1.tant = 100.0;
    d1.calpwr = 0;
    d1.yfac = 0;
    d1.calon = 0;
    d1.calmode = 0;
    d1.docal = 0;
    d1.tcal = 290;              // absorber or bushes
    d1.sourn = 0;
    d1.track = 0;
    d1.scan = 0;
    d1.bsw = 0;
    d1.nbsw = 1;
    d1.obsn = 0;
    d1.stopproc = 0;
    d1.fstatus = 0;
    d1.cmdfl = 0;
    d1.south = 1;
    d1.hgt = 0;
    d1.dongle = 0;              // set to zero initially - set to 1 in Init_Device if dongle
    d1.npoly = 25;              // number of terms in polynomial fit of bandpass
    pwrst = pwrprev = 0.0;
    soutrack[0] = 0;
    sprintf(d1.cmdfnam, "cmd.txt");
    sprintf(d1.datadir, "./");  // default to local directory

    if (!catfile())
        return 0;
    d1.foutstatus = 0;
// to get permission su root chown root srtn then chmod u+s srtn then exit 
    if (!d1.azelsim) {
        if (d1.printout)
            printf("initializing antenna controller\n");
        i = rot2(&d1.aznow, &d1.elnow, -1, buf); // initialize
        i = rot2(&d1.aznow, &d1.elnow, 1, buf); // read
        if (i < 0) {
            printf("Couldn't talk to antenna controller\n");
            return 0;
        }
    } else {
        if (d1.stowatlim) {
            d1.azprev = d1.azlim1;
            d1.elprev = d1.ellim1;
        } else {
            d1.azprev = d1.stowaz;
            d1.elprev = d1.stowel;
        }
    }
    setgid(getgid());
    setuid(getuid());
    if (d1.mainten == 0) {
        if (d1.stowatlim) {
            d1.azcmd = d1.azlim1;
            d1.elcmd = d1.ellim1;
        } else {
            d1.azcmd = d1.stowaz;
            d1.elcmd = d1.stowel;
        }
        d1.azcount = 0;
        d1.elcount = 0;
        d1.stow = 1;
    }
    if (d1.azlim1 > d1.azlim2) {
        d1.south = 0;           // dish pointing North for southern hemisphere
        if (d1.azlim2 < 360.0)
            d1.azlim2 += 360.0;
    }

    if (!d1.radiosim)
        Init_Device(0);

    if (d1.displ) {
        gtk_init(&argc, &argv);
        window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        geometry.min_width = 500;
        geometry.min_height = 300;
        geo_mask = GDK_HINT_MIN_SIZE;
        gtk_window_set_geometry_hints(GTK_WINDOW(window), window, &geometry, geo_mask);
        //Table size determines number of buttons across the top
        table = gtk_table_new(30, NUMBUTTONS, TRUE);

        drawing_area = gtk_drawing_area_new();
        gtk_window_set_default_size(GTK_WINDOW(window), 800, 600);
        color.red = 0xffff;
        color.blue = 0xffff;
        color.green = 0xffff;
        gtk_widget_show(drawing_area);
        gtk_table_attach_defaults(GTK_TABLE(table), drawing_area, 0, NUMBUTTONS, 3, 30);

        g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(quit), NULL);

        gtk_container_add(GTK_CONTAINER(window), table);

        g_signal_connect(G_OBJECT(drawing_area), "expose_event", (GtkSignalFunc) expose_event, NULL);
        g_signal_connect(G_OBJECT(drawing_area), "configure_event", (GtkSignalFunc) configure_event, NULL);

        g_signal_connect(G_OBJECT(drawing_area), "button_press_event",
                         (GtkSignalFunc) button_press_event, NULL);

        gtk_widget_set_events(drawing_area, GDK_EXPOSURE_MASK
                              | GDK_LEAVE_NOTIFY_MASK
                              | GDK_BUTTON_PRESS_MASK
                              | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);


        button_clear = gtk_button_new_with_label("clear");
        button_stow = gtk_button_new_with_label("stow");
        button_azel = gtk_button_new_with_label("azel");
        button_npoint = gtk_button_new_with_label("npoint");
        button_bsw = gtk_button_new_with_label("beamsw");
        button_freq = gtk_button_new_with_label("freq");
        button_offset = gtk_button_new_with_label("offset");
        button_record = gtk_button_new_with_label("record");
        button_cmdfl = gtk_button_new_with_label("cmdfl");
        button_cal = gtk_button_new_with_label("cal");
        button_help = gtk_button_new_with_label("help");
        button_exit = gtk_button_new_with_label("exit");

        g_signal_connect(G_OBJECT(button_clear), "clicked", G_CALLBACK(button_clear_clicked), NULL);
        g_signal_connect(G_OBJECT(button_stow), "clicked", G_CALLBACK(button_stow_clicked), NULL);
        g_signal_connect(G_OBJECT(button_azel), "clicked", G_CALLBACK(button_azel_clicked), NULL);
        g_signal_connect(G_OBJECT(button_npoint), "clicked", G_CALLBACK(button_npoint_clicked), NULL);
        g_signal_connect(G_OBJECT(button_bsw), "clicked", G_CALLBACK(button_bsw_clicked), NULL);
        g_signal_connect(G_OBJECT(button_freq), "clicked", G_CALLBACK(button_freq_clicked), NULL);
        g_signal_connect(G_OBJECT(button_offset), "clicked", G_CALLBACK(button_offset_clicked), NULL);
        g_signal_connect(G_OBJECT(button_record), "clicked", G_CALLBACK(button_record_clicked), NULL);
        g_signal_connect(G_OBJECT(button_cmdfl), "clicked", G_CALLBACK(button_cmdfl_clicked), NULL);
        g_signal_connect(G_OBJECT(button_cal), "clicked", G_CALLBACK(button_cal_clicked), NULL);
        g_signal_connect(G_OBJECT(button_help), "clicked", G_CALLBACK(button_help_clicked), NULL);
        g_signal_connect(G_OBJECT(button_exit), "clicked", G_CALLBACK(button_exit_clicked), NULL);

        // test setting up tooltips instead of the "enter"/"leave" used below
        tooltips = gtk_tooltips_new();
        gtk_tooltips_set_tip(tooltips, button_clear,
                             "click to clear integration and reset time plot to 1/4-scale", NULL);
        gtk_tooltips_set_tip(tooltips, button_stow, "click to stow antenna", NULL);
        gtk_tooltips_set_tip(tooltips, button_azel, "click to enter az el coordinates", NULL);
        gtk_tooltips_set_tip(tooltips, button_npoint, "click to start npoint scan", NULL);
        gtk_tooltips_set_tip(tooltips, button_bsw, "click to start beam switch", NULL);
        gtk_tooltips_set_tip(tooltips, button_freq, "click to enter new frequency in MHz [bandwidth] [nfreq]",
                             NULL);
        gtk_tooltips_set_tip(tooltips, button_offset, "click to enter offsets", NULL);
        if (!d1.cmdfl)
            gtk_tooltips_set_tip(tooltips, button_cmdfl, "click to start cmd file", NULL);
        else
            gtk_tooltips_set_tip(tooltips, button_cmdfl, "click to stop cmd file", NULL);

        gtk_tooltips_set_tip(tooltips, button_cal, "click to start calibration", NULL);
        gtk_tooltips_set_tip(tooltips, button_help, "click to open help window", NULL);
        record_tooltip();


        gtk_table_attach(GTK_TABLE(table), button_clear, 0, 1, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_stow, 1, 2, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_azel, 2, 3, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_npoint, 3, 4, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_bsw, 4, 5, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_freq, 5, 6, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_offset, 6, 7, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_record, 7, 8, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_cmdfl, 8, 9, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_cal, 9, 10, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_help, 10, 11, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_exit, 11, 12, 0, 2, GTK_FILL, GTK_FILL, 0, 0);



        gtk_widget_show(button_clear);
        gtk_widget_show(button_stow);
        gtk_widget_show(button_azel);
        gtk_widget_show(button_npoint);
        gtk_widget_show(button_bsw);
        gtk_widget_show(button_freq);
        gtk_widget_show(button_offset);
        gtk_widget_show(button_record);
        gtk_widget_show(button_cmdfl);
        gtk_widget_show(button_cal);
        gtk_widget_show(button_help);
        gtk_widget_show(button_exit);


        gtk_widget_show(table);
        gtk_widget_show(window);
        clearpaint();
    }
    ii = 0;
    if (d1.printout) {
        toyrday(d1.secs, &yr, &da, &hr, &mn, &sc);
        printf("%4d:%03d:%02d:%02d:%02d %3s ", yr, da, hr, mn, sc, d1.timsource);
    }
    zerospectra(0);
    for (i = 0; i < d1.nfreq; i++)
        bspec[i] = 1;
    secstart = d1.nsecstart = -1;
    d1.secs = readclock();
    while (d1.run) {
        zerospectra(1);
        if (d1.clearint) {
            if (d1.displ)
                cleararea();
            zerospectra(0);
            d1.clearint = 0;
        }
        if (d1.freqchng) {
            if (d1.dongle)
                Init_Device(1);
            if (d1.printout) {
                toyrday(d1.secs, &yr, &da, &hr, &mn, &sc);
                printf("%4d:%03d:%02d:%02d:%02d %3s ", yr, da, hr, mn, sc, d1.timsource);
            }
            if (!d1.radiosim) {
                sleep(1);
            }
            zerospectra(0);
            d1.freqchng = 0;
        }
        if (d1.docal) {
            if (d1.docal == 1) {
                sprintf(d1.recnote, "* calibration started\n");
                outfile(d1.recnote);
            }
            if (d1.bsw) {
                d1.bsw = 0;
                d1.azoff = 0.0;
            }
            if (d1.scan) {
                d1.scan = 0;
                d1.eloff = d1.azoff = 0.0;
            }
            if (d1.slew)
                d1.slew = 0;
            if (d1.docal == 1)
                cal(0);
            d1.docal = 2;
            cal(1);
            if (d1.integ >= NCAL) {
                cal(2);
                d1.docal = 0;
            }
        }

        if (d1.displ)
            cleararea();
        azel(d1.azcmd, d1.elcmd); // allow time after cal 
        if (d1.comerr == -1)
            return 0;
        if (!d1.slew) {
            pwr = 0.0;
        }
        if (!d1.slew)
            vspectra();
        d1.secs = readclock();
        aver();
        d1.integ2++;
        if (d1.record_int_sec && d1.integ2 >= d1.record_int_sec) {
            outfile(" ");
            if (d1.record_clearint && d1.track && !d1.bsw && !d1.scan)
                d1.clearint = 1;
            d1.integ2 = 0;
        }
        if (d1.displ) {
            if (!d1.plot)
                Repaint();
            while (gtk_events_pending() || d1.stopproc == 1) {
                gtk_main_iteration();
                d1.plot = 0;
            }
        }
        if (!d1.displ && d1.domap)
            scanplot();
    }
    return 0;
}
コード例 #15
0
ファイル: NetEM.cpp プロジェクト: cns-iu/nwb
int main(int argc, char *argv[])
{
    input_file input(argc, argv);

    std::string mdl = input.getStringOpt("model");
    unsigned seed = input.getUnsignedOpt("seed");
    unsigned M = input.getUnsignedOpt("M", 3);

    if(M<2)
    {
        fprintf(stderr, "Memory (M) must be larger or equal to 2\n");
        exit(3);
    }

    std::string infections = input.getStringOpt("infections");
    std::string network = input.getStringOpt("network");
    std::string output = input.getStringOpt("output");
    std::string name = input.getStringOpt("name", std::string("0"));
    unsigned days = input.getUnsignedOpt("days");
    unsigned events = input.getUnsignedOpt("events", 2);
    string outVal = input.getStringOpt("outVal");
    string date = input.getStringOpt("date");
    string frames = input.getStringOpt("frames", "none");

    output = unquoteString(output);
    outVal = unquoteString(outVal);
    frames = unquoteString(frames);

#ifdef BGDEBUG
    input.writeToFile(stderr);
    input.writeToFile(stderr, mdl);
    input.writeToFile(stderr, infections);
#endif
    //Ensure that the directory name has a trailing "/"
    if(output[output.size()-1]!='/')
        output+="/";

    if(frames != "none" && frames[frames.size()-1]!='/')
        frames+="/";


#ifdef _WIN32
    freopen((output + "NetEM." + name + ".out.dat").c_str(), "w", stdout);
    freopen((output + "NetEM." + name + ".err.dat").c_str(), "w", stderr);
#else
    stdout = fopen((output+"NetEM."+name+".out.dat").c_str(),"w");
    stderr = fopen((output+"NetEM."+name+".err.dat").c_str(),"w");
#endif // _WIN32

    for(unsigned i=0; i<argc; ++i)
        printf("# %u %s\n", i, argv[i]);

    Parse parse(mdl);
    Rand r(seed);

    Graph g(network);
    std::vector<std::vector<NODE> > graph = g.getGraph();

    unsigned N = graph.size();
    unsigned susIndex = parse.susceptible();
    unsigned recIndex = parse.recovered();
    unsigned NStates = parse.NStates();
    std::vector<unsigned> Ni = g.getPi();
    ModelNetwork model(parse, &r);
    uint64_t secondary;

    std::vector<std::string> outComp = getVector(outVal);
    std::vector<unsigned> outCompIndex;

    fprintf(stderr,"# Found %u comps\n", unsigned(outComp.size()));

    std::vector<Transition> transList = parse.getTransitions();

    std::vector<unsigned> outTrans(transList.size(), 0);

    for(unsigned i=0; i<outComp.size(); ++i)
    {
        fprintf(stderr,"%u \"%s\"",i,outComp[i].c_str());

        unsigned comp = parse.label(outComp[i]);

        outCompIndex.push_back(comp);

        for(unsigned j=0; j<transList.size(); ++j)
        {
            if(transList[j].j == comp)
            {
                outTrans[j] = 1;
                fprintf(stderr," %u",j);
            }
        }

        fprintf(stderr, "\n");
    }

    bool hasFrames = false;

    if(frames != "none")
        hasFrames = true;

    do {
        Population nodes(M, N, susIndex, recIndex);

        nodes.seeding(infections, 0, parse, r);

        FILE *fpout = input.openFile((output + "NetEM." + name + ".out"));
        FILE *fperr = input.openFile((output + "NetEM." + name + ".err"));
        FILE *fpsec = input.openFile((output + "NetEM." + name + ".sec"));

        FILE *fpstate;

        if(hasFrames)
        {
            fpstate = input.openFile((frames + "NetEM." + name + ".state"));
            g.saveHeader(fpstate);
        }

        fprintf(fpout, "# time");

        Output outData(N, days+1);
        for(unsigned i=0; i<NStates; ++i)
            fprintf(fpout, " %s", parse.index(i).c_str());

        fprintf(fpout, "\n");

        secondary = 0;

        vector<uint64_t> transCount;
        Calendar cal(date);
        unsigned day0 = cal.day();
        for(unsigned step = 0; step < days; ++step)
        {
            unsigned delta = model.step(graph, nodes, Ni, step, fperr,  outTrans, transCount);

            secondary += delta;
            outData.add(transCount, step);

            if(hasFrames)
                nodes.saveState(step, fpstate);

            nodes.savePopulations(step, NStates, fpout);

            fprintf(fpsec, "%u %u\n",step, delta);
        }

        fclose(fpout);
        fclose(fperr);
        fclose(fpsec);

        if (hasFrames)
            fclose(fpstate);

        fprintf(stderr, "outbreak = %Lu\n", secondary);

        if(secondary > events)
        {
            outData.writeToFile(output+"sum");
        }

    } while(secondary < events);



    return 0;
}
コード例 #16
0
void TestMessageFormat::testSetLocale()
{
    UErrorCode err = U_ZERO_ERROR;
    GregorianCalendar cal(err);   
    Formattable arguments[] = {
        456.83,
        Formattable(UDate(8.71068e+011), Formattable::kIsDate),
        "deposit"
        };
   
    UnicodeString result;

    //UnicodeString formatStr = "At {1,time} on {1,date}, you made a {2} of {0,number,currency}.";
    UnicodeString formatStr = "At <time> on {1,date}, you made a {2} of {0,number,currency}.";
    // {sfb} to get $, would need Locale::US, not Locale::ENGLISH
    // Just use unlocalized currency symbol.
    //UnicodeString compareStrEng = "At <time> on Aug 8, 1997, you made a deposit of $456.83.";
    UnicodeString compareStrEng = "At <time> on Aug 8, 1997, you made a deposit of ";
    compareStrEng += (UChar) 0x00a4;
    compareStrEng += "456.83.";
    // {sfb} to get DM, would need Locale::GERMANY, not Locale::GERMAN
    // Just use unlocalized currency symbol.
    //UnicodeString compareStrGer = "At <time> on 08.08.1997, you made a deposit of 456,83 DM.";
    UnicodeString compareStrGer = "At <time> on 08.08.1997, you made a deposit of ";
    compareStrGer += "456,83 ";
    compareStrGer += (UChar) 0x00a4;
    compareStrGer += ".";

    MessageFormat msg( formatStr, err);
    result = "";
    FieldPosition pos(0);
    result = msg.format(
        arguments,
        3,
        result,
        pos,
        err);

    logln(result);
    if (result != compareStrEng) {
        errln("***  MSG format err.");
    }

    msg.setLocale(Locale::getEnglish());
    UBool getLocale_ok = TRUE;
    if (msg.getLocale() != Locale::getEnglish()) {
        errln("*** MSG getLocal err.");
        getLocale_ok = FALSE;
    }

    msg.setLocale(Locale::getGerman());

    if (msg.getLocale() != Locale::getGerman()) {
        errln("*** MSG getLocal err.");
        getLocale_ok = FALSE;
    }

    msg.applyPattern( formatStr, err);

    pos.setField(0);
    result = "";
    result = msg.format(
        arguments,
        3,
        result,
        pos,
        err);

    logln(result);
    if (result == compareStrGer) {
        logln("MSG setLocale tested.");
    }else{
        errln( "*** MSG setLocale err.");
    }

    if (getLocale_ok) { 
        logln("MSG getLocale tested.");
    }
}
コード例 #17
0
//---------------------------------------
UnicodeString&
TimeZone::getDisplayName(UBool daylight, EDisplayType style, const Locale& locale, UnicodeString& result) const
{
    // SRL TODO: cache the SDF, just like java.
    UErrorCode status = U_ZERO_ERROR;
#ifdef U_DEBUG_TZ
    char buf[128];
    fID.extract(0, sizeof(buf)-1, buf, sizeof(buf), "");
#endif
    SimpleDateFormat format(style == LONG ? ZZZZ_STR : Z_STR, locale, status);
    U_DEBUG_TZ_MSG(("getDisplayName(%s)\n", buf));
    if(!U_SUCCESS(status))
    {
#ifdef U_DEBUG_TZ
      char buf2[128];
      result.extract(0, sizeof(buf2)-1, buf2, sizeof(buf2), "");
      U_DEBUG_TZ_MSG(("getDisplayName(%s) -> %s\n", buf, buf2));
#endif
      return result.remove();
    }

    UDate d = Calendar::getNow();
    int32_t  rawOffset;
    int32_t  dstOffset;
    this->getOffset(d, FALSE, rawOffset, dstOffset, status);
    if (U_FAILURE(status)) {
        return result.remove();
    }
    
    if ((daylight && dstOffset != 0) || (!daylight && dstOffset == 0)) {
        // Current time and the request (daylight / not daylight) agree.
        format.setTimeZone(*this);
        return format.format(d, result);
    }
    
    // Create a new SimpleTimeZone as a stand-in for this zone; the
    // stand-in will have no DST, or DST during July, but the same ID and offset,
    // and hence the same display name.
    // We don't cache these because they're small and cheap to create.
    UnicodeString tempID;
    getID(tempID);
    SimpleTimeZone *tz = NULL;
    if(daylight && useDaylightTime()){
        // The display name for daylight saving time was requested, but currently not in DST
        // Set a fixed date (July 1) in this Gregorian year
        GregorianCalendar cal(*this, status);
        if (U_FAILURE(status)) {
            return result.remove();
        }
        cal.set(UCAL_MONTH, UCAL_JULY);
        cal.set(UCAL_DATE, 1);
        
        // Get July 1 date
        d = cal.getTime(status);
        
        // Check if it is in DST
        if (cal.get(UCAL_DST_OFFSET, status) == 0) {
            // We need to create a fake time zone
            tz = new SimpleTimeZone(rawOffset, tempID,
                                UCAL_JUNE, 1, 0, 0,
                                UCAL_AUGUST, 1, 0, 0,
                                getDSTSavings(), status);
            if (U_FAILURE(status) || tz == NULL) {
                if (U_SUCCESS(status)) {
                    status = U_MEMORY_ALLOCATION_ERROR;
                }
                return result.remove();
            }
            format.adoptTimeZone(tz);
        } else {
            format.setTimeZone(*this);
        }
    } else {
        // The display name for standard time was requested, but currently in DST
        // or display name for daylight saving time was requested, but this zone no longer
        // observes DST.
        tz = new SimpleTimeZone(rawOffset, tempID);
        if (U_FAILURE(status) || tz == NULL) {
            if (U_SUCCESS(status)) {
                status = U_MEMORY_ALLOCATION_ERROR;
            }
            return result.remove();
        }
        format.adoptTimeZone(tz);
    }

    format.format(d, result, status);
    return  result;
}
コード例 #18
0
ファイル: libcore_icu_ICU.cpp プロジェクト: TeamNyx/libcore
static jboolean ICU_initLocaleDataImpl(JNIEnv* env, jclass, jstring locale, jobject localeData) {
    ScopedUtfChars localeName(env, locale);
    if (localeName.c_str() == NULL) {
        return JNI_FALSE;
    }

    // Get DateTimePatterns
    UErrorCode status;
    char currentLocale[ULOC_FULLNAME_CAPACITY];
    int32_t localeNameLen = 0;
    if (localeName.size() >= ULOC_FULLNAME_CAPACITY) {
        return JNI_FALSE;  // Exceed ICU defined limit of the whole locale ID.
    }
    strcpy(currentLocale, localeName.c_str());
    do {
        status = U_ZERO_ERROR;
        ScopedResourceBundle root(ures_open(NULL, currentLocale, &status));
        if (U_FAILURE(status)) {
            if (localeNameLen == 0) {
                break;  // No parent locale, report this error outside the loop.
            } else {
                status = U_ZERO_ERROR;
                continue;  // get parent locale.
            }
        }
        ScopedResourceBundle calendar(ures_getByKey(root.get(), "calendar", NULL, &status));
        if (U_FAILURE(status)) {
            status = U_ZERO_ERROR;
            continue;  // get parent locale.
        }

        ScopedResourceBundle gregorian(ures_getByKey(calendar.get(), "gregorian", NULL, &status));
        if (U_FAILURE(status)) {
            status = U_ZERO_ERROR;
            continue;  // get parent locale.
        }
        ScopedResourceBundle dateTimePatterns(ures_getByKey(gregorian.get(), "DateTimePatterns", NULL, &status));
        if (U_SUCCESS(status)) {
            setStringField(env, localeData, "fullTimeFormat", dateTimePatterns.get(), 0);
            setStringField(env, localeData, "longTimeFormat", dateTimePatterns.get(), 1);
            setStringField(env, localeData, "mediumTimeFormat", dateTimePatterns.get(), 2);
            setStringField(env, localeData, "shortTimeFormat", dateTimePatterns.get(), 3);
            setStringField(env, localeData, "fullDateFormat", dateTimePatterns.get(), 4);
            setStringField(env, localeData, "longDateFormat", dateTimePatterns.get(), 5);
            setStringField(env, localeData, "mediumDateFormat", dateTimePatterns.get(), 6);
            setStringField(env, localeData, "shortDateFormat", dateTimePatterns.get(), 7);
            break;
        } else {
            status = U_ZERO_ERROR;  // get parent locale.
        }
    } while((localeNameLen = uloc_getParent(currentLocale, currentLocale, sizeof(currentLocale), &status)) >= 0);
    if (U_FAILURE(status)) {
        ALOGE("Error getting ICU resource bundle: %s", u_errorName(status));
        return JNI_FALSE;
    }

    status = U_ZERO_ERROR;
    Locale localeObj = getLocale(env, locale);

    UniquePtr<Calendar> cal(Calendar::createInstance(localeObj, status));
    if (U_FAILURE(status)) {
        return JNI_FALSE;
    }
    setIntegerField(env, localeData, "firstDayOfWeek", cal->getFirstDayOfWeek());
    setIntegerField(env, localeData, "minimalDaysInFirstWeek", cal->getMinimalDaysInFirstWeek());

    // Get DateFormatSymbols
    status = U_ZERO_ERROR;
    DateFormatSymbols dateFormatSym(localeObj, status);
    if (U_FAILURE(status)) {
        return JNI_FALSE;
    }
    int32_t count = 0;
    // Get AM/PM marker
    const UnicodeString* amPmStrs = dateFormatSym.getAmPmStrings(count);
    setStringArrayField(env, localeData, "amPm", amPmStrs, count);
    const UnicodeString* erasStrs = dateFormatSym.getEras(count);
    setStringArrayField(env, localeData, "eras", erasStrs, count);

    const UnicodeString* longMonthNames =
       dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longMonthNames", longMonthNames, count);
    const UnicodeString* shortMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortMonthNames", shortMonthNames, count);
    const UnicodeString* longWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longWeekdayNames", longWeekdayNames, count);
    const UnicodeString* shortWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortWeekdayNames", shortWeekdayNames, count);

    const UnicodeString* longStandAloneMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longStandAloneMonthNames", longStandAloneMonthNames, count);
    const UnicodeString* shortStandAloneMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortStandAloneMonthNames", shortStandAloneMonthNames, count);
    const UnicodeString* longStandAloneWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longStandAloneWeekdayNames", longStandAloneWeekdayNames, count);
    const UnicodeString* shortStandAloneWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortStandAloneWeekdayNames", shortStandAloneWeekdayNames, count);

    status = U_ZERO_ERROR;

    // For numberPatterns and symbols.
    setNumberPatterns(env, localeData, locale);
    setDecimalFormatSymbolsData(env, localeData, locale);

    jstring countryCode = env->NewStringUTF(Locale::createFromName(localeName.c_str()).getCountry());
    jstring internationalCurrencySymbol = ICU_getCurrencyCode(env, NULL, countryCode);
    env->DeleteLocalRef(countryCode);
    countryCode = NULL;

    jstring currencySymbol = NULL;
    if (internationalCurrencySymbol != NULL) {
        currencySymbol = ICU_getCurrencySymbol(env, NULL, locale, internationalCurrencySymbol);
    } else {
        internationalCurrencySymbol = env->NewStringUTF("XXX");
    }
    if (currencySymbol == NULL) {
        // This is the UTF-8 encoding of U+00A4 (CURRENCY SIGN).
        currencySymbol = env->NewStringUTF("\xc2\xa4");
    }
    setStringField(env, localeData, "currencySymbol", currencySymbol);
    setStringField(env, localeData, "internationalCurrencySymbol", internationalCurrencySymbol);

    return JNI_TRUE;
}
コード例 #19
0
ファイル: CalibrationManager.cpp プロジェクト: schiebel/casa
void CalibrationManager::calibrate()
{
  os_.origin(LogOrigin("CalibrationManager","calibrate",WHERE));
  os_ << LogIO::DEBUGGING << "start calibration with mode " << calmode_ << "." << LogIO::POST;
  //assert(!target_.null());
  assert_<AipsError>(!target_.null(), "You have to set target scantable first.");
  if (calmode_ == "TSYS") {
    //assert(spwlist_.size() > 0);
    if (spwlist_withrange_.empty()) {
      assert_<AipsError>(spwlist_.size() > 0, "You have to set list of IFNOs for ATM calibration.");
      STCalTsys cal(target_, spwlist_);
      cal.calibrate();
      tsystables_.push_back(cal.applytable());
    }
    else {
      STCalTsys cal(target_, spwlist_withrange_, do_average_);
      cal.calibrate();
      tsystables_.push_back(cal.applytable());
    }      
  }
  else if (calmode_ == "PS") {
//     // will match DV01-25, DA41-65, PM01-04, CM01-12
//     Regex reant("^(DV(0[1-9]|1[0-9]|2[0-5])|DA(4[1-9]|5[0-9]|6[0-5])|PM0[1-4]|CM(0[1-9]|1[1,2]))$");
//     const String antname = target_->getAntennaName();
//     if (reant.match(antname.c_str(), antname.size()) != String::npos) {
    if (isAlmaAntenna()) {
      os_ << LogIO::DEBUGGING << "ALMA specific position-switch calibration." << LogIO::POST; 
      STCalSkyPSAlma cal(target_);
      cal.calibrate();
      skytables_.push_back(cal.applytable());
    }
    else {
      String msg = "Calibration type " + calmode_ + " for non-ALMA antenna " + target_->getAntennaName() + " is not supported.";
      os_.origin(LogOrigin("CalibrationManager","calibrate",WHERE));
      os_ << LogIO::SEVERE << msg << LogIO::POST;
      throw AipsError(msg);
    }      
  }
  else if (calmode_ == "OTF" || calmode_ == "OTFRASTER") {
    if (isAlmaAntenna()) {
      os_ << LogIO::DEBUGGING << "ALMA specific position-switch calibration." << LogIO::POST; 
      STCalSkyOtfAlma cal(target_, (calmode_ == "OTFRASTER"));
      if (!options_.empty())
        cal.setOption(options_);
      cal.calibrate();
      skytables_.push_back(cal.applytable());
    }
    else {
      String msg = "Calibration type " + calmode_ + " for non-ALMA antenna " + target_->getAntennaName() + " is not supported.";
      os_.origin(LogOrigin("CalibrationManager","calibrate",WHERE));
      os_ << LogIO::SEVERE << msg << LogIO::POST;
      throw AipsError(msg);
    }      
  }
  else {
    String msg = "Calibration type " + calmode_ + " is not supported.";
    os_.origin(LogOrigin("CalibrationManager","calibrate",WHERE));
    os_ << LogIO::SEVERE << msg << LogIO::POST;
    throw AipsError(msg);
  }
}
コード例 #20
0
ファイル: Astar.cpp プロジェクト: mike83311/test_jasper
int main(int argc,char *argv[]){
	
	int i,j;
	Node node;
	Node *temp;
	Node *now;
	SpecialNode g;
	SpecialNode s;
	NodeList list;
	
	//printf("%c %c",argv[1],argv[2]);
	//printf("%d ",argc);
	s.x = atoi(argv[1]);
    s.y = atoi(argv[2]);

	//g.x = atoi(argv[3]);
	//g.y = atoi(argv[4]); 

	//s.x = 1;
	//s.y = 1;
	g.x = 46;
	g.y = 22;

	if(InputFile(&list, &g, &s) == 0)
	{
		printf("Cannot Open File!");
		exit(1);
	}
	SetStarValue(&list,&s);
	Display(&list);
	delay(4000);
	SetOverValue(&list,&g);
	Display(&list);	
	delay(2000);
	SetValue(&list, &g, &s);
	now = &(list.node[s.x][s.y]);
	now->x = s.x;
	now->y = s.y;
	
	while(1)
	{
		now->openlist = close;
		for(i=now->y-1; i<=now->y+1; i++)
		{
			for(j=now->x-1; j<=now->x+1; j++)
			{
				if(j == now->x && i ==now->y)
					continue;
				if(list.node[j][i].num != '0' && list.node[j][i].openlist == none && list.node[j][i].num != '-' && list.node[j][i].num != '|' && list.node[j][i].num != '3' && list.node[j][i].num != '0' && list.node[j][i].num != '4' && list.node[j][i].num != 'E' && list.node[j][i].num != 'H' && list.node[j][i].num != 'C' && list.node[j][i].num != 'L' && list.node[j][i].num != '6' && list.node[j][i].num != 'I' && list.node[j][i].num != 'u' )
				{
					cal(&node, now , g , i , j);
					Add_to_list(&(list.node[j][i]),node);
					list.node[j][i].link = now;
				}
			}
		}
		
		if(list.node[g.x][g.y].s != 0) break;
		
		temp = now;
		if(choose_next_now_node(&list,&now) == 0)
		{
			now = now->pre;
			
			if(now->x == s.x && now->y == s.y)
			{
				printf("Cannot Arrive destination!\n");
				break;
			}
			continue;
		}
		else
		{
			now->pre = temp;
		}
		
	}
	OutputFile(&list,now);
	Display(&list);
	

	return 0;
}
コード例 #21
0
ファイル: header.c プロジェクト: samb8s/sigproc
main(int argc, char *argv[]) 
{
	FILE *fileptr;
	char filename[80],*telescope,*backend,*datatype,message[80],unit[16];
	int i,j,year,month,day,check,rah,ram,ded,dem;
	double ras,des,frac,tobs;
	char sra[6],sde[6],decsign;
	int raw,uth,utm,uts;
	long long numsamps,datasize,headersize;

	int writeobsdbline;

	fileptr=stdin;
	strcpy(filename,"stdin");
	strcpy(rawdatafile,"stdin");
	pulsarcentric=barycentric=0;

	writeobsdbline=0;

	if (argc>1) {
		print_version(argv[0],argv[1]);
		if (help_required(argv[1])) {
			header_help();
			exit(0);
		} else if (file_exists(argv[1])) {
			strcpy(filename,argv[1]);
			fileptr=open_file(filename,"rb");
		} else if (!file_exists(argv[1]) && (strncmp(argv[1],"-",1) !=0)) {
			sprintf(message,"Data file: %s not found...\n",argv[1]);
			error_message(message);
			exit(1);
		}
	}


	if (!(headersize=read_header(fileptr))) {
		rewind(fileptr);
		if ((raw=typeof_inputdata(fileptr,filename))) {
			data_type=0;
			switch (raw) {
				case 1:
					headersize=32768;
					break;
				case 5:
					headersize=32768;
					break;
				case 3:
					headersize=wapp_header_size+wapp_incfile_length;
					break;
				default:
					break;
			}
		} else {
			error_message("could not read header parameters!");
			exit(1);
		}
	}

	/* attempt to find number of bytes of data and number of samples */
	if (!strings_equal(filename,"stdin")) {
		datasize=sizeof_file(filename)-headersize;
		numsamps=nsamples(filename,headersize,nbits,nifs,nchans);
	} else if (!strings_equal(rawdatafile,"stdin")) {
		datasize=sizeof_file(rawdatafile)-headersize;
		numsamps=nsamples(rawdatafile,headersize,nbits,nifs,nchans);
	} else {
		datasize=numsamps=0;
	}

	telescope=telescope_name(telescope_id);
	backend=backend_name(machine_id);
	datatype=data_category(data_type);

	if (argc>2) {
		check=1;
		i=2;
	} else if ((argc>1) && strings_equal(filename,"stdin")) {
		check=1;
		i=1;
	} else {
		check=0;
	}

	angle_split(src_raj,&rah,&ram,&ras);
	if (ras<10.0) {
		sprintf(sra,"0%.1f",ras);
	} else {
		sprintf(sra,"%.1f",ras);
	}

	angle_split(src_dej,&ded,&dem,&des);
	if (src_dej > 0.0) 
		decsign = '+';
	else 
		decsign = '-';
	if (des<10.0) {
		sprintf(sde,"0%.1f",des);
	} else {
		sprintf(sde,"%.1f",des);
	}

	cal(tstart,&year,&month,&day);

	if (check) {
		/* check command-line parameters */ 
		while (i<argc) {
			if (strings_equal(argv[i],"-telescope")) {
				puts(telescope);
			} else if (strings_equal(argv[i],"-obsdb")) {
				writeobsdbline=1;
			} else if (strings_equal(argv[i],"-machine")) {
				puts(backend);
			} else if (strings_equal(argv[i],"-source_name")) {
				puts(source_name);
			} else if (strings_equal(argv[i],"-scan_number")) {
				puti(scan_number);
			} else if (strings_equal(argv[i],"-datatype")) {
				puts(datatype);
			} else if (strings_equal(argv[i],"-frame")) {
				if (pulsarcentric) 
					puts("pulsarcentric");
				else if (barycentric) 
					puts("barycentric");
				else 
					puts("topocentric");
			} else if (strings_equal(argv[i],"-barycentric")) {
				puti(barycentric);
			} else if (strings_equal(argv[i],"-pulsarcentric")) {
				puti(pulsarcentric);
			} else if (strings_equal(argv[i],"-data_type")) {
				puti(data_type);
			} else if (strings_equal(argv[i],"-headersize")) {
				printf("%d\n",headersize);
			} else if (strings_equal(argv[i],"-datasize")) {
				printf("%lld\n",datasize);
			} else if (strings_equal(argv[i],"-nsamples")) {
				printf("%lld\n",numsamps);
			} else if (strings_equal(argv[i],"-tobs")) {
				printf("%f\n",(double)numsamps*tsamp);
			} else if (strings_equal(argv[i],"-az_start")) {
				printf("%f\n",az_start);
			} else if (strings_equal(argv[i],"-za_start")) {
				printf("%f\n",za_start);
			} else if (strings_equal(argv[i],"-fch1")) {
				printf("%.3f\n",fch1);
			} else if (strings_equal(argv[i],"-bandwidth")) {
				printf("%.3f\n",fabs(foff)*(double)nchans);
			} else if (strings_equal(argv[i],"-fmid")) {
				printf("%.3f\n",fch1+foff*nchans/2);
			} else if (strings_equal(argv[i],"-foff")) {
				printf("%f\n",foff);
			} else if (strings_equal(argv[i],"-refdm")||strings_equal(argv[i],"-dm")) {
				printf("%f\n",refdm);
			} else if (strings_equal(argv[i],"-nchans")) {
				printf("%d\n",nchans);
			} else if (strings_equal(argv[i],"-tstart")) {
				printf("%.12f\n",tstart);
			} else if (strings_equal(argv[i],"-frequencies")) {
				for (j=0; j<nchans; j++) printf("%f\n",frequency_table[j]);
			} else if (strings_equal(argv[i],"-mjd")) {
				printf("%d\n",(int)floor(tstart));
			} else if (strings_equal(argv[i],"-date")) {
				printf("%4d/%02d/%02d\n",year,month,day);
			} else if (strings_equal(argv[i],"-utstart")) {
				frac=tstart-floor(tstart);
				uth=(int) floor(24.0*frac);
				frac-=(double)uth/24.0;
				utm=(int) floor(1440.0*frac);
				frac-=(double)utm/1440.0;
				uts=(int) floor(86400.0*frac);
				printf("%02d:%02d:%02d\n",uth,utm,uts);
			} else if (strings_equal(argv[i],"-tsamp")) {
				printf("%.5f\n",tsamp*1.0e6);
			} else if (strings_equal(argv[i],"-nbits")) {
				printf("%d\n",nbits);
			} else if (strings_equal(argv[i],"-nifs")) {
				printf("%d\n",nifs);
			} else if (strings_equal(argv[i],"-src_raj")) {
				printf("%02d:%02d:%s\n",rah,ram,sra);
			} else if (strings_equal(argv[i],"-src_dej")) {
				printf("%c%02d:%02d:%s\n",decsign,abs(ded),dem,sde);
			}else if (strings_equal(argv[i],"-ra_deg")) {
				printf("%f\n",rah*15+ram/4.0+ras/240.0);
			} else if (strings_equal(argv[i],"-dec_deg")) {
				printf("%c%f\n",decsign,abs(ded)+dem/60.0+des/3600.0);
			} else {
				header_help();
				sprintf(message,"unknown argument (%s) passed to header",argv[i]);
				error_message(message);
			}
			i++;
		}
		/* if we are doing a obs line do this... otherwise continue normaly
		 * MK 2006, for the MM survey bookkeeping.
		 */


		if(writeobsdbline){
			printf("%s ",source_name);
                        printf("%3.3lf %3.3lf ",gal_l,gal_b);
			printf("%s ",filename);
                        printf("%5.3lf %6.6lf ",header_tobs,tstart);
			printf("%6.3lf %6.3lf ",src_raj,src_dej);
                        printf("%5.3lf %3.3lf ",raw_fch1,raw_foff);
			printf("%d %d %5.3lf",nbeams,nchans,tsamp*1000);
			printf("\n");

		}

		exit(0);
	}


	/* no command-line flags were specified - display full output */

	printf("Data file                        : %s\n",filename);
	printf("Header size (bytes)              : %d\n",headersize);
	if (datasize) 
		printf("Data size (bytes)                : %lld\n",datasize);
	if (pulsarcentric) 
		printf("Data type                        : %s (pulsarcentric)\n",datatype);
	else if (barycentric) 
		printf("Data type                        : %s (barycentric)\n",datatype);
	else
		printf("Data type                        : %s (topocentric)\n",datatype);

	printf("Telescope                        : %s\n",telescope);
	printf("Datataking Machine               : %s\n",backend);


	if (!strings_equal(source_name,"")) 
		printf("Source Name                      : %s\n",source_name);
	if (src_raj != 0.0) 
		printf("Source RA (J2000)                : %02d:%02d:%s\n",rah,ram,sra);
	if (src_dej != 0.0)
		printf("Source DEC (J2000)               : %c%02d:%02d:%s\n",
				decsign,abs(ded),dem,sde);
	if ((az_start != 0.0) && (az_start != -1.0))
		printf("Start AZ (deg)                   : %f\n",az_start);
	if ((za_start != 0.0) && (za_start != -1.0))
		printf("Start ZA (deg)                   : %f\n",za_start);

	switch (data_type) {
		case 0:
		case 1:
			if ((fch1==0.0) && (foff==0.0)) {
				printf("Highest frequency channel (MHz)  : %f\n",
						frequency_table[0]);
				printf("Lowest frequency channel  (MHz)  : %f\n",
						frequency_table[nchans-1]);
			} else {
				printf("Frequency of channel 1 (MHz)     : %f\n",fch1);
				printf("Channel bandwidth      (MHz)     : %f\n",foff); 
				printf("Number of channels               : %d\n",nchans);
				printf("Number of beams                  : %d\n",nbeams);
				printf("Beam number                      : %d\n",ibeam); 
			}
			break;
		case 2:
			nchans=1;
			printf("Reference DM (pc/cc)             : %f\n",refdm);
			printf("Reference frequency    (MHz)     : %f\n",fch1);
			break;
		case 3:
			if (refdm > 0.0)
				printf("Reference DM (pc/cc)             : %f\n",refdm);
			printf("Frequency of channel 1 (MHz)     : %f\n",fch1);
			printf("Channel bandwidth      (MHz)     : %f\n",foff); 
			printf("Number of channels               : %d\n",nchans);
			printf("Number of phase bins             : %d\n",nbins);
			printf("Folding period  (s)              : %.12f\n",period);
			break;
		case 6:
			printf("Reference DM (pc/cc)             : %f\n",refdm);
			printf("Frequency of channel 1 (MHz)     : %f\n",fch1);
			printf("Channel bandwidth      (MHz)     : %f\n",foff); 
			printf("Number of channels               : %d\n",nchans);
			break;
	}

	printf("Time stamp of first sample (MJD) : %.12f\n",tstart);
	printf("Gregorian date (YYYY/MM/DD)      : %4d/%02d/%02d\n",year,month,day);

	if (data_type != 3) 
		printf("Sample time (us)                 : %.5f\n",tsamp*1.0e6); 

	if (datasize && data_type != 3) {
		printf("Number of samples                : %lld\n",numsamps);
		tobs=(double)numsamps*tsamp;
		strcpy(unit,"(seconds)   ");
		if (tobs>60.0) {
			tobs/=60.0;
			strcpy(unit,"(minutes)   ");
			if (tobs>60.0) {
				tobs/=60.0;
				strcpy(unit,"(hours)     ");
				if (tobs>24.0) {
					tobs/=24.0;
					strcpy(unit,"(days)      ");
				}
			}
		}
		printf("Observation length %s  : %.1f\n",unit,tobs);
	}
	printf("Number of bits per sample        : %d\n",nbits);
	printf("Number of IFs                    : %d\n",nifs);
	exit(0);
}
コード例 #22
0
int cal(int n,int k)
{
    if(n==1)return ++k;
    else if(n%2==1) return cal(3*n+1,++k);
    else return cal(n/2,++k);
 }
コード例 #23
0
ファイル: DEVSTR.c プロジェクト: anandarao/Codes
int main() {
 
    int t,n,k,i,j,p,flag,res,res1,res2;
    char str[100005];
    scanf("%d",&t);
    while(t--)
    {
        res = 0;
        scanf("%d %d",&n,&k);
        scanf(" %s",str);
        if(k==1)
        {
            i = 0; j = 1;
            res1=0;res2=0;
            for(p = 0; p<n ; p++)
            {
                res1 += abs(str[p]-48-i);
                res2 += abs(str[p]-48-j);
                i = !i;
                j = !j;
            }
            if(res1<res2)
            {
                printf("%d\n",res1);
                i = 0;
            }
            else
            {
                printf("%d\n",res2);
                i = 1;
            }
            for(j=0;j<n;j++)
            {
                printf("%c",i+48);
                i=!i;
            }
            printf("\n");
        }
        else
        {
            for(i=k;i<n;i++)
            {
                flag = 1;
                for(j=i;j>=i-k;j--)
                {
                    if(str[i]!=str[j])
                    {
                        flag = 0;
                        break;
                    }
                }
                if(flag)
                {
                    if(str[i]==str[i+1] || i == n-1)
                    {
                        str[i] = cal(str[i]-48);
                        i += k;
                    }
                    else
                    {
                        str[i-k/2] = cal(str[i-k/2]-48);
                        i += k/2;
                    }
                    res++;
                }
            }
            printf("%d\n",res);
            printf("%s\n",str);
        }
 
 
    }
    return 0;
}
コード例 #24
0
ファイル: 261.c プロジェクト: hamt5821/JudgeGirl
void cal(int a) {
    if (judge) return;
    if (a==cnt) {
        int power=1;
        n1=n2=n3=0;
        for (int i=l1-1; i>=0; i--) {
            if (isdigit(s1[i])) {
                n1+=(s1[i]-'0')*power;
            } else {
                n1+=num[s1[i]]*power;
            }
            power*=10;
        }
        power=1;
        for (int i=l2-1; i>=0; i--) {
            if (isdigit(s2[i])) {
                n2+=(s2[i]-'0')*power;
            } else {
                n2+=num[s2[i]]*power;
            }
            power*=10;
        }
        power=1;
        for (int i=l3-1; i>=0; i--) {
            if (isdigit(s3[i])) {
                n3+=(s3[i]-'0')*power;
            } else {
                n3+=num[s3[i]]*power;
            }
            power*=10;
        }
        if (n1*n2==n3) {
            judge++;
            power=1;
            int k=0;
            while (n1/power) {
                k++;
                power*=10;
            }
            l1-=k;
            while(l1--) printf("0");
            if (n1) printf("%d x ", n1);
            else printf(" x ");
            power=1, k=0;
            while(n2/power) {
                k++;
                power*=10;
            }
            l2-=k;
            while(l2--) printf("0");
            if (n2) printf("%d = ", n2);
            else printf(" = ");
            power=1, k=0;
            while(n3/power) {
                k++;
                power*=10;
            }
            l3-=k;
            while(l3--) printf("0");
            if (n3) printf("%d\n", n3);
            else printf("\n");
        }
        return;
    }
    for (int i=0; i<=9; i++) {
        num[what[a]]=i;
        cal(a+1);
    }
}
コード例 #25
0
static jboolean ICU_initLocaleDataNative(JNIEnv* env, jclass, jstring javaLanguageTag, jobject localeData) {
    ScopedUtfChars languageTag(env, javaLanguageTag);
    if (languageTag.c_str() == NULL) {
        return JNI_FALSE;
    }
    if (languageTag.size() >= ULOC_FULLNAME_CAPACITY) {
        return JNI_FALSE; // ICU has a fixed-length limit.
    }

    ScopedIcuLocale icuLocale(env, javaLanguageTag);
    if (!icuLocale.valid()) {
      return JNI_FALSE;
    }

    // Get the DateTimePatterns.
    UErrorCode status = U_ZERO_ERROR;
    bool foundDateTimePatterns = false;
    for (LocaleNameIterator it(icuLocale.locale().getBaseName(), status); it.HasNext(); it.Up()) {
      if (getDateTimePatterns(env, localeData, it.Get())) {
          foundDateTimePatterns = true;
          break;
      }
    }
    if (!foundDateTimePatterns) {
        ALOGE("Couldn't find ICU DateTimePatterns for %s", languageTag.c_str());
        return JNI_FALSE;
    }

    // Get the "Yesterday", "Today", and "Tomorrow" strings.
    bool foundYesterdayTodayAndTomorrow = false;
    for (LocaleNameIterator it(icuLocale.locale().getBaseName(), status); it.HasNext(); it.Up()) {
      if (getYesterdayTodayAndTomorrow(env, localeData, icuLocale.locale(), it.Get())) {
        foundYesterdayTodayAndTomorrow = true;
        break;
      }
    }
    if (!foundYesterdayTodayAndTomorrow) {
      ALOGE("Couldn't find ICU yesterday/today/tomorrow for %s", languageTag.c_str());
      return JNI_FALSE;
    }

    // Get the narrow "AM" and "PM" strings.
    bool foundAmPmMarkersNarrow = false;
    for (LocaleNameIterator it(icuLocale.locale().getBaseName(), status); it.HasNext(); it.Up()) {
      if (getAmPmMarkersNarrow(env, localeData, it.Get())) {
        foundAmPmMarkersNarrow = true;
        break;
      }
    }
    if (!foundAmPmMarkersNarrow) {
      ALOGE("Couldn't find ICU AmPmMarkersNarrow for %s", languageTag.c_str());
      return JNI_FALSE;
    }

    status = U_ZERO_ERROR;
    UniquePtr<Calendar> cal(Calendar::createInstance(icuLocale.locale(), status));
    if (U_FAILURE(status)) {
        return JNI_FALSE;
    }

    setIntegerField(env, localeData, "firstDayOfWeek", cal->getFirstDayOfWeek());
    setIntegerField(env, localeData, "minimalDaysInFirstWeek", cal->getMinimalDaysInFirstWeek());

    // Get DateFormatSymbols.
    status = U_ZERO_ERROR;
    DateFormatSymbols dateFormatSym(icuLocale.locale(), status);
    if (U_FAILURE(status)) {
        return JNI_FALSE;
    }

    // Get AM/PM and BC/AD.
    int32_t count = 0;
    const UnicodeString* amPmStrs = dateFormatSym.getAmPmStrings(count);
    setStringArrayField(env, localeData, "amPm", amPmStrs, count);
    const UnicodeString* erasStrs = dateFormatSym.getEras(count);
    setStringArrayField(env, localeData, "eras", erasStrs, count);

    const UnicodeString* longMonthNames =
       dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longMonthNames", longMonthNames, count);
    const UnicodeString* shortMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortMonthNames", shortMonthNames, count);
    const UnicodeString* tinyMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::FORMAT, DateFormatSymbols::NARROW);
    setStringArrayField(env, localeData, "tinyMonthNames", tinyMonthNames, count);
    const UnicodeString* longWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longWeekdayNames", longWeekdayNames, count);
    const UnicodeString* shortWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortWeekdayNames", shortWeekdayNames, count);
    const UnicodeString* tinyWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::FORMAT, DateFormatSymbols::NARROW);
    setStringArrayField(env, localeData, "tinyWeekdayNames", tinyWeekdayNames, count);

    const UnicodeString* longStandAloneMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longStandAloneMonthNames", longStandAloneMonthNames, count);
    const UnicodeString* shortStandAloneMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortStandAloneMonthNames", shortStandAloneMonthNames, count);
    const UnicodeString* tinyStandAloneMonthNames =
        dateFormatSym.getMonths(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::NARROW);
    setStringArrayField(env, localeData, "tinyStandAloneMonthNames", tinyStandAloneMonthNames, count);
    const UnicodeString* longStandAloneWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::WIDE);
    setStringArrayField(env, localeData, "longStandAloneWeekdayNames", longStandAloneWeekdayNames, count);
    const UnicodeString* shortStandAloneWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::ABBREVIATED);
    setStringArrayField(env, localeData, "shortStandAloneWeekdayNames", shortStandAloneWeekdayNames, count);
    const UnicodeString* tinyStandAloneWeekdayNames =
        dateFormatSym.getWeekdays(count, DateFormatSymbols::STANDALONE, DateFormatSymbols::NARROW);
    setStringArrayField(env, localeData, "tinyStandAloneWeekdayNames", tinyStandAloneWeekdayNames, count);

    status = U_ZERO_ERROR;

    // For numberPatterns and symbols.
    setNumberPatterns(env, localeData, icuLocale.locale());
    setDecimalFormatSymbolsData(env, localeData, icuLocale.locale());

    jstring countryCode = env->NewStringUTF(icuLocale.locale().getCountry());
    jstring internationalCurrencySymbol = ICU_getCurrencyCode(env, NULL, countryCode);
    env->DeleteLocalRef(countryCode);
    countryCode = NULL;

    jstring currencySymbol = NULL;
    if (internationalCurrencySymbol != NULL) {
        currencySymbol = ICU_getCurrencySymbol(env, NULL, javaLanguageTag, internationalCurrencySymbol);
    } else {
        internationalCurrencySymbol = env->NewStringUTF("XXX");
    }
    if (currencySymbol == NULL) {
        // This is the UTF-8 encoding of U+00A4 (CURRENCY SIGN).
        currencySymbol = env->NewStringUTF("\xc2\xa4");
    }
    setStringField(env, localeData, "currencySymbol", currencySymbol);
    setStringField(env, localeData, "internationalCurrencySymbol", internationalCurrencySymbol);

    return JNI_TRUE;
}
コード例 #26
0
ファイル: 1655.cpp プロジェクト: HaochenLiu/POJ-snuc
int main()
{
    int t,i,j,a,b,max;
	struct edge *p,*q;
	scanf("%d",&t);
	for (i=0;i<t;i++)
	{
		scanf("%d",&n);
		for (j=1;j<=n;j++)
		{
			Node[j].num=0;
			Node[j].next=NULL;
		}
		for (j=n-1;j>0;j--)
		{
			scanf("%d%d",&a,&b);
			p=(struct edge *)malloc(sizeof(struct edge));
			p->v=b;
			p->next=NULL;
			if (Node[a].num==0)
				Node[a].next=p;
			else{
				q=Node[a].next;
				while (q->next!=NULL)
					q=q->next;
				q->next=p;
			}
			Node[a].num++;
			p=(struct edge *)malloc(sizeof(struct edge));
			p->v=a;
			p->next=NULL;
			if (Node[b].num==0)
				Node[b].next=p;
			else{
				q=Node[b].next;
				while (q->next!=NULL)
					q=q->next;
				q->next=p;
			}
			Node[b].num++;
		}
		cal(0,1);
		p=Node[1].next;
		while (p!=NULL)
		{
			q=p;
			p=p->next;
			free(q);
		}
		for (j=2,max=1;j<=n;j++)
		{
			if (balance[j]<balance[max])
				max=j;
			p=Node[j].next;
			while (p!=NULL)
			{
				q=p;
				p=p->next;
				free(q);
			}
		}
		printf("%d %d\n",max,balance[max]);
	}
	return 0;
}
コード例 #27
0
ファイル: vm2tac.c プロジェクト: tctsigemura/C--
// まず、スタックからシフトするビット数、シフトされるデータの順で取り出す。
// 次に、左シフトした結果をスタックに積む
void vmShl() {
  cal("SHLA");                                  // 左右逆順なしのコード生成
}
コード例 #28
0
ii cal(int i,int j,int k){
	
	ii ret=0;
	if(k<0) return 1;
    if(i<0&&j<0) return 0;
	if(dp[i+1][j+1][k+1]!=-1) return dp[i+1][j+1][k+1];
	if(i<0&&j>=0){
		if(s2[j]==s3[k]){
			ret=cal(i,j-1,k-1);
		}
		ret+=cal(i,j-1,k); ret%=mod;
		return dp[i+1][j+1][k+1]=ret;
	}
	if(j<0&&i>=0){		
		if(s1[i]==s3[k]){
			ret=cal(i-1,j,k-1);
		}
		ret+=cal(i-1,j,k); ret%=mod;
		return dp[i+1][j+1][k+1]=ret;
	}
	
	if(dp[i+1][j+1][k+1]!=-1) return dp[i+1][j+1][k+1];

	

	if(s1[i]==s3[k]){
		ret+=cal(i-1,j,k-1);
		ret%=mod;
	}
	
	if(s2[j]==s3[k]){
		ret+=cal(i,j-1,k-1);
		ret%=mod;
	}

 // if(s3[j]!=s3[k])
        ret+=cal(i-1,j,k);
	ret%=mod;
		
//	if(s1[j]!=s3[k])
        ret+=cal(i,j-1,k);
	ret%=mod;

	if(s1[i]==s3[k]){
	    ret-=(cal(i-1,j-1,k-1)); if(ret<0) ret+=mod;
    	    ret%=mod;
	}
	if(s2[j]==s3[k]){
		ret-=cal(i-1,j-1,k-1); if(ret<0) ret+=mod;
		ret%=mod;
	}	

   	ret-=cal(i-1,j-1,k);  if(ret<0) ret+=mod;
        ret%=mod;

	return dp[i+1][j+1][k+1]=ret;

}
コード例 #29
0
int
main(int argc, char *argv[])
{
	int	f_dayAfter = 0;		/* days after current date */
	int	f_dayBefore = 0;	/* days before current date */
	int	Friday = 5;		/* day before weekend */

	int ch;
	struct tm tp1, tp2;

	(void)setlocale(LC_ALL, "");

	while ((ch = getopt(argc, argv, "-A:aB:D:dF:f:l:t:U:W:?")) != -1)
		switch (ch) {
		case '-':		/* backward contemptible */
		case 'a':
			if (getuid()) {
				errno = EPERM;
				err(1, NULL);
			}
			doall = 1;
			break;

		case 'W': /* we don't need no steenking Fridays */
			Friday = -1;
			/* FALLTHROUGH */

		case 'A': /* days after current date */
			f_dayAfter = atoi(optarg);
			break;

		case 'B': /* days before current date */
			f_dayBefore = atoi(optarg);
			break;

		case 'D': /* debug output of sun and moon info */
			DEBUG = optarg;
			break;

		case 'd': /* debug output of current date */
			debug = 1;
			break;

		case 'F': /* Change the time: When does weekend start? */
			Friday = atoi(optarg);
			break;

		case 'f': /* other calendar file */
			calendarFile = optarg;
			break;

		case 'l': /* Change longitudal position */
			EastLongitude = strtol(optarg, NULL, 10);
			break;

		case 't': /* other date, for tests */
			f_time = Mktime(optarg);
			break;

		case 'U': /* Change UTC offset */
			UTCOffset = strtod(optarg, NULL);
			break;

		case '?':
		default:
			usage();
		}

	argc -= optind;
	argv += optind;

	if (argc)
		usage();

	/* use current time */
	if (f_time <= 0)
		(void)time(&f_time);

	/* if not set, determine where I could be */
	{
		if (UTCOffset == UTCOFFSET_NOTSET &&
		    EastLongitude == LONGITUDE_NOTSET) {
			/* Calculate on difference between here and UTC */
			time_t t;
			struct tm tm;
			long utcoffset, hh, mm, ss;
			double uo;

			time(&t);
			localtime_r(&t, &tm);
			utcoffset = tm.tm_gmtoff;
			/* seconds -> hh:mm:ss */
			hh = utcoffset / SECSPERHOUR;
			utcoffset %= SECSPERHOUR;
			mm = utcoffset / SECSPERMINUTE;
			utcoffset %= SECSPERMINUTE;
			ss = utcoffset;

			/* hh:mm:ss -> hh.mmss */
			uo = mm + (100.0 * (ss / 60.0));
			uo /=  60.0 / 100.0;
			uo = hh + uo / 100;

			UTCOffset = uo;
			EastLongitude = UTCOffset * 15;
		} else if (UTCOffset == UTCOFFSET_NOTSET) {
			/* Base on information given */
			UTCOffset = EastLongitude / 15;
		} else if (EastLongitude == LONGITUDE_NOTSET) {
			/* Base on information given */
			EastLongitude = UTCOffset * 15;
		}
	}

	settimes(f_time, f_dayBefore, f_dayAfter, Friday, &tp1, &tp2);
	generatedates(&tp1, &tp2);

	/*
	 * FROM now on, we are working in UTC.
	 * This will only affect moon and sun related events anyway.
	 */
	if (setenv("TZ", "UTC", 1) != 0)
		errx(1, "setenv: %s", strerror(errno));
	tzset();

	if (debug)
		dumpdates();

	if (DEBUG != NULL) {
		dodebug(DEBUG);
		exit(0);
	}

	if (doall)
		while ((pw = getpwent()) != NULL) {
			(void)setegid(pw->pw_gid);
			(void)initgroups(pw->pw_name, pw->pw_gid);
			(void)seteuid(pw->pw_uid);
			if (!chdir(pw->pw_dir))
				cal();
			(void)seteuid(0);
		}
	else
		cal();
	exit(0);
}
コード例 #30
0
void TodoPlugin::processDropEvent( QDropEvent *event )
{
  const QMimeData *md = event->mimeData();

  if ( KABC::VCardDrag::canDecode( md ) ) {
    KABC::Addressee::List contacts;

    KABC::VCardDrag::fromMimeData( md, contacts );

    KABC::Addressee::List::Iterator it;

    QStringList attendees;
    for ( it = contacts.begin(); it != contacts.end(); ++it ) {
      QString email = (*it).fullEmail();
      if ( email.isEmpty() ) {
        attendees.append( (*it).realName() + "<>" );
      } else {
        attendees.append( email );
      }
    }

    interface()->openTodoEditor( i18nc( "@item", "Meeting" ),
                                 QString(), QStringList(), attendees );
    return;
  }

  if ( KCalUtils::ICalDrag::canDecode( event->mimeData() ) ) {
    KCalCore::MemoryCalendar::Ptr cal( new KCalCore::MemoryCalendar( KSystemTimeZones::local() ) );
    if ( KCalUtils::ICalDrag::fromMimeData( event->mimeData(), cal ) ) {
      KCalCore::Incidence::List incidences = cal->incidences();
      Q_ASSERT( incidences.count() );
      if ( !incidences.isEmpty() ) {
        event->accept();
        KCalCore::Incidence::Ptr i = incidences.first();
        QString summary;
        if ( i->type() == KCalCore::Incidence::TypeJournal ) {
          summary = i18nc( "@item", "Note: %1", i->summary() );
        } else {
          summary = i->summary();
        }
        interface()->openTodoEditor( summary, i->description(), QStringList() );
        return;
      }
      // else fall through to text decoding
    }
  }

  if ( md->hasText() ) {
    QString text = md->text();
    interface()->openTodoEditor( text );
    return;
  }

  if ( KPIM::MailList::canDecode( md ) ) {
    KPIM::MailList mails = KPIM::MailList::fromMimeData( md );
    event->accept();
    if ( mails.count() != 1 ) {
      KMessageBox::sorry(
        core(),
        i18nc( "@info", "Dropping multiple mails is not supported." ) );
    } else {
      KPIM::MailSummary mail = mails.first();
      QString txt = i18nc( "@item", "From: %1\nTo: %2\nSubject: %3",
                           mail.from(), mail.to(), mail.subject() );
      QString uri = QLatin1String( "kmail:" ) +
                    QString::number( mail.serialNumber() ) + '/' +
                    mail.messageId();
      KTemporaryFile tf;
      tf.setAutoRemove( true );
      tf.write( event->encodedData( "message/rfc822" ) );
      interface()->openTodoEditor(
        i18nc( "@item", "Mail: %1", mail.subject() ),
        txt, uri, tf.fileName(), QStringList(), "message/rfc822" );
      tf.close();
    }
    return;
  }

  kWarning() << QString( "Cannot handle drop events of type '%1'." ).arg( event->format() );
}