Example #1
0
static CPLErr CompressLERC2(buf_mgr &dst, buf_mgr &src, const ILImage &img, double precision)
{
    int w = img.pagesize.x;
    int h = img.pagesize.y;
    // So we build a bitmask to pass a pointer to bytes, which gets converted to a bitmask?
    BitMask2 bitMask;
    int ndv_count = 0;
    if (img.hasNoData) { // Only build a bitmask if no data value is defined
	switch (img.dt) {

#define MASK(T) ndv_count = MaskFill(bitMask, (T *)(src.buffer), img)

	case GDT_Byte:		MASK(GByte);	break;
	case GDT_UInt16:	MASK(GUInt16);	break;
	case GDT_Int16:		MASK(GInt16);	break;
	case GDT_Int32:		MASK(GInt32);	break;
	case GDT_UInt32:	MASK(GUInt32);	break;
	case GDT_Float32:	MASK(float);	break;
	case GDT_Float64:	MASK(double);	break;
        default:                CPLAssert(FALSE); break;

#undef MASK
	}
    }
    // Set bitmask if it has some ndvs
    Lerc2 lerc2(w, h, (ndv_count == 0) ? NULL : bitMask.Bits());
    bool success = false;
    Byte *ptr = (Byte *)dst.buffer;

    long sz = 0;
    switch (img.dt) {

#define ENCODE(T) if (true) { \
    sz = lerc2.ComputeNumBytesNeededToWrite((T *)(src.buffer), precision, ndv_count != 0);\
    success = lerc2.Encode((T *)(src.buffer), &ptr);\
    }

    case GDT_Byte:	ENCODE(GByte);	    break;
    case GDT_UInt16:	ENCODE(GUInt16);    break;
    case GDT_Int16:	ENCODE(GInt16);	    break;
    case GDT_Int32:	ENCODE(GInt32);	    break;
    case GDT_UInt32:	ENCODE(GUInt32);    break;
    case GDT_Float32:	ENCODE(float);	    break;
    case GDT_Float64:	ENCODE(double);	    break;
    default:            CPLAssert(FALSE); break;

#undef ENCODE
    }

    // write changes the value of the pointer, we can find the size by testing how far it moved
    dst.size = (char *)ptr - dst.buffer;
    if (!success || sz != static_cast<long>(dst.size)) {
	CPLError(CE_Failure, CPLE_AppDefined, "MRF: Error during LERC2 compression");
	return CE_Failure;
    }
    CPLDebug("MRF_LERC", "LERC2 Compressed to %d\n", (int)sz);
    return CE_None;
}
Example #2
0
/*
 *	----- standard_inquiry - Issue a standard SCSI inquiry command.
 *	Given a robot or tape drive device data, retrieve
 *	and display standard inquiry data.
 */
int				/* 0 is success. */
standard_inquiry(
	devdata_t *devdata)	/* device data. */
{
#define	STD_INQ_LEN 0xff
	char cdb [] = {0x12, 0, 0, 0, (char)STD_INQ_LEN, 0};
	char data [STD_INQ_LEN];
	int return_code, i, length = 0, datalen = STD_INQ_LEN;

	if ((return_code = issue_cmd(devdata, cdb, 6, data, &datalen,
	    DATAIN, REQUIRED)) != 0)
		return (return_code);

	memcpy(devdata->vendor, &data[8], 8);
	memcpy(devdata->product, &data[16], 16);

	printf("Standard Inquiry\n");
	printf("----------------\n");

	if (datalen >= 1)
		devdata->devtype = data [0] & 0x1f;
	printf("device-type: %x\n", devdata->devtype);

	printf("version: %02x\n", data [2] & 0xff);

	length = (datalen >= 16 ? 8 : 0);

	printf("vendor: ");
	for (i = 0; i < length; i++) {
		printf("%s", ENCODE(devdata->encode, DPNC(data[i+8])));
	}
	printf("\n");

	length = (datalen >= 32 ? 16 : 0);
	printf("product: ");
	for (i = 0; i < length; i++) {
		printf("%s", ENCODE(devdata->encode, DPNC(data[i+16])));
	}
	printf("\n");

	length = (datalen >= 35 ? 4 : 0);
	printf("revision: ");
	for (i = 0; i < length; i++) {
		printf("%s", ENCODE(devdata->encode, DPNC(data[i+32])));
	}
	printf("\n");

	printf("multiport: %d\n", (data[6] >> 4) & 1);

	printf("\n");
	return (0);
}
Example #3
0
/*
 *	----- usn_inquiry - Unit serial number inquiry page 80.
 *	Given a robot or tape drive device data, retrieve
 *	and display unit serial number data.
 */
int				/* 0 is success. */
usn_inquiry(
	devdata_t *devdata)	/* device data. */
{
#define	USN_INQ_LEN 0xff
	char cdb [] = {0x12, 1, (char)0x80, 0, (char)USN_INQ_LEN, 0};
	char data [USN_INQ_LEN];
	int return_code, i, length = 0, datalen = USN_INQ_LEN;

	/*
	 * scsi standard says usn page is required, however since some
	 * devices like optical don't have usn pages make it optional.
	 */
	if ((return_code = issue_cmd(devdata, cdb, 6, data, &datalen,
	    DATAIN, OPTIONAL)) != 0)
		return (return_code);

	if (datalen >= 4)
		length = data [3];

	printf("Unit Serial Number Inquiry\n");
	printf("--------------------------\n");

	printf("unit-serial-number: ");
	for (i = 0; i < length; i++) {
		printf("%s", ENCODE(devdata->encode, DPNC(data[i+4])));
	}
	printf("\n");

	printf("\n");
	return (0);
}
int main()
{
	PlaySoundA("skyrim.wav", NULL, SND_ASYNC | SND_LOOP | SND_FILENAME);//Play Music 
	string choice;//choice
	while (1)//infinite loop
	{
		cout << "Team RAN (Ravi :) , Ajay :'( , Neha <3)" << endl << endl;
		cout << "Song: Elder Scrolls V: Skyrim Theme" << endl << endl;
		cout << "Would you like to encode or decode a phrase?" << endl << "'E' for Encoding" << endl << "'D' for Decoding" << endl << "'QQ' to Quit" << endl;
		getline(cin, choice);//get whole line
		if (choice == "E" || choice == "e")//call ENCODE
			ENCODE();
		else if (choice == "D" || choice == "d")//call DECODE
			DECODE();
		else if (choice == "QQ" || choice == "qq" || choice == "Qq" || choice == "qQ")//QUIT
		{
			cout << "Thank you for using this program!" << endl;
			system("pause");
			break;
		}
		else
			cout << "INVALID RESPONSE" << endl << endl;//if none of the others
		system("pause");
		system("CLS");//clears screen
	}
	return 0;
}
Example #5
0
void MQencoder::ENCODER()
{
    INITENC();

    //loop until the end of bitstream
    for(unsigned long int i=0;;i++)
    {
    //read CX, D : use just one CX, read D from?
    D = input->GetBitAt(i);
    //CX = CX
    if(D == 2)
        break;
   
#ifdef QMDEBUG
    std::cout 
            << std::setw(4) << std::setfill(' ') << i+1
            << " D: " << (int)D 
            << " I: " << std::setw(2) << std::setfill(' ') <<(int)CX.I
            << " MPS: " << (int)CX.MPS
            << " Qe: " << std::setw(4) << std::setfill(' ') << std::hex << Qe[CX.I] << std::dec
            << " A: " << std::setw(4) << std::setfill(' ') << std::hex << A << std::dec
            << " C: " << std::setw(8) << std::setfill(' ') << std::hex << C << std::dec
            << " CT: " << std::setw(2) << std::setfill(' ') << CT 
            << " B: " << std::setw(2) << std::setfill(' ') << std::hex << (int)*BP << std::dec
            ;
#endif
    
    ENCODE();
    
    }    //if not finished goto read CX, D

    FLUSH();
    output->SetLength(codedBytes*8);
}
Example #6
0
void convert_scr7 (image *img) {
  image *temp;
  int i,j;
  histogram hist[256];

  temp=(image *) malloc (sizeof (image));
  temp->x=img->x;
  temp->y=img->y;
  temp->buffer=(unsigned char *) malloc (img->x*img->y);

  for (i=0; i<256; i++) {
    hist[i].value=0;
    hist[i].index=i;
  }
  
  for (j=0; j<img->y; j++)
    for (i=0; i<img->x; i++)
      hist[ENCODE(img,i,j)].value++;

  qsort (hist,256,sizeof (histogram),sort_histogram);
  
  for (j=0; j<temp->y; j++)
    for (i=0; i<temp->x; i++)
      PIXEL8(temp,i,j)=
        match_color(PIXEL(img,i,j,R),PIXEL(img,i,j,G),PIXEL(img,i,j,B),hist);

  custom_blit (temp);
  show_pal (0,hist);
}
Example #7
0
/**************************************************************************
*
* FUNCTION NAME: CheckPassword
*
* DESCRIPTION:
*		Encrypts the name and compares the resulting ID against the supplied one
*
* INPUT PARAMETERS:
*     PCHAR szName and szID
*
* OUTPUT PARAMETERS:
*     TRUE if password is good.
*
**************************************************************************/
BOOL CheckPassword (PCHAR szRegName, PCHAR szID)
{
	INT  i, j, iLen;
	CHAR c;
	CHAR szName[REGISTER_NAME_LEN];

	/*
	** Get the name into an upper case string - removing spaces and only
	** using every other character 
	*/
	for (i = 0, j = 0;  i < strlen (szRegName);  i += 2)
	{
	   if (szRegName[i] != '\"' && szRegName[i] != ' ' && szRegName[i] != '\t')
		{
			szName[j++] = toupper (szRegName[i]);
		}
	}
	szName[j] = '\0';

	/* Append AQUA to the name */
	strcat (szName, "AQUA");
	iLen = strlen (szName);

	/* Now switch the characters, encoding as we go along */
	for (i = 0;  i < iLen - 1;  i += 2)
	{
		c = szName[i];
		szName[i] = ENCODE (szName[i+1]);
		szName[i+1] = ENCODE (c);
	}

	/* If there are an odd number of characters then encode the last char */
	if (iLen & 1)
	{
		szName[iLen - 1] = ENCODE (szName[iLen - 1]);
	}

	/* Now make the supplied ID uppercase */
	for (i = 0;  i < strlen (szID);  i++)
	{
		szID[i] = toupper (szID[i]);
	}

	/* If the two are now the same the password is OK! */
	return ((strcmp (szID, szName) == 0) ? TRUE : FALSE);
}
Example #8
0
static void
clip_triangle (GL_primitive_list *pl, GLcontext *g, GL_float plane[4],
	       GL_primitive *p, int bits)
{
    GL_procvert *v0 = p->verts[0];
    GL_procvert *v1 = p->verts[1];
    GL_procvert *v2 = p->verts[2];
    GL_procvert *v3;
    GL_procvert *v4;

    switch (bits) {
    case ENCODE(OUT, OUT, OUT):
	__glcore_destroy_primitive(p);
	break;
    case ENCODE(OUT, OUT, IN):
	v3 = intersect(pl, g, v1, v2, v0, plane);
	v4 = intersect(pl, g, v0, v2, v0, plane);
	__glcore_set_and_add_primitive(pl, p, 3, v3, v2, v4);
	break;
    case ENCODE(OUT, IN, OUT):
	v3 = intersect(pl, g, v0, v1, v0, plane);
	v4 = intersect(pl, g, v2, v1, v0, plane);
	__glcore_set_and_add_primitive(pl, p, 3, v3, v1, v4);
	break;
    case ENCODE(OUT, IN, IN):
	v3 = intersect(pl, g, v0, v1, v0, plane);
	v4 = intersect(pl, g, v0, v2, v0, plane);
	__glcore_set_and_add_primitive(pl, p, 3, v3, v1, v2);
	__glcore_add_new_primitive(pl, 3, v3, v2, v4);
	break;
    case ENCODE(IN, OUT, OUT):
	v3 = intersect(pl, g, v1, v0, v0, plane);
	v4 = intersect(pl, g, v2, v0, v0, plane);
	__glcore_set_and_add_primitive(pl, p, 3, v0, v3, v4);
	break;
    case ENCODE(IN, OUT, IN):
	v3 = intersect(pl, g, v1, v0, v0, plane);
	v4 = intersect(pl, g, v1, v2, v0, plane);
	__glcore_set_and_add_primitive(pl, p, 3, v0, v3, v4);
	__glcore_add_new_primitive(pl, 3, v0, v4, v2);
	break;
    case ENCODE(IN, IN, OUT):
	v3 = intersect(pl, g, v2, v1, v0, plane);
	v4 = intersect(pl, g, v2, v0, v0, plane);
	__glcore_set_and_add_primitive(pl, p, 3, v0, v1, v3);
	__glcore_add_new_primitive(pl, 3, v0, v3, v4);
	break;
    case ENCODE(IN, IN, IN):
	__glcore_add_primitive(pl, p);
	break;
    }
}
Example #9
0
static void backup_to_relexing_point(token_iterator&iterator, i7_codepoint first_codepoint_of_altered_text, bool have_already_effectively_backed_up_once) {
  static const i7_string*SINGLE_QUOTE = &vocabulary.acquire(ENCODE("'"));
  // First we deal with anything that might combine to form a documentation break; this is the most complicated.
  if (first_codepoint_of_altered_text == ' ' || first_codepoint_of_altered_text == '-' || first_codepoint_of_altered_text == '\n' || is_i7_lexical_delimiter_letter(first_codepoint_of_altered_text)) {
    backup_to_look_for_documentation_break(iterator, first_codepoint_of_altered_text, have_already_effectively_backed_up_once);
    return;
  }
  // Then we dispatch other combining punctuation.
  switch (first_codepoint_of_altered_text) {
  case '+':  // We need to decide between + and (+.
  case ')':  // We need to decide between ) and -) and +).
    // Backup once to look for a preceding parenthesis, hyphen, or plus.
    if (!have_already_effectively_backed_up_once) {
      --iterator;
    }
    return;
  case '\'':
    // Single quotes do not combine, but, because of the I6 parsing rule for a
    // single quote character literal (written '''), they do change lexical
    // effect depending on the number of immediately preceding occurrences.  So
    // we need to backup accoss any earlier single quotes to make sure that we
    // count correctly.
    //
    // The have_already_effectively_backed_up_once flag means that we began in
    // the middle of a multicodepoint token, which means that there aren't any
    // preceding single quotes because they're always lexed into one-codepoint
    // tokens.  Thereore, we only look behind when the flag is cleared.
    if (!have_already_effectively_backed_up_once) {
      while (iterator.can_decrement()) {
	token_iterator probe = iterator;
	if ((--probe)->get_text() != SINGLE_QUOTE) {
	  break;
	}
	--iterator;
      }
    }
    return;
  }
  // And everything else can combine at most once, unless it's punctuation, in which case it can't combine at all.
  if (!have_already_effectively_backed_up_once && !is_i7_punctuation(first_codepoint_of_altered_text)) {
    --iterator;
  }
}
Example #10
0
void GridAnt::move()
{
    DIRECTION dir = chooseGrid();
    switch(dir)
    {
        case UP:cur_x--;distance += PIX;break;
        case DOWN:cur_x++;distance += PIX;break;
        case LEFT:cur_y--;distance += PIX;break;
        case RIGHT:cur_y++;distance += PIX;break;
        case LEFT_UP:cur_x--;cur_y--;distance += ANG_PIX;break;
        case LEFT_DOWN:cur_y--;cur_x++;distance += ANG_PIX;break;
        case RIGHT_UP:cur_y++;cur_x--;distance += ANG_PIX;break;
        case RIGHT_DOWN:cur_y++;cur_x++;distance += ANG_PIX;break;
        case NOROAD:return;
        case GOAL:distance += sqrt(pow(end_x - cur_x,2) + pow(end_y - cur_y,2))*100.0;cur_x = end_x;cur_y = end_y;break;
    }
    cur_city = ENCODE(cur_x,cur_y);
    num_city++;
    travel[cur_x][cur_y] = 1;
    road[num_city] = cur_city;
}
Example #11
0
/**	对词表进行加密
 *	加密方法,循环右移7位,异或aa55
 */
void encode_word_list(char *word_list, int word_list_pos)
{
	int index = 0;
	unsigned short x;

	return;

	while(index < word_list_pos)
	{
		if (!word_list[index])
		{
			index++;
			continue;
		}

		x = *(unsigned short*)&word_list[index];
		x = ENCODE(x);
		*(unsigned short*)&word_list[index] = x;
		index += 2;
	}
}
Example #12
0
void GridAnt::init(int x_start,int y_start,int x_end,int y_end)
{
    for (int i = 0; i < N_GRID; ++i)
    {
        for (int j = 0; j < N_GRID; ++j)
        {
            travel[i][j] = 0;           //0代表可以走1代表不可以走
        }
    }
    memset(road,0,sizeof(road));
    start_x = cur_x = x_start;
    start_y = cur_y = y_start;
    end_x = x_end;
    end_y = y_end;
    cur_city = ENCODE(cur_x,cur_y);
    distance = 0.0;
    direction = RIGHT;
    travel[cur_x][cur_y] = 1;
    num_city = 0;
    road[num_city] = cur_city;
}
Example #13
0
/*
 *	----- parse_identifier_descriptor - Parse identification descriptor.
 *	Given inquiry or read element status identification descriptor,
 *	display vital information.
 */
int				/* 0 is success. */
parse_identifier_descriptor(
	devdata_t *devdata,	/* device data. */
	char *desc,		/* binary description data. */
	int desclen,		/* binary description data length. */
	int *usedlen)		/* bytes processed. */
{
	int length = 0, i;
	int code_set, id_type;
	const int binary_values = 1,
	    ascii_graphic_codes = 2;

	if (desclen < 3)
		return (1);

	code_set = desc [0] & 0xf;
	printf("code-set: %x\n", code_set);

	printf("association: %x\n", (desc [2] >> 4) & 0x3);

	id_type = desc [1] & 0xf;
	printf("id-type: %x\n", id_type);

	if (desclen >= 4)
		length = desc [3];

	printf("id: ");
	for (i = 0; i < length && i < desclen; i++) {
		if (code_set == binary_values)
			printf("%02x", (unsigned char)desc[i+4]);
		else if (code_set == ascii_graphic_codes)
			printf("%s", ENCODE(devdata->encode, DPNC(desc[i+4])));
	}
	printf("\n");

	*usedlen = (i > 0 ? i + 4 : 0);

	return (0);
}
Example #14
0
int
rsstool_write_xml (st_rsstool_t *rt)
{
  st_rss_t rss;
  int i = 0;
  st_hash_t *dl_url_h = NULL;
  st_hash_t *url_h = NULL;
  st_hash_t *title_h = NULL;
  int items = rsstool_get_item_count (rt);
//#define ENCODE(s) s
#define ENCODE(s) base64_enc(s,0)
//#define ENCODE(s) str_escape_xml(s)

  memset (&rss, 0, sizeof (st_rss_t));

  fputs ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", rsstool.output_file);

  fputs ("<!--\n"
         "RSStool - read, parse, merge and write RSS and Atom feeds\n"
         "http://rsstool.berlios.de\n"
         "-->\n", rsstool.output_file);

  fputs ("<!--\n"
         "format:\n"
         "item[]\n"
         "  dl_url           \n"
         "  dl_url_md5\n"
         "  dl_url_crc32\n"
         "  dl_date\n"
         "  user             (base64 encoded)\n"
         "  site             (base64 encoded)\n"
         "  url              \n"
         "  url_md5\n"
         "  url_crc32\n"
         "  date\n"
         "  title            used by searches for related items (base64 encoded)\n"
         "  title_md5\n"
         "  title_crc32\n"
         "  desc             description (base64 encoded)\n"
         "  media_keywords   default: keywords from title and description\n"
         "  media_duration\n"
         "  media_thumbnail  path (base64 encoded)\n"
//         "  media_image      path (base64 encoded)\n"
//         "  event_start      default: date\n"
//         "  event_end        default: event_start + media_duration\n"
         "-->\n", rsstool.output_file);

  fputs ("<rsstool version=\"" RSSTOOL_VERSION_S "\">\n", rsstool.output_file);

  for (i = 0; i < items && i < RSSMAXITEM; i++)
//  for (i = 0; i < items; i++)
    {
      dl_url_h = hash_open (HASH_MD5|HASH_CRC32);
      url_h = hash_open (HASH_MD5|HASH_CRC32);
      title_h = hash_open (HASH_MD5|HASH_CRC32);

      dl_url_h = hash_update (dl_url_h, (const unsigned char *) rt->item[i]->feed_url, strlen (rt->item[i]->feed_url));
      url_h = hash_update (url_h, (const unsigned char *) rt->item[i]->url, strlen (rt->item[i]->url));
      title_h = hash_update (title_h, (const unsigned char *) rt->item[i]->title, strlen (rt->item[i]->title));

      fprintf (rsstool.output_file,
               "  <item>\n"
               "    <dl_url>%s</dl_url>\n"
               "    <dl_url_md5>%s</dl_url_md5>\n"
               "    <dl_url_crc32>%u</dl_url_crc32>\n"
               "    <dl_date>%ld</dl_date>\n"
               "    <user>%s</user>\n"
               "    <site>%s</site>\n"
               "    <url>%s</url>\n"
               "    <url_md5>%s</url_md5>\n"
               "    <url_crc32>%u</url_crc32>\n"
               "    <date>%ld</date>\n"
               "    <title>%s</title>\n"
               "    <title_md5>%s</title_md5>\n"
               "    <title_crc32>%u</title_crc32>\n"
               "    <desc>%s</desc>\n"
               "    <media_keywords>%s</media_keywords>\n"
               "    <media_duration>%d</media_duration>\n"
               "    <media_thumbnail>%s</media_thumbnail>\n"
//               "    <media_image>%s</media_image>\n"
//               "    <event_start>%u</event_start>\n"
//               "    <event_end>%u</event_end>\n"
               "  </item>\n",
        str_escape_xml (rt->item[i]->feed_url),
        hash_get_s (dl_url_h, HASH_MD5),
        hash_get_crc32 (dl_url_h),
        time (0),
        ENCODE (rt->item[i]->user),
        ENCODE (rt->item[i]->site),
        str_escape_xml (rt->item[i]->url),
        hash_get_s (url_h, HASH_MD5),
        hash_get_crc32 (url_h),
        rt->item[i]->date,
        ENCODE (rt->item[i]->title),
        hash_get_s (title_h, HASH_MD5),
        hash_get_crc32 (title_h),
        ENCODE (rt->item[i]->desc),
        ENCODE (rt->item[i]->media_keywords),
        rt->item[i]->media_duration,
        str_escape_xml (rt->item[i]->media_thumbnail)
//        str_escape_xml (rt->item[i]->media_image),
//        rt->item[i]->event_start,
//        rt->item[i]->event_end
);

      hash_close (dl_url_h);
      hash_close (url_h);
      hash_close (title_h);
    }

  fputs ("</rsstool>\n", rsstool.output_file);

  if (items >= RSSMAXITEM)
    {
      char buf[MAXBUFSIZE];

      sprintf (buf, "can write only RSS feeds with up to %d items (was %d items)\n",
        RSSMAXITEM, items);
      rsstool_log (rt, buf);
    }

  return 0;
}
Example #15
0
enum DIRECTION GridAnt::chooseGrid()
{
    double tmp_prob[8] = {0,0,0,0,0,0,0,0};
    bool flag[8] = {false,false,false,false,false,false,false,false};
    int flag_res = 0;
    double total = 0.0;

    if(abs(cur_x - end_x) <= 1 && abs(cur_y - end_y) <= 1)
    {
        direction = GOAL;
        return GOAL;
    }

    if (cur_x - 1 >= 0 && g_grid[cur_x - 1][cur_y] == 0 && travel[cur_x - 1][cur_y] == 0)      //up
    {
        /*计算转移到其它城市概率,公式1*/
        tmp_prob[0] = pow(grid_pher[cur_city][ENCODE(cur_x - 1,cur_y)],ALPHA)*pow(1.0/PIX,BETA);
        flag[0] = true;
    }
    if (cur_x + 1 < N_GRID && g_grid[cur_x + 1][cur_y] == 0 && travel[cur_x + 1][cur_y] == 0)      //down
    {
        tmp_prob[1] = pow(grid_pher[cur_city][ENCODE(cur_x + 1,cur_y)],ALPHA)*pow(1.0/PIX,BETA);
        flag[1] = true;
    }
    if (cur_y - 1 >= 0 && g_grid[cur_x][cur_y - 1] == 0 && travel[cur_x][cur_y - 1] == 0)      //left
    {
        tmp_prob[2] = pow(grid_pher[cur_city][ENCODE(cur_x,cur_y - 1)],ALPHA)*pow(1.0/PIX,BETA);
        flag[2] = true;
    }
    if (cur_y + 1 < N_GRID && g_grid[cur_x][cur_y + 1] == 0 && travel[cur_x][cur_y + 1] == 0)      //right
    {
        tmp_prob[3] = pow(grid_pher[cur_city][ENCODE(cur_x,cur_y + 1)],ALPHA)*pow(1.0/PIX,BETA);
        flag[3] = true;
    }
    if (cur_x - 1 >= 0 && cur_y - 1 >= 0 && g_grid[cur_x - 1][cur_y - 1] == 0 && travel[cur_x - 1][cur_y - 1] == 0)         //left-up
    {
        tmp_prob[4] = pow(grid_pher[cur_city][ENCODE(cur_x - 1,cur_y - 1)],ALPHA)*pow(1.0/ANG_PIX,BETA);
        flag[4] = true;
    }
    if (cur_x + 1 < N_GRID && cur_y - 1 >= 0 && g_grid[cur_x + 1][cur_y - 1] == 0 && travel[cur_x + 1][cur_y - 1] == 0)      //left-down
    {
        tmp_prob[5] = pow(grid_pher[cur_city][ENCODE(cur_x + 1,cur_y - 1)],ALPHA)*pow(1.0/ANG_PIX,BETA);
        flag[5] = true;
    }
    if (cur_x - 1 >= 0 && cur_y + 1 < N_GRID && g_grid[cur_x - 1][cur_y + 1] == 0 && travel[cur_x - 1][cur_y + 1] == 0)      //right-up
    {
        tmp_prob[6] = pow(grid_pher[cur_city][ENCODE(cur_x - 1,cur_y + 1)],ALPHA)*pow(1.0/ANG_PIX,BETA);
        flag[6] = true;
    }
    if (cur_x + 1 < N_GRID && cur_y + 1 < N_GRID && g_grid[cur_x + 1][cur_y + 1] == 0 && travel[cur_x + 1][cur_y + 1] == 0)   //right-down
    {
        tmp_prob[7] = pow(grid_pher[cur_city][ENCODE(cur_x + 1,cur_y + 1)],ALPHA)*pow(1.0/ANG_PIX,BETA);
        flag[7] = true;
    }

    for (int i = 0; i < 8; ++i)
    {
        total += tmp_prob[i];
        flag_res += flag[i];
    }

    if(flag_res == 0)
    {
        direction = NOROAD;
        return NOROAD;
    }

    double rand_num = rnd(0.0,total);

    if (total > 0.0)
    {
        for (int i = 0; i < 8; ++i)
        {
            rand_num -= tmp_prob[i];
            if (rand_num < 0.0)
            {
                direction = (DIRECTION)i;
                return (DIRECTION)i;
            }
        }
    }
    printf("total is too little!\n");
    /*如果城市间的信息素非常小 ( 小到比double能够表示的最小的数字还要小 )
    那么由于浮点运算的误差原因,上面计算的概率总和可能为0
    会出现经过上述操作,没有城市被选择出来
    出现这种情况,就把第一个没去过的城市作为返回结果*/
    int greed_choose = -1;
    for (int i = 0; i < 8; ++i)
    {
        if (tmp_prob[i] > greed_choose)
        {
            greed_choose = i;
        }
    }

    direction = (DIRECTION)greed_choose;
    return (DIRECTION)greed_choose;
}
Example #16
0
u_char
sl_compress_tcp(struct mbuf * m,
		struct ip * ip,
		struct slcompress *comp,
                struct slstat *slstat,
		int compress_cid)
{
  register struct cstate *cs = comp->last_cs->cs_next;
  register u_int hlen = ip->ip_hl;
  register struct tcphdr *oth;
  register struct tcphdr *th;
  register u_int deltaS, deltaA;
  register u_int changes = 0;
  u_char new_seq[16];
  register u_char *cp = new_seq;

  /*
   * Bail if this is an IP fragment or if the TCP packet isn't `compressible'
   * (i.e., ACK isn't set or some other control bit is set).  (We assume that
   * the caller has already made sure the packet is IP proto TCP).
   */
  if ((ip->ip_off & htons(0x3fff)) || m->m_len < 40) {
    log_Printf(LogDEBUG, "??? 1 ip_off = %x, m_len = %lu\n",
	      ntohs(ip->ip_off), (unsigned long)m->m_len);
    log_DumpBp(LogDEBUG, "", m);
    return (TYPE_IP);
  }
  th = (struct tcphdr *) & ((int *) ip)[hlen];
  if ((th->th_flags & (TH_SYN | TH_FIN | TH_RST | TH_ACK)) != TH_ACK) {
    log_Printf(LogDEBUG, "??? 2 th_flags = %x\n", th->th_flags);
    log_DumpBp(LogDEBUG, "", m);
    return (TYPE_IP);
  }

  /*
   * Packet is compressible -- we're going to send either a COMPRESSED_TCP or
   * UNCOMPRESSED_TCP packet.  Either way we need to locate (or create) the
   * connection state.  Special case the most recently used connection since
   * it's most likely to be used again & we don't have to do any reordering
   * if it's used.
   */
  slstat->sls_packets++;
  if (ip->ip_src.s_addr != cs->cs_ip.ip_src.s_addr ||
      ip->ip_dst.s_addr != cs->cs_ip.ip_dst.s_addr ||
      *(int *) th != ((int *) &cs->cs_ip)[cs->cs_ip.ip_hl]) {

    /*
     * Wasn't the first -- search for it.
     *
     * States are kept in a circularly linked list with last_cs pointing to the
     * end of the list.  The list is kept in lru order by moving a state to
     * the head of the list whenever it is referenced.  Since the list is
     * short and, empirically, the connection we want is almost always near
     * the front, we locate states via linear search.  If we don't find a
     * state for the datagram, the oldest state is (re-)used.
     */
    register struct cstate *lcs;
    register struct cstate *lastcs = comp->last_cs;

    do {
      lcs = cs;
      cs = cs->cs_next;
      slstat->sls_searches++;
      if (ip->ip_src.s_addr == cs->cs_ip.ip_src.s_addr
	  && ip->ip_dst.s_addr == cs->cs_ip.ip_dst.s_addr
	  && *(int *) th == ((int *) &cs->cs_ip)[cs->cs_ip.ip_hl])
	goto found;
    } while (cs != lastcs);

    /*
     * Didn't find it -- re-use oldest cstate.  Send an uncompressed packet
     * that tells the other side what connection number we're using for this
     * conversation. Note that since the state list is circular, the oldest
     * state points to the newest and we only need to set last_cs to update
     * the lru linkage.
     */
    slstat->sls_misses++;
      comp->last_cs = lcs;
#define	THOFFSET(th)	(th->th_off)
    hlen += th->th_off;
    hlen <<= 2;
    if (hlen > m->m_len)
      return (TYPE_IP);
    goto uncompressed;

found:

    /*
     * Found it -- move to the front on the connection list.
     */
    if (cs == lastcs)
      comp->last_cs = lcs;
    else {
      lcs->cs_next = cs->cs_next;
      cs->cs_next = lastcs->cs_next;
      lastcs->cs_next = cs;
    }
  }

  /*
   * Make sure that only what we expect to change changed. The first line of
   * the `if' checks the IP protocol version, header length & type of
   * service.  The 2nd line checks the "Don't fragment" bit. The 3rd line
   * checks the time-to-live and protocol (the protocol check is unnecessary
   * but costless).  The 4th line checks the TCP header length.  The 5th line
   * checks IP options, if any.  The 6th line checks TCP options, if any.  If
   * any of these things are different between the previous & current
   * datagram, we send the current datagram `uncompressed'.
   */
  oth = (struct tcphdr *) & ((int *) &cs->cs_ip)[hlen];
  deltaS = hlen;
  hlen += th->th_off;
  hlen <<= 2;
  if (hlen > m->m_len)
    return (TYPE_IP);

  if (((u_short *) ip)[0] != ((u_short *) & cs->cs_ip)[0] ||
      ((u_short *) ip)[3] != ((u_short *) & cs->cs_ip)[3] ||
      ((u_short *) ip)[4] != ((u_short *) & cs->cs_ip)[4] ||
      THOFFSET(th) != THOFFSET(oth) ||
      (deltaS > 5 &&
       memcmp(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2)) ||
      (THOFFSET(th) > 5 &&
       memcmp(th + 1, oth + 1, (THOFFSET(th) - 5) << 2))) {
    goto uncompressed;
  }

  /*
   * Figure out which of the changing fields changed.  The receiver expects
   * changes in the order: urgent, window, ack, seq (the order minimizes the
   * number of temporaries needed in this section of code).
   */
  if (th->th_flags & TH_URG) {
    deltaS = ntohs(th->th_urp);
    ENCODEZ(deltaS);
    changes |= NEW_U;
  } else if (th->th_urp != oth->th_urp) {

    /*
     * argh! URG not set but urp changed -- a sensible implementation should
     * never do this but RFC793 doesn't prohibit the change so we have to
     * deal with it.
     */
    goto uncompressed;
  }
  deltaS = (u_short) (ntohs(th->th_win) - ntohs(oth->th_win));
  if (deltaS) {
    ENCODE(deltaS);
    changes |= NEW_W;
  }
  deltaA = ntohl(th->th_ack) - ntohl(oth->th_ack);
  if (deltaA) {
    if (deltaA > 0xffff) {
      goto uncompressed;
    }
    ENCODE(deltaA);
    changes |= NEW_A;
  }
  deltaS = ntohl(th->th_seq) - ntohl(oth->th_seq);
  if (deltaS) {
    if (deltaS > 0xffff) {
      goto uncompressed;
    }
    ENCODE(deltaS);
    changes |= NEW_S;
  }
  switch (changes) {

  case 0:

    /*
     * Nothing changed. If this packet contains data and the last one didn't,
     * this is probably a data packet following an ack (normal on an
     * interactive connection) and we send it compressed.  Otherwise it's
     * probably a retransmit, retransmitted ack or window probe.  Send it
     * uncompressed in case the other side missed the compressed version.
     */
    if (ip->ip_len != cs->cs_ip.ip_len &&
	ntohs(cs->cs_ip.ip_len) == hlen)
      break;

    /* FALLTHROUGH */

  case SPECIAL_I:
  case SPECIAL_D:

    /*
     * actual changes match one of our special case encodings -- send packet
     * uncompressed.
     */
    goto uncompressed;

  case NEW_S | NEW_A:
    if (deltaS == deltaA &&
	deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
      /* special case for echoed terminal traffic */
      changes = SPECIAL_I;
      cp = new_seq;
    }
    break;

  case NEW_S:
    if (deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
      /* special case for data xfer */
      changes = SPECIAL_D;
      cp = new_seq;
    }
    break;
  }

  deltaS = ntohs(ip->ip_id) - ntohs(cs->cs_ip.ip_id);
  if (deltaS != 1) {
    ENCODEZ(deltaS);
    changes |= NEW_I;
  }
  if (th->th_flags & TH_PUSH)
    changes |= TCP_PUSH_BIT;

  /*
   * Grab the cksum before we overwrite it below.  Then update our state with
   * this packet's header.
   */
  deltaA = ntohs(th->th_sum);
  memcpy(&cs->cs_ip, ip, hlen);

  /*
   * We want to use the original packet as our compressed packet. (cp -
   * new_seq) is the number of bytes we need for compressed sequence numbers.
   * In addition we need one byte for the change mask, one for the connection
   * id and two for the tcp checksum. So, (cp - new_seq) + 4 bytes of header
   * are needed.  hlen is how many bytes of the original packet to toss so
   * subtract the two to get the new packet size.
   */
  deltaS = cp - new_seq;
  cp = (u_char *) ip;

  /*
   * Since fastq traffic can jump ahead of the background traffic, we don't
   * know what order packets will go on the line.  In this case, we always
   * send a "new" connection id so the receiver state stays synchronized.
   */
  if (comp->last_xmit == cs->cs_id && compress_cid) {
    hlen -= deltaS + 3;
    cp += hlen;
    *cp++ = changes;
  } else {
    comp->last_xmit = cs->cs_id;
    hlen -= deltaS + 4;
    cp += hlen;
    *cp++ = changes | NEW_C;
    *cp++ = cs->cs_id;
  }
  m->m_len -= hlen;
  m->m_offset += hlen;
  *cp++ = deltaA >> 8;
  *cp++ = deltaA;
  memcpy(cp, new_seq, deltaS);
  slstat->sls_compressed++;
  return (TYPE_COMPRESSED_TCP);

  /*
   * Update connection state cs & send uncompressed packet ('uncompressed'
   * means a regular ip/tcp packet but with the 'conversation id' we hope to
   * use on future compressed packets in the protocol field).
   */
uncompressed:
  memcpy(&cs->cs_ip, ip, hlen);
  ip->ip_p = cs->cs_id;
  comp->last_xmit = cs->cs_id;
  return (TYPE_UNCOMPRESSED_TCP);
}
Example #17
0
static void backup_to_look_for_documentation_break(token_iterator&iterator, i7_codepoint first_codepoint_of_altered_text, bool have_already_effectively_backed_up_once) {
  static const i7_string*HYPHEN = &vocabulary.acquire(ENCODE("-"));
  static const i7_string*SPACE = &vocabulary.acquire(ENCODE(" "));
  static const i7_string*DOCUMENTATION = &vocabulary.acquire(ENCODE("DOCUMENTATION"));
  // While this function is called to look for documentation breaks, it is
  // always possible that the codepoint will combine in some more mundane way,
  // and checking for that requires at least one backup.  We get it out of the
  // way.
  --iterator;
  // Now, typing in the middle of a token can only form a documentation break
  // with earlier codepoints if it inserts letters to form DOCUMENTATION in the
  // middle.  In that case, we've already backed up past the other letters, so
  // we can fall through and pretend that the insertion wasn't in the middle.
  // Otherwise we're done.
  if (have_already_effectively_backed_up_once && !is_i7_lexical_delimiter_letter(first_codepoint_of_altered_text)) {
    return;
  }
  // For insertions not in the middle of a token, there are four cases.
  if (is_i7_lexical_delimiter_letter(first_codepoint_of_altered_text)) {
    // First, suppose the insertion begins with letters, which might be
    // DOCUMENTATION.  Then we still need to rewind past the prior space and the
    // four hyphens and get to the newline.
    goto from_documentation;
  }
  switch (first_codepoint_of_altered_text) {
  case '\n':
    // Newlines are similar, except that we have more tokens to cross.
    goto from_newline;
  case ' ':
    // Now we get into more complicated cases.  If we have a space, we don't
    // know which one it might be, so we have to consider both possibilities.
    if (iterator->get_text() == DOCUMENTATION) {
      goto from_second_space;
    }
    goto from_first_space;
  case '-':
    // And finally, if we have a hyphen, it could be in any of eight positions.
    // We backup over up to three prior hyphens, which will either be enough or
    // will get us to the second space, depending on which hyphen group we're
    // in.
    if (iterator->get_text() == HYPHEN) {
      --iterator;
      if (iterator->get_text() == HYPHEN) {
	--iterator;
	if (iterator->get_text() == HYPHEN) {
	  --iterator;
	}
      }
    }
    goto from_hyphens;
  }
  assert(false);
 from_newline:
  BACKUP_OVER(HYPHEN);
  BACKUP_OVER(HYPHEN);
  BACKUP_OVER(HYPHEN);
  BACKUP_OVER(HYPHEN);
 from_hyphens:
  BACKUP_OVER(SPACE);
 from_second_space:
  BACKUP_OVER(DOCUMENTATION);
 from_documentation:
  BACKUP_OVER(SPACE);
 from_first_space:
  BACKUP_OVER(HYPHEN);
  BACKUP_OVER(HYPHEN);
  BACKUP_OVER(HYPHEN);
  BACKUP_OVER(HYPHEN);
}
Example #18
0
int PS_color_aln(const char *structure, const char *filename, 
		 const char *seqs[], const char *names[]) {
  /* produce PS sequence alignment color-annotated by consensus structure */

  int N,i,j,k,x,y,tmp,columnWidth;
  char *tmpBuffer,*ssEscaped,*ruler, *cons;
  char c;
  float fontWidth, fontHeight, imageHeight, imageWidth,tmpColumns;
  int length, maxName, maxNum, currPos;
  float lineStep,blockStep,consStep,ssStep,rulerStep,nameStep,numberStep;
  float maxConsBar,startY,namesX,seqsX, currY;
  float score,barHeight,xx,yy;
  int match,block;
  FILE *outfile;
  short *pair_table;
  char * colorMatrix[6][3] = {
    {"0.0 1", "0.0 0.6",  "0.0 0.2"},  /* red    */
    {"0.16 1","0.16 0.6", "0.16 0.2"}, /* ochre  */
    {"0.32 1","0.32 0.6", "0.32 0.2"}, /* turquoise */
    {"0.48 1","0.48 0.6", "0.48 0.2"}, /* green  */
    {"0.65 1","0.65 0.6", "0.65 0.2"}, /* blue   */
    {"0.81 1","0.81 0.6", "0.81 0.2"} /* violet */
  };

  const char *alnPlotHeader =
	"%%!PS-Adobe-3.0 EPSF-3.0\n"
	"%%%%BoundingBox: %i %i %i %i\n"
	"%%%%EndComments\n"
	"%% draws Vienna RNA like colored boxes\n"
	"/box { %% x1 y1 x2 y2 hue saturation\n"
	"  gsave\n"
	"  dup 0.3 mul 1 exch sub sethsbcolor\n"
	"  exch 3 index sub exch 2 index sub rectfill\n"
	"  grestore\n"
	"} def\n"
	"%% draws a box in current color\n"
	"/box2 { %% x1 y1 x2 y2\n"
	"  exch 3 index sub exch 2 index sub rectfill\n"
	"} def\n"
	"/string { %% (Text) x y\n"
	" 6 add\n"
	" moveto\n"
	"  show\n"
	"} def\n"
	"0 %i translate\n"
	"1 -1 scale\n"
	"/Courier findfont\n"
	"[10 0 0 -10 0 0] makefont setfont\n";
	
  
  outfile = fopen(filename, "w");

  if (outfile == NULL) {
    fprintf(stderr, "can't open file %s - not doing alignment plot\n", 
	    filename);
    return 0;
  }
  
  columnWidth=60;            /* Display long alignments in blocks of this size */
  fontWidth=6;               /* Font metrics */
  fontHeight=6.5;
  lineStep=fontHeight+2;     /* distance between lines */
  blockStep=3.5*fontHeight;  /* distance between blocks */
  consStep=fontHeight*0.5;   /* distance between alignment and conservation curve */
  ssStep=2;                  /* distance between secondary structure line and sequences */
  rulerStep=2;               /* distance between sequences and ruler */
  nameStep=3*fontWidth;	     /* distance between names and sequences */
  numberStep=fontWidth;      /* distance between sequeces and numbers */
  maxConsBar=2.5*fontHeight; /* Height of conservation curve */
  startY=2;		     /* "y origin" */
  namesX=fontWidth;	     /* "x origin" */

  /* Number of columns of the alignment */
  length=strlen(seqs[0]);

  /* Allocate memory for various strings, length*2 is (more than)
	 enough for all of them */
  tmpBuffer = (char *) space((unsigned) length*2);
  ssEscaped=(char *) space((unsigned) length*2);
  ruler=(char *) space((unsigned) length*2);

  pair_table=make_pair_table(structure);
  /* Get length of longest name and count sequences in alignment*/

  for (i=maxName=N=0; names[i] != NULL; i++) {
    N++;
    tmp=strlen(names[i]);
    if (tmp>maxName)  maxName=tmp;
  }

  
  /* x-coord. where sequences start */
  seqsX=namesX+maxName*fontWidth+nameStep; 

  /* calculate number of digits of the alignment length */
  snprintf(tmpBuffer,length, "%i",length);
  maxNum=strlen(tmpBuffer);
  

  /* Calculate bounding box */
  tmpColumns=columnWidth;
  if (length<columnWidth){
	tmpColumns=length;
  }
  imageWidth=ceil(namesX+(maxName+tmpColumns+maxNum)*fontWidth+2*nameStep+fontWidth+numberStep);
  imageHeight=startY+ceil((float)length/columnWidth)*((N+2)*lineStep+blockStep+consStep+ssStep+rulerStep);

  /* Write postscript header including correct bounding box */
  fprintf(outfile,alnPlotHeader,0,0,(int)imageWidth,(int)imageHeight,(int)imageHeight);

  /* Create ruler and secondary structure lines */
  i=0;
  /* Init all with dots */
  for (i=0;i<(length);i++){
	ruler[i]='.';
  }
  i=0;
  for (i=0;i<length;i++){
	/* Write number every 10th position, leave out block breaks */
	if ((i+1)%10==0 && (i+1)%columnWidth!=0){
	  snprintf(tmpBuffer,length,"%i",i+1);
	  strncpy(ruler+i,tmpBuffer,strlen(tmpBuffer));
	}
  }
  ruler[length]='\0';
  
  /* Draw color annotation first */
  /* Repeat for all pairs */
  for (i=1; i<=length; i++) {
    if ((j=pair_table[i])>i) {
      /* Repeat for open and closing position */
      for (k=0;k<2;k++){
	int pairings, nonpair, s, col;
	int ptype[8] = {0,0,0,0,0,0,0,0};
	char *color;
	col = (k==0)?i-1:j-1;
	block=ceil((float)(col+1)/columnWidth);
	xx=seqsX+(col-(block-1)*columnWidth)*fontWidth;
	/* Repeat for each sequence */
	for (s=pairings=nonpair=0; s<N; s++) {
	  ptype[BP_pair[ENCODE(seqs[s][i-1])][ENCODE(seqs[s][j-1])]]++;
	}
	for (pairings=0,s=1; s<=7; s++) {
	  if (ptype[s]) pairings++;
	}
	nonpair=ptype[0];
	if (nonpair <=2) {
	  color = colorMatrix[pairings-1][nonpair];
	  for (s=0; s<N; s++) {
	    yy=startY+(block-1)*(lineStep*(N+2)+blockStep+consStep+rulerStep)+ssStep*(block)+(s+1)*lineStep;
	    
	    /* Color according due color information in pi-array, only if base pair is possible */
	    if (BP_pair[ENCODE(seqs[s][i-1])][ENCODE(seqs[s][j-1])]) {

	      fprintf(outfile, "%.1f %.1f %.1f %.1f %s box\n",
		      xx,yy-1,xx+fontWidth,yy+fontHeight+1,color);
	    }
	  }
	}
      }
    }
  }
  free(pair_table);

  /* Process rest of the output in blocks of columnWidth */

  currY=startY;
  currPos=0;

  cons =  consensus(seqs);
  
  while (currPos<length) {

    /* Display secondary structure line */
    fprintf(outfile,"0 setgray\n");
    strncpy(tmpBuffer,structure+currPos,columnWidth);
    tmpBuffer[columnWidth]='\0';
    
    x=0;y=0;
    while ((c=tmpBuffer[x])){
      if (c=='.'){
	ssEscaped[y++]='.';
      } else {
	ssEscaped[y++]='\\';
	ssEscaped[y++]=c;
      }			 
      x++;
    }
    ssEscaped[y]='\0';
    
    fprintf(outfile, "(%s) %.1f %.1f string\n", ssEscaped,seqsX,currY);
    currY+=ssStep+lineStep;
    
    /* Display names, sequences and numbers */

    for (i=0; i<N; i++) {
      
      strncpy(tmpBuffer,seqs[i]+currPos,columnWidth);
      tmpBuffer[columnWidth]='\0';
      
      match=0;
      for (j=0;j<(currPos+strlen(tmpBuffer));j++){
	if (seqs[i][j] != '-') match++;
      }
      
      fprintf(outfile, "(%s) %.1f %.1f string\n", names[i],namesX,currY);
      fprintf(outfile, "(%s) %.1f %.1f string\n", tmpBuffer,seqsX,currY);
      fprintf(outfile, "(%i) %.1f %.1f string\n", match,seqsX+fontWidth*(strlen(tmpBuffer))+numberStep,currY);
      currY+=lineStep;
    }
    currY+=rulerStep;
    strncpy(tmpBuffer,ruler+currPos,columnWidth);
    tmpBuffer[columnWidth]='\0';
    fprintf(outfile, "(%s) %.1f %.1f string\n", tmpBuffer,seqsX,currY);
    
    currY+=lineStep;
    currY+=consStep;
    
    /*Display conservation bar*/
    
    fprintf(outfile,"0.6 setgray\n");
    for (i=currPos;(i<currPos+columnWidth && i<length);i++){
      match=0;
      for (j=0;j<N;j++){
	if (cons[i] == seqs[j][i]) match++;
	if (cons[i]=='U' && seqs[j][i]=='T') match++;
	if (cons[i]=='T' && seqs[j][i]=='U') match++;
      }
      score=(float)(match-1)/(N-1);
      
      if (cons[i] == '-' ||
	  cons[i] == '_' ||
	  cons[i] == '.'){
	score=0;
      }
      
      barHeight=maxConsBar*score;
      if (barHeight==0){
	barHeight=1;
      }
      
      xx=seqsX+(i-(columnWidth*currPos/columnWidth))*fontWidth;
      
      fprintf(outfile,"%.1f %.1f %.1f %.1f box2\n",
	      xx,
	      currY+maxConsBar-barHeight,
	      xx+fontWidth,
	      currY+maxConsBar);
    }
    
    currY+=blockStep;
    currPos+=columnWidth;
  }
  free(cons);

  fprintf(outfile,"showpage\n");
  fclose(outfile);

  free(tmpBuffer);
  free(ssEscaped);free(ruler);
  
  return 0;

}
Example #19
0
}

CCodeEngine::~CCodeEngine()
{

}

int32_t CCodeEngine::Encode(uint8_t* buf, const uint32_t size, uint32_t& offset, const bool data)
{
	uint8_t v = (data ? 1 : 0);
	return Encode(buf, size, offset, v);
}

int32_t CCodeEngine::Encode(uint8_t* buf, const uint32_t size, uint32_t& offset, const int8_t data)
{
	ENCODE(buf, size, offset, data, int8_t)
}

int32_t CCodeEngine::Encode(uint8_t* buf, const uint32_t size, uint32_t& offset, const int16_t data)
{
	ENCODE(buf, size, offset, data, int16_t)
}

int32_t CCodeEngine::Encode(uint8_t* buf, const uint32_t size, uint32_t& offset, const int32_t data)
{
	ENCODE(buf, size, offset, data, int32_t)
}

int32_t CCodeEngine::Encode(uint8_t* buf, const uint32_t size, uint32_t& offset, const int64_t data)
{
	ENCODE(buf, size, offset, data, int64_t)
Example #20
0
int
rsstool_write_xml (st_rsstool_t *rt)
{
#define XMLPRINTF(s) xmlTextWriterWriteString(writer,BAD_CAST s)
  st_rss_t rss;
  int i = 0;
  xmlTextWriterPtr writer;
  xmlBufferPtr buffer;
  st_hash_t *dl_url_h = NULL;
  st_hash_t *url_h = NULL;
  st_hash_t *title_h = NULL;
  int items = rsstool_get_item_count (rt);
#define ENCODE(s) s
//#define ENCODE(s) base64_enc(s,0)
//#define ENCODE(s) str_escape_xml(s)

  memset (&rss, 0, sizeof (st_rss_t));

  if (!(buffer = xmlBufferCreate ()))
    return -1;

  if (!(writer = xmlNewTextWriterMemory (buffer, 0)))
    return -1;

  xmlTextWriterStartDocument (writer, NULL, "UTF-8", NULL);

  xmlTextWriterWriteComment (writer, BAD_CAST " RSStool - read, parse, merge and write RSS and Atom feeds\n"                            
    "http://rsstool.berlios.de ");

  XMLPRINTF("\n");

  xmlTextWriterWriteComment (writer, BAD_CAST "\n"
         "format:\n"
         "item[]\n"
         "  dl_url           \n"
         "  dl_url_md5\n"
         "  dl_url_crc32\n"
         "  dl_date\n"
         "  user             author\n"
         "  site\n"
         "  url              \n"
         "  url_md5\n"
         "  url_crc32\n"
         "  date             default: current time\n"
         "  title            used by searches for related items\n"
         "  title_md5\n"
         "  title_crc32\n"
         "  desc             description\n"
         "  media_keywords   default: keywords from title and description\n"
         "  media_duration   event length\n"
         "  media_image      thumbnail\n"
         "  event_start      default: date\n"
         "  event_end        default: event_start + media_duration\n"
);

  XMLPRINTF("\n");

  xmlTextWriterStartElement (writer, BAD_CAST "rsstool");  // <rsstool>
  xmlTextWriterWriteAttribute (writer, BAD_CAST "version", BAD_CAST RSSTOOL_VERSION_S);

  for (i = 0; i < items && i < RSSMAXITEM; i++)
//  for (i = 0; i < items; i++)
    {
      dl_url_h = hash_open (HASH_MD5|HASH_CRC32);
      url_h = hash_open (HASH_MD5|HASH_CRC32);
      title_h = hash_open (HASH_MD5|HASH_CRC32);

      dl_url_h = hash_update (dl_url_h, (const unsigned char *) rt->item[i]->feed_url, strlen (rt->item[i]->feed_url));
      url_h = hash_update (url_h, (const unsigned char *) rt->item[i]->url, strlen (rt->item[i]->url));
      title_h = hash_update (title_h, (const unsigned char *) rt->item[i]->title, strlen (rt->item[i]->title));

      XMLPRINTF("\n  ");

      xmlTextWriterStartElement (writer, BAD_CAST "item"); // <item>

      XMLPRINTF("\n    ");

//      xmlTextWriterWriteElement (writer, BAD_CAST "dl_url", BAD_CAST rt->item[i]->feed_url);
      xmlTextWriterWriteFormatElement (writer, BAD_CAST "dl_url", "%s", rt->item[i]->feed_url);

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "dl_url_md5", "%s", hash_get_s (dl_url_h, HASH_MD5));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "dl_url_crc32", "%u", hash_get_crc32 (dl_url_h));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "dl_date", "%ld", rsstool.start_time);

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "user", "%s", ENCODE (rt->item[i]->user));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "site", "%s", ENCODE (rt->item[i]->site));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "url", "%s", rt->item[i]->url);

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "url_md5", "%s", hash_get_s (url_h, HASH_MD5));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "url_crc32", "%u", hash_get_crc32 (url_h));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "date", "%ld", rt->item[i]->date);

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "title", "%s", ENCODE (rt->item[i]->title));


      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "title_md5", "%s", hash_get_s (title_h, HASH_MD5));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "title_crc32", "%u", hash_get_crc32 (title_h));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "desc", "%s", ENCODE (rt->item[i]->desc));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "media_keywords", "%s", ENCODE (rt->item[i]->media_keywords));

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "media_duration", "%ld", rt->item[i]->media_duration);

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "media_image", "%s", rt->item[i]->media_image);

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "event_start", "%ld", rt->item[i]->event_start);

      XMLPRINTF("\n    ");

      xmlTextWriterWriteFormatElement (writer, BAD_CAST "event_end", "%ld", rt->item[i]->event_end);

      XMLPRINTF("\n  ");

      xmlTextWriterEndElement (writer); // </item>

      hash_close (dl_url_h);
      hash_close (url_h);
      hash_close (title_h);
    }

  XMLPRINTF("\n");

  xmlTextWriterEndDocument (writer);  // </rsstool>

  xmlFreeTextWriter (writer);

  fputs ((const char *) buffer->content, rt->output_file);

  xmlBufferFree (buffer);

  if (items >= RSSMAXITEM)
    {
      char buf[MAXBUFSIZE];

      sprintf (buf, "can write only RSS feeds with up to %d items (was %d items)\n",
        RSSMAXITEM, items);
      rsstool_log (rt, buf);
    }

  return 0;
}
bool	Satori::Save(bool isOnUnload) {
	GetSender().next_event();

	// メンバ変数を里々変数化
	for (std::map<int, string>::iterator it=reserved_talk.begin(); it!=reserved_talk.end() ; ++it)
		variables[string("次から")+itos(it->first)+"回目のトーク"] = it->second;

	// 起動時間累計を設定
	variables["ゴースト起動時間累計秒"] =
	    uitos(posix_get_current_sec() - sec_count_at_load + sec_count_total,"%lu");
	// (互換用)
	variables["ゴースト起動時間累計ミリ秒"] =
	    uitos((posix_get_current_sec() - sec_count_at_load + sec_count_total)*1000,"%lu");
	variables["ゴースト起動時間累計(ms)"] =
	    uitos((posix_get_current_sec() - sec_count_at_load + sec_count_total)*1000,"%lu");

	if ( isOnUnload ) {
		secure_flag = true;
		(void)GetSentence("OnSatoriUnload");
	}

	string	theFullPath = mBaseFolder + "satori_savedata.tmp";

	std::ofstream	out(theFullPath.c_str());
	bool	temp = GetSender().is_validated();
	GetSender().validate();
	GetSender().sender() << "saving " << theFullPath << "... " ;
	GetSender().validate(temp);
	if ( !out.is_open() )
	{
		GetSender().sender() << "failed." << std::endl;
		return	false;
	}

	string	line = "*セーブデータ";
	string  data;

	out << ENCODE(line) << std::endl;
	for (strmap::const_iterator it=variables.begin() ; it!=variables.end() ; ++it) {
		string	str = zen2han(it->first);
		if ( str[0]=='S' && aredigits(str.c_str()+1) ) {
			continue;
		}
		if ( str == "今回は喋らない" || str == "今回は会話時サーフェス戻し" || str == "今回は会話時サーフィス戻し" || str == "今回は自動アンカー" ) {
			continue;
		}

		data = it->second;
		
		replace(data,"φ","φφ");
		replace(data,"(","φ(");
		replace(data,")","φ)");
		m_escaper.unescape_for_dic(data);

		string	line = string("$")+it->first+"\t"+data; // 変数を保存
		out << ENCODE(line) << std::endl;
	}

	for (std::map<string, std::vector<Word> >::const_iterator i=mAppendedWords.begin() ; i!=mAppendedWords.end() ; ++i )
	{
		if ( ! i->second.empty() ) {
			out << std::endl << ENCODE( string("@") + i->first ) << std::endl;
			for (std::vector<Word>::const_iterator j=i->second.begin() ; j!=i->second.end() ; ++j )
			{
				out << ENCODE( *j ) << std::endl;
			}
		}
	}

	out.flush();
	out.close();

	GetSender().sender() << "ok." << std::endl;

	//バックアップ
	string	realFullPath = mBaseFolder + "satori_savedata." + (fEncodeSavedata?"sat":"txt");
	string	realFullPathBackup = mBaseFolder + "satori_savebackup." + (fEncodeSavedata?"sat":"txt");
#ifdef POSIX
	unlink(realFullPathBackup.c_str());
	rename(realFullPath.c_str(),realFullPathBackup.c_str());
	rename(theFullPath.c_str(),realFullPath.c_str());
#else
	::DeleteFile(realFullPathBackup.c_str());
	::MoveFile(realFullPath.c_str(),realFullPathBackup.c_str());
	::MoveFile(theFullPath.c_str(),realFullPath.c_str());
#endif

	//いらないほうを消す
	string	delFullPath = mBaseFolder + "satori_savedata." + (fEncodeSavedata?"txt":"sat");
	string	delFullPathBackup = mBaseFolder + "satori_savebackup." + (fEncodeSavedata?"txt":"sat");
#ifdef POSIX
	unlink(delFullPath.c_str());
	unlink(delFullPathBackup.c_str());
#else
	::DeleteFile(delFullPath.c_str());
	::DeleteFile(delFullPathBackup.c_str());
#endif

	return	true;
}