示例#1
0
文件: winapi.l.c 项目: ignacio/winapi
/// expand # unicode escapes in a string.
// @param text ASCII text with #XXXX, where XXXX is four hex digits. ## means # itself.
// @return text as UTF-8
// @see testu.lua
// @function utf8_expand
def utf8_expand(Str text) {
  int len = strlen(text), i = 0, enc = get_encoding();
  WCHAR wch;
  LPWSTR P = wbuff;
  if (len > sizeof(wbuff)) {
    return push_error_msg(L,"string too big");
  }
  while (i <= len) {
    if (text[i] == '#') {
      ++i;
      if (text[i] == '#') {
        wch = '#';
      } else
      if (len-i >= 4) {
        char hexnum[5];
        strncpy(hexnum,text+i,4);
        hexnum[4] = '\0';
        wch = strtol(hexnum,NULL,16);
        i += 3;
      } else {
        return push_error_msg(L,"bad # escape");
      }
    } else {
      wch = (WCHAR)text[i];
    }
    *P++ = wch;
    ++i;
  }
  *P++ = 0;
  set_encoding(CP_UTF8);
  push_wstring(L,wbuff);
  set_encoding(enc);
  return 1;
}
示例#2
0
文件: hexa.c 项目: daloji/UsbDongle
int check_encoding(const char* msg, unsigned length)
{
	str_encoding_t possible_enc = get_encoding(RECODE_ENCODE, msg, length);
	if(possible_enc == STR_ENCODING_7BIT_HEX)
		return PDU_DCS_ALPABET_7BIT;
	return PDU_DCS_ALPABET_UCS2;
}
示例#3
0
// somewhat over-elaborate constructor
// because errors related to image files can be such a pain to debug
Image::Image(Point xy, string s, Suffix::Encoding e)
    :w(0), h(0), fn(xy,"")
{
    add(xy);

    if (!can_open(s)) {    // can we open s?
        fn.set_label("cannot open \""+s+'\"');
        p = new Bad_image(30,20);    // the "error image"
        return;
    }

    if (e == Suffix::none) e = get_encoding(s);

    switch(e) {        // check if it is a known encoding
    case Suffix::jpg:
        p = new Fl_JPEG_Image(s.c_str());
        break;
    case Suffix::gif:
        p = new Fl_GIF_Image(s.c_str());
        break;
    default:    // Unsupported image encoding
        fn.set_label("unsupported file type \""+s+'\"');
        p = new Bad_image(30,20);    // the "error image"
    }
}
示例#4
0
 /**
  * @return a std::string containing a list of vertices and edges
  */
 std::string tsp_vrplc::human_readable_extra() const 
 {
     std::ostringstream oss;
     oss << "\n\tNumber of cities: " << get_n_cities() << '\n';
     oss << "\tEncoding: ";
     switch( get_encoding()  ) {
         case FULL:
             oss << "FULL" << '\n';
             break;
         case RANDOMKEYS:
             oss << "RANDOMKEYS" << '\n';
             break;
         case CITIES:
             oss << "CITIES" << '\n';
             break;
     }
     oss << "\tMaximum vehicle capacity: " << m_capacity << std::endl;
     oss << "\tWeight Matrix: \n";
     for (decision_vector::size_type i=0; i<get_n_cities() ; ++i)
     {
         oss << "\t\t" << m_weights.at(i) << '\n';
         if (i>5)
         {
             oss << "\t\t..." << '\n';
             break;
         }
     }
     return oss.str();
 }
示例#5
0
char* create_xlfd(font_family* family, font_style* style, uint32 flag) {
  char buf[100];
  sprintf(buf, "-TTFont-%s-%s-%c-normal--0-0-0-0-%c-0-%s",
    *family, get_weight(style), get_slant(style), get_spacing(flag), get_encoding(family));
  char* xlfd = (char*) calloc(strlen(buf) + 1, sizeof(char));
  strcpy(xlfd, buf);
  return xlfd;
}
示例#6
0
void openddl::detail::ParserContext::push_literal_list(Command::LiteralPayload::encoding_t encoding, Token const * ts, Token const * te)
{
	Command::LiteralPayload::encoding_t type_encoding;
	try {
		if (commands.back().type == Command::kDataList)
			type_encoding = get_encoding(commands.back().payload.list_.type);
		else
			type_encoding = get_encoding(commands[*(&parents.back() - 1) - 1].payload.array_.type);
			
		if (type_encoding == Command::LiteralPayload::kInteger && encoding == Command::LiteralPayload::kFloat
			|| type_encoding == Command::LiteralPayload::kFloat && encoding == Command::LiteralPayload::kInteger)
		{
			encoding = type_encoding;
		}
	}
	catch (std::out_of_range &)
	{
		push_error("parse.literal.internal_error");
		type_encoding = encoding;
	}

	unsigned int parent = parents.back();
	unsigned int depth = parents.size();
	Command::LiteralPayload payload;

	Token const * i = ts + 1;
	while (i < te - 1)
	{
		i += build_literal(encoding, i, te - 1, payload) + 1;
		commands.emplace_back(payload,parent,depth);
		
	}

	{
		//Set parent lengths
		Command * parent = &commands[parents.back()-1];
		if (parent->type == Command::kDataList)
			parent->payload.list_.length = &commands.back() - parent;
		else if (parent->type == Command::kArrayElement)
			parent->payload.element_.length = &commands.back() - parent;
	}
	
	parents.pop_back();

}
示例#7
0
static const char * parse_cmgr_text(char ** str, size_t len, char * oa, size_t oa_len, str_encoding_t * oa_enc, char ** msg, str_encoding_t * msg_enc)
{
	/*
	 * parse cmgr info in the following TEXT format:
	 * +CMGR: "<msg status>","+123456789",,timestamp<CR><LF>
	 * <message text><CR><LF><CR><LF>
	 * OK<CR><LF>
	 *	or
	 * +CMGR: "<msg status>","002B....",,timestamp<CR><LF>
	 * <message text><CR><LF><CR><LF>
	 * OK<CR><LF>
	 */

	char delimiters[] = ",,,\n";
	char * marks[STRLEN(delimiters)];
	size_t length;
	
	unsigned count = mark_line(*str, delimiters, marks);
	if(count == ITEMS_OF(marks))
	{
		/* unquote number */
		marks[0]++;
		if(marks[0][0] == '"')
			marks[0]++;
		if(marks[1][-1] == '"')
			marks[1]--;
		length = marks[1] - marks[0] + 1;
		if(oa_len < length)
			return "Not enought space for store number";
		*oa_enc = get_encoding(RECODE_DECODE, marks[0], length  - 1);
		marks[1][0] = 0;
		memcpy(oa, marks[0], length);

		*msg = marks[3] + 1;
		length = len - (*msg - *str);
		*msg_enc = get_encoding(RECODE_DECODE, *msg, length);
		return NULL;
	}
	else if(count > 0)
		*str = marks[count - 1];

	return "Can't parse +CMGR response text";
}
示例#8
0
static int
ircam_write_header (SF_PRIVATE *psf, int UNUSED (calc_length))
{	int			encoding ;
	float		samplerate ;
	sf_count_t	current ;

	if (psf->pipeoffset > 0)
		return 0 ;

	current = psf_ftell (psf) ;

	/* This also sets psf->endian. */
	encoding = get_encoding (SF_CODEC (psf->sf.format)) ;

	if (encoding == 0)
		return SFE_BAD_OPEN_FORMAT ;

	/* Reset the current header length to zero. */
	psf->header [0] = 0 ;
	psf->headindex = 0 ;

	if (psf->is_pipe == SF_FALSE)
		psf_fseek (psf, 0, SEEK_SET) ;

	samplerate = psf->sf.samplerate ;

	switch (psf->endian)
	{	case SF_ENDIAN_BIG :
			psf_binheader_writef (psf, "Emf", IRCAM_02B_MARKER, samplerate) ;
			psf_binheader_writef (psf, "E44", psf->sf.channels, encoding) ;
			break ;

		case SF_ENDIAN_LITTLE :
			psf_binheader_writef (psf, "emf", IRCAM_03L_MARKER, samplerate) ;
			psf_binheader_writef (psf, "e44", psf->sf.channels, encoding) ;
			break ;

		default :
			return SFE_BAD_OPEN_FORMAT ;
	} ;

	psf_binheader_writef (psf, "z", (size_t) (IRCAM_DATA_OFFSET - psf->headindex)) ;

	/* Header construction complete so write it out. */
	psf_fwrite (psf->header, psf->headindex, 1, psf) ;

	if (psf->error)
		return psf->error ;

	if (current > 0)
		psf_fseek (psf, current, SEEK_SET) ;

	return psf->error ;
} /* ircam_write_header */
示例#9
0
static int get_message(const char *raw_message, struct commit_message *out)
{
	const char *encoding;
	const char *p, *abbrev, *eol;
	char *q;
	int abbrev_len, oneline_len;

	if (!raw_message)
		return -1;
	encoding = get_encoding(raw_message);
	if (!encoding)
		encoding = "UTF-8";
	if (!git_commit_encoding)
		git_commit_encoding = "UTF-8";

	out->reencoded_message = NULL;
	out->message = raw_message;
	if (strcmp(encoding, git_commit_encoding))
		out->reencoded_message = reencode_string(raw_message,
					git_commit_encoding, encoding);
	if (out->reencoded_message)
		out->message = out->reencoded_message;

	abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
	abbrev_len = strlen(abbrev);

	/* Find beginning and end of commit subject. */
	p = out->message;
	while (*p && (*p != '\n' || p[1] != '\n'))
		p++;
	if (*p) {
		p += 2;
		for (eol = p + 1; *eol && *eol != '\n'; eol++)
			; /* do nothing */
	} else
		eol = p;
	oneline_len = eol - p;

	out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
			      strlen("... ") + oneline_len + 1);
	q = out->parent_label;
	q = mempcpy(q, "parent of ", strlen("parent of "));
	out->label = q;
	q = mempcpy(q, abbrev, abbrev_len);
	q = mempcpy(q, "... ", strlen("... "));
	out->subject = q;
	q = mempcpy(q, p, oneline_len);
	*q = '\0';
	return 0;
}
示例#10
0
		bool base_type_die::is_rep_compatible(std::shared_ptr<type_die> arg) const
		{
        	// first, try to make arg concrete
			// HACK: strange infinite recursion bug here, so try using get_offset
			if (!arg->get_concrete_type()) return false;
			if (arg->get_concrete_type()->get_offset() != arg->get_offset()) return this->is_rep_compatible(
				arg->get_concrete_type());			
			auto arg_base_type = std::dynamic_pointer_cast<base_type_die>(arg);
			if (!arg_base_type) return false;
			
			return arg_base_type->get_encoding() == this->get_encoding()
				&& arg_base_type->get_byte_size() == this->get_byte_size()
				&& arg_base_type->get_bit_size () == this->get_bit_size()
				&& arg_base_type->get_bit_offset() == this->get_bit_offset();
		}
示例#11
0
static int
ircam_write_header (SF_PRIVATE *psf, int calc_length)
{	int			encoding ;
	float		samplerate ;
	sf_count_t	current ;

	current = psf_ftell (psf) ;

	calc_length = calc_length ;

	/* This also sets psf->endian. */
	encoding = get_encoding (psf->sf.format & SF_FORMAT_SUBMASK) ;
	
	if (! encoding)
		return SFE_BAD_OPEN_FORMAT ;

	/* Reset the current header length to zero. */
	psf->header [0] = 0 ;
	psf->headindex = 0 ;
	psf_fseek (psf, 0, SEEK_SET) ;
	
	samplerate = psf->sf.samplerate ;

	if (psf->endian == SF_ENDIAN_BIG)
	{	psf_binheader_writef (psf, "Emf", IRCAM_02B_MARKER, samplerate) ;
		psf_binheader_writef (psf, "E44", psf->sf.channels, encoding) ;
		}
	else if  (psf->endian == SF_ENDIAN_LITTLE)
	{	psf_binheader_writef (psf, "emf", IRCAM_03L_MARKER, samplerate) ;
		psf_binheader_writef (psf, "e44", psf->sf.channels, encoding) ;
		}
	else
		return SFE_BAD_OPEN_FORMAT ;

	psf_binheader_writef (psf, "z", IRCAM_DATA_OFFSET - psf->headindex) ;
	
	/* Header construction complete so write it out. */
	psf_fwrite (psf->header, psf->headindex, 1, psf) ;

	if (psf->error)
		return psf->error ;

	if (current > 0)
		psf_fseek (psf, current, SEEK_SET) ;
		
	return psf->error ;
} /* ircam_write_header */ 
示例#12
0
文件: winapi.l.c 项目: ignacio/winapi
/// encode a string in another encoding.
// Note: currently there's a limit of about 2K on the string buffer.
// @param e_in `CP_ACP`, `CP_UTF8` or `CP_UTF16`
// @param e_out likewise
// @param text the string
// @function encode
def encode(Int e_in, Int e_out, Str text) {
  int ce = get_encoding();
  LPCWSTR ws;
  if (e_in != -1) {
    set_encoding(e_in);
    ws = wstring(text);
  } else {
    ws = (LPCWSTR)text;
  }
  if (e_out != -1) {
    set_encoding(e_out);
    push_wstring(L,ws);
  } else {
    lua_pushlstring(L,(LPCSTR)ws,wcslen(ws)*sizeof(WCHAR));
  }
  set_encoding(ce);
  return 1;
}
示例#13
0
文件: revert.c 项目: jjuran/git
static int get_message(const char *raw_message, struct commit_message *out)
{
	const char *encoding;
	const char *abbrev, *subject;
	int abbrev_len, subject_len;
	char *q;

	if (!raw_message)
		return -1;
	encoding = get_encoding(raw_message);
	if (!encoding)
		encoding = "UTF-8";
	if (!git_commit_encoding)
		git_commit_encoding = "UTF-8";

	out->reencoded_message = NULL;
	out->message = raw_message;
	if (strcmp(encoding, git_commit_encoding))
		out->reencoded_message = reencode_string(raw_message,
					git_commit_encoding, encoding);
	if (out->reencoded_message)
		out->message = out->reencoded_message;
	else
		out->message = raw_message;

	abbrev = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
	abbrev_len = strlen(abbrev);

	subject_len = find_commit_subject(out->message, &subject);

	out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
			      strlen("... ") + subject_len + 1);
	q = out->parent_label;
	q = mempcpy(q, "parent of ", strlen("parent of "));
	out->label = q;
	q = mempcpy(q, abbrev, abbrev_len);
	q = mempcpy(q, "... ", strlen("... "));
	out->subject = q;
	q = mempcpy(q, subject, subject_len);
	*q = '\0';
	return 0;
}
示例#14
0
 void tsp_vrplc::objfun_impl(fitness_vector &f, const decision_vector& x) const 
 {
     f[0] = 1;
     double stl = 0;
     decision_vector tour;
     decision_vector::size_type n_cities = get_n_cities();
     switch( get_encoding() ) {
         case FULL:
         {
             tour = full2cities(x);
             break;
         }
         case RANDOMKEYS:
         {
             tour = randomkeys2cities(x);
             break;
         }
         case CITIES:
         {
             tour = x;
             break;
         }
     }
     for (decision_vector::size_type i=0; i<n_cities-1; ++i) {
         stl += m_weights[tour[i]][tour[i+1]];
         if(stl > m_capacity)
         {
             stl = 0;
             f[0] += 1;
         }
         else
         {
             f[0] += (m_weights[tour[i]][tour[i+1]])/(n_cities*m_capacity);
         }
     }
     return;
 }
示例#15
0
  Object* UnMarshaller::unmarshal() {
    char code;

    stream >> code;

    switch(code) {
    case 'n':
      return cNil;
    case 't':
      return cTrue;
    case 'f':
      return cFalse;
    case 'I':
      return get_int();
    case 's':
      return get_string();
    case 'x':
      return get_symbol();
    case 'p':
      return get_tuple();
    case 'd':
      return get_float();
    case 'i':
      return get_iseq();
    case 'M':
      return get_cmethod();
    case 'c':
      return get_constant();
    case 'E':
      return get_encoding();
    default:
      std::string str = "unknown marshal code: ";
      str.append( 1, code );
      Exception::type_error(state, str.c_str());
      return cNil;    // make compiler happy
    }
  }
示例#16
0
int main(int argc, char *argv[]){

  // 1. Initialization
  int c;
  symbol *root;
  root=init_symbol(ROOT_NODE);
  root->frequency=NON_EXISTENT;
  root->parent=root;
  
  // 1.a. init: file pointers
  FILE *inputfile;
  FILE *outputfile;
  inputfile=NULL;
  outputfile=NULL;

  if (argc >=2)
    inputfile = fopen(argv[1],"r");
  
  if (argc >=3)
    outputfile = fopen(argv[2],"w");
  
  if (inputfile == NULL) {
    fprintf(stderr, "Can't open input file. \n");
    exit(1);
  }

  if (outputfile == NULL) {
    outputfile=stdout;
  }
  
  // 2. count the frequency of each character in inputfile 
  while((c=fgetc(inputfile))!=EOF){
    update_frequency(root,c);
  }
  update_frequency(root,-1);


  // 3. Make the huffman tree
  while(count_parentless_nodes(root) > 1){
    symbol *node1,*node2, *newnode;
    node1 = get_rarest_parentless_node(root);
    node1->parent=node1; //temporarily
    node2 = get_rarest_parentless_node(root);
    node2->parent=node2; //temporarily
    newnode = new_node(node1, node2);
    insert_symbol(root,newnode);
  }


  // 4. Output symbol mappings
  for(c=-1;c<256;c++){
    char *encodingstring;
    encodingstring=get_encoding(root,c);
    int freq=get_frequency(root,c);
    if (freq > 0){
      /*if (c <=127 && c>=32 )
	fprintf(outputfile,"%c\t%d\t%s\n", c, freq, encodingstring);    
      else */
	fprintf(outputfile,"%d\t%d\t%s\n", c, freq, encodingstring);    
    }
    free(encodingstring);
  }
  fprintf(outputfile,"\n");    

  
  // 5. Output encoding of inputfile
  rewind(inputfile);
  while((c=fgetc(inputfile))!=EOF){
    char *encodingstring;
    encodingstring=get_encoding(root,c);
    fprintf(outputfile, "%s", encodingstring);
    free(encodingstring);
  }
  char *encodingstring;
  encodingstring=get_encoding(root,EOF);
  fprintf(outputfile, "%s", encodingstring);
  free(encodingstring);
  fprintf(outputfile,"\n");    

  free_symbol(root);
  
  
  // 6. Close file pointers
  fclose(inputfile);
  fclose(outputfile);
}
gchar *
get_encoding_and_convert (const gchar * text, guint length)
{
  GError *error = NULL;
  gchar *converted_str;
  guint start_text = 0;
  gboolean is_multibyte;
  LocalIconvCode encoding;
  GIConv giconv = (GIConv) - 1;

  g_return_val_if_fail (text != NULL, NULL);

  if (text == NULL || length == 0)
    return g_strdup ("");

  encoding = get_encoding (text, &start_text, &is_multibyte);

  if (encoding > _ICONV_UNKNOWN && encoding < _ICONV_MAX) {
    GST_DEBUG ("Encoding %s", iconvtablename[encoding]);
    giconv = _get_iconv (encoding, _ICONV_UTF8);
  } else {
    GST_FIXME ("Could not detect encoding. Returning NULL string");
    converted_str = NULL;
    goto beach;
  }

  converted_str = convert_to_utf8 (text, length - start_text, start_text,
      giconv, is_multibyte, &error);
  if (error != NULL) {
    GST_WARNING ("Could not convert string: %s", error->message);
    g_free (converted_str);
    g_error_free (error);
    error = NULL;

    if (encoding >= _ICONV_ISO8859_2 && encoding <= _ICONV_ISO8859_15) {
      /* Sometimes using the standard 8859-1 set fixes issues */
      GST_DEBUG ("Encoding %s", iconvtablename[_ICONV_ISO8859_1]);
      giconv = _get_iconv (_ICONV_ISO8859_1, _ICONV_UTF8);

      GST_INFO ("Trying encoding ISO 8859-1");
      converted_str = convert_to_utf8 (text, length, 1, giconv, FALSE, &error);
      if (error != NULL) {
        GST_WARNING
            ("Could not convert string while assuming encoding ISO 8859-1: %s",
            error->message);
        g_error_free (error);
        goto failed;
      }
    } else if (encoding == _ICONV_ISO6937) {

      /* The first part of ISO 6937 is identical to ISO 8859-9, but
       * they differ in the second part. Some channels don't
       * provide the first byte that indicates ISO 8859-9 encoding.
       * If decoding from ISO 6937 failed, we try ISO 8859-9 here.
       */
      giconv = _get_iconv (_ICONV_ISO8859_9, _ICONV_UTF8);

      GST_INFO ("Trying encoding ISO 8859-9");
      converted_str = convert_to_utf8 (text, length, 0, giconv, FALSE, &error);
      if (error != NULL) {
        GST_WARNING
            ("Could not convert string while assuming encoding ISO 8859-9: %s",
            error->message);
        g_error_free (error);
        goto failed;
      }
    } else
      goto failed;
  }

beach:
  return converted_str;

failed:
  {
    text += start_text;
    return g_strndup (text, length - start_text);
  }
}
示例#18
0
/* This function parses the header of an email that
 * can be read from an open file handle.
 * Note, T2D: There are a few short cuts that should be fixed.
 */
int
parse_header(FILE *fp, email_hdr_t *eh, char *errstr)
{
	int len;
	int blank;

  /* various flags to indicate what header parts were already seen */
	int header= 0;
	int gotsubj= 0;
	int gotenc= 0;
	int gotset= 0;
	int waitbound= 0;

	char *p;
	char *s;
	char buf[CDDBBUFSIZ];
	char buf2[CDDBBUFSIZ];
	char set[CDDBBUFSIZ];
	char enc[CDDBBUFSIZ];

	eh->eh_flags = 0;
	eh->eh_class = EC_NONE;
	eh->eh_charset = CC_US_ASCII;
	eh->eh_encoding = CE_7BIT;

	while(get_hdr_line(buf, sizeof(buf), fp)) {
		strcpy(buf2, buf); /* pointless copy */
		blank = (buf[0] == '\n' ||
			 (buf[0] == '\r' && buf[1] == '\n'));

		if(!strncmp(buf, from, strlen(from)) ||
		    !strncmp(buf, x_cddbd_from, strlen(rpath)) ||
		    (!header && !strncmp(buf, rpath, strlen(rpath)))) {
			p = buf;
			while(*p != '\0' && !isspace(*p))
				p++;
			while(*p != '\0' && isspace(*p))
				p++;

			if(*p != '\0') {
				cpy_sender(p, eh->eh_rcpt, eh->eh_to,
				    eh->eh_host);

				eh->eh_flags |= EH_RCPT;
				header++;
			}

			continue;
		}

		if(!header)
			continue;

		if(!strncmp(buf, subj, strlen(subj))) {
			p = buf;
			while(*p != '\0' && !isspace(*p))
				p++;
			while(*p != '\0' && isspace(*p))
				p++;

			if(sscanf(p, cmd_send_subj, eh->eh_serial))
				eh->eh_class = EC_COMMAND;
			else if(sscanf(p, sub_send_subj, eh->eh_category,
			    &eh->eh_discid) == 2)
				eh->eh_class = EC_SUBMIT;
			else {
				strcpy(errstr, "Malformed subject in header");
				return EE_ERROR;
			}

			strip_crlf(p);
			strncpy(eh->eh_subj, p, sizeof(eh->eh_subj));
			eh->eh_subj[sizeof(eh->eh_subj) - 1] = '\0';

			gotsubj++;
			eh->eh_flags |= EH_SUBJECT;
		}
		else if(!cddbd_strncasecmp(buf, x_cddbd_crc,
		    strlen(x_cddbd_crc))) {
			/* Skip junk. */
			p = buf + strlen(x_cddbd_crc) + 1;
			while(*p != '\0' && !isxdigit(*p))
				p++;

			/* Find the crc. */
			if(sscanf(p, "%255[a-zA-Z0-9]", buf2) != 1 ||
			    strlen(buf2) != CDDBXCRCLEN) {
				cddbd_snprintf(errstr, CDDBBUFSIZ,
				    "Malformed %s in header", x_cddbd_crc);

				return EE_ERROR;
			}

			strcpy(eh->eh_crc, buf2);
			eh->eh_flags |= EH_CRC;
		}
		else if(!cddbd_strncasecmp(buf, x_cddbd_echo,
		    strlen(x_cddbd_echo))) {
			/* Skip junk. */
			p = buf + strlen(x_cddbd_echo) + 1;
			while(*p != '\0' && isspace(*p))
				p++;

			/* Find the echo string. */
			if(sscanf(p, "%255[^\n\r]", buf2) != 1 ||
			    strlen(buf2) > CDDBXECHOLEN) {
				cddbd_snprintf(errstr, CDDBBUFSIZ,
				    "Invalid %s in header", x_cddbd_echo);

				return EE_ERROR;
			}

			strcpy(eh->eh_echo, buf2);
			eh->eh_flags |= EH_ECHO;
		}
		else if(!cddbd_strncasecmp(buf, x_cddbd_note,
		    strlen(x_cddbd_note))) {
			/* Skip junk. */
			p = buf + strlen(x_cddbd_note) + 1;
			while(*p != '\0' && isspace(*p))
				p++;

			/* Find the note string. */
			if(sscanf(p, "%255[^\n\r]", buf2) != 1 ||
			    strlen(buf2) > CDDBXNOTELEN) {
				cddbd_snprintf(errstr, CDDBBUFSIZ,
				    "Invalid %s in header", x_cddbd_note);

				return EE_ERROR;
			}

			strcpy(eh->eh_note, buf2);
			eh->eh_flags |= EH_NOTE;
		}
		else if(!cddbd_strncasecmp(buf, content_type,
		    strlen(content_type))) {
			if((p = cddbd_strcasestr(buf, charset)) != 0) {
				/* Skip junk. */
				p += strlen(charset);
				while(*p != '\0' && !isalpha(*p) &&
				    !isdigit(*p))
					p++;

				/* Find the charset. */
				if(sscanf(p, "%255[a-zA-Z0-9_-]", set) != 1) {
					cddbd_snprintf(errstr, CDDBBUFSIZ,
					    "Malformed %s in header",
					    content_type);
					return EE_ERROR;
				}

				gotset++;
			}

			if((p = cddbd_strcasestr(buf, boundary)) != 0) {
				/* Skip junk. */
				p += strlen(boundary);
				while(*p != '\0') {
					if(*p == '=') {
						p++;
						break;
					}
					p++;
				}

				if(*p ==  '"') {
					p++;
					s = "%255[^\"]";
				}
				else
					s = "%255s";

				/* Find the boundary string. */
				if(sscanf(p, s, eh->eh_boundary) != 1) {
					cddbd_snprintf(errstr, CDDBBUFSIZ,
					    "Malformed %s in header",
					    content_type);
					return EE_ERROR;
				}

				len = strlen(eh->eh_boundary);
				if(eh->eh_boundary[len - 1] == '"' ||
				    eh->eh_boundary[len - 1] == ';')
					eh->eh_boundary[len - 1] = '\0';

				eh->eh_flags |= EH_BOUNDARY;

				waitbound++;
			}
		}
		else if(!cddbd_strncasecmp(buf, content_encoding,
		    strlen(content_encoding))) {
			/* Skip junk. */
			p = buf + strlen(content_encoding);
			while(*p != '\0' && !isalpha(*p) && !isdigit(*p))
				p++;

			/* Find the encoding. */
			if(sscanf(p, "%[a-zA-Z0-9_-]", enc) != 1) {
				cddbd_snprintf(errstr, CDDBBUFSIZ,
				    "Malformed %s in header", content_encoding);

				return EE_ERROR;
			}

			gotenc++;
		}
		else if(waitbound && strstr(buf, eh->eh_boundary) != NULL) {
			waitbound = 0;
		}
		else if(blank && !waitbound) {
			get_rmt_hostname(-1, eh->eh_host, rhost);

			if(!gotsubj) {
				strcpy(errstr, "Missing subject in header");
				return EE_ERROR;
			}

			if(gotenc && !get_encoding(enc, eh, errstr))
				return EE_ERROR;

			if(gotset && !get_charset(set, eh, errstr))
				return EE_ERROR;

			return EE_OK;
		}
	}

	if(waitbound)
		strcpy(errstr, "Missing boundary string");
	else
		strcpy(errstr, "Malformed email header");

	return EE_ERROR;
}
示例#19
0
static PurpleDesktopItem *
ditem_load (FILE *df,
	    gboolean no_translations,
	    const char *uri)
{
	int state;
	char CharBuffer [1024];
	char *next = CharBuffer;
	int c;
	Encoding encoding;
	PurpleDesktopItem *item;
	Section *cur_section = NULL;
	char *key = NULL;
	gboolean old_kde = FALSE;

	encoding = get_encoding (df);
	if (encoding == ENCODING_UNKNOWN) {
		fclose(df);
		/* spec says, don't read this file */
		printf ("Unknown encoding of .desktop file");

		return NULL;
	}

	/* Rewind since get_encoding goes through the file */
	if (fseek(df, 0L, SEEK_SET)) {
		fclose(df);
		/* spec says, don't read this file */
		printf ("fseek() error on .desktop file");
		return NULL;
	}

	item = _purple_desktop_item_new ();
	item->modified = FALSE;

	/* Note: location and mtime are filled in by the new_from_file
	 * function since it has those values */

#define PURPLE_DESKTOP_ITEM_OVERFLOW (next == &CharBuffer [sizeof(CharBuffer)-1])

	state = FirstBrace;
	while ((c = getc (df)) != EOF) {
		if (c == '\r')		/* Ignore Carriage Return */
			continue;
		
		switch (state) {

		case OnSecHeader:
			if (c == ']' || PURPLE_DESKTOP_ITEM_OVERFLOW) {
				*next = '\0';
				next = CharBuffer;

				/* keys were inserted in reverse */
				if (cur_section != NULL &&
				    cur_section->keys != NULL) {
					cur_section->keys = g_list_reverse
						(cur_section->keys);
				}
				if (strcmp (CharBuffer,
					    "KDE Desktop Entry") == 0) {
					/* Main section */
					cur_section = NULL;
					old_kde = TRUE;
				} else if (strcmp (CharBuffer,
						   "Desktop Entry") == 0) {
					/* Main section */
					cur_section = NULL;
				} else {
					cur_section = g_new0 (Section, 1);
					cur_section->name =
						g_strdup (CharBuffer);
					cur_section->keys = NULL;
					item->sections = g_list_prepend
						(item->sections, cur_section);
				}
				state = IgnoreToEOL;
			} else if (c == '[') {
				/* FIXME: probably error out instead of ignoring this */
			} else {
				*next++ = c;
			}
			break;

		case IgnoreToEOL:
		case IgnoreToEOLFirst:
			if (c == '\n'){
				if (state == IgnoreToEOLFirst)
					state = FirstBrace;
				else
					state = KeyDef;
				next = CharBuffer;
			}
			break;

		case FirstBrace:
		case KeyDef:
		case KeyDefOnKey:
			if (c == '#') {
				if (state == FirstBrace)
					state = IgnoreToEOLFirst;
				else
					state = IgnoreToEOL;
				break;
			}

			if (c == '[' && state != KeyDefOnKey){
				state = OnSecHeader;
				next = CharBuffer;
				g_free (key);
				key = NULL;
				break;
			}
			/* On first pass, don't allow dangling keys */
			if (state == FirstBrace)
				break;
	    
			if ((c == ' ' && state != KeyDefOnKey) || c == '\t')
				break;
	    
			if (c == '\n' || PURPLE_DESKTOP_ITEM_OVERFLOW) { /* Abort Definition */
				next = CharBuffer;
				state = KeyDef;
				break;
			}
	    
			if (c == '=' || PURPLE_DESKTOP_ITEM_OVERFLOW){
				*next = '\0';

				g_free (key);
				key = g_strdup (CharBuffer);
				state = KeyValue;
				next = CharBuffer;
			} else {
				*next++ = c;
				state = KeyDefOnKey;
			}
			break;

		case KeyValue:
			if (PURPLE_DESKTOP_ITEM_OVERFLOW || c == '\n'){
				*next = '\0';

				insert_key (item, cur_section, encoding,
					    key, CharBuffer, old_kde,
					    no_translations);

				g_free (key);
				key = NULL;

				state = (c == '\n') ? KeyDef : IgnoreToEOL;
				next = CharBuffer;
			} else {
				*next++ = c;
			}
			break;

		} /* switch */
	
	} /* while ((c = getc_unlocked (f)) != EOF) */
	if (c == EOF && state == KeyValue) {
		*next = '\0';

		insert_key (item, cur_section, encoding,
			    key, CharBuffer, old_kde,
			    no_translations);

		g_free (key);
		key = NULL;
	}

#undef PURPLE_DESKTOP_ITEM_OVERFLOW

	/* keys were inserted in reverse */
	if (cur_section != NULL &&
	    cur_section->keys != NULL) {
		cur_section->keys = g_list_reverse (cur_section->keys);
	}
	/* keys were inserted in reverse */
	item->keys = g_list_reverse (item->keys);
	/* sections were inserted in reverse */
	item->sections = g_list_reverse (item->sections);

	/* sanitize some things */
	sanitize (item, uri);

	/* make sure that we set up the type */
	setup_type (item, uri);

	fclose (df);

	return item;
}
	0x97, 0x40, 0x01, 0x27, 0xD1, 0x41, 0xCC, 0xEB, 0x4D, 0xB7,
	0x04, 0xC4, 0x91, 0xE0, 0x95, 0x8A, 0x43, 0x26, 0x2D, 0x1F,
	0x88, 0xA0, 0xD8
);

START_TEST(test_bliss_signature_fail)
{
	bliss_param_set_t set2 = { .id = BLISS_B_II };
	bliss_param_set_t *set;
	bliss_signature_t *signature;
	chunk_t encoding;
	int k;

	signature = bliss_signature_create(&set2);
	ck_assert(signature);
	encoding = signature->get_encoding(signature);
	ck_assert(encoding.len == 0);
	signature->destroy(signature);

	signature  = bliss_signature_create_from_data(&set2, data);
	ck_assert(!signature);

	set = bliss_param_set_get_by_id(BLISS_B_I);
	ck_assert(set);

	for (k = 0; k < data.len - 2; k++)
	{
		chunk_t fragment = { data.ptr, k };

		signature  = bliss_signature_create_from_data(set, fragment);
		ck_assert(!signature);
示例#21
0
/*
    Load the image from disk and convert it into a sequence of flux levels.
*/
bool ti99_floppy_format::load(io_generic *io, UINT32 form_factor, floppy_image *image)
{
	int cell_size = 0;
	int sector_count = 0;
	int heads = 0;
	int log_track_count = 0;
	determine_sizes(io, cell_size, sector_count, heads, log_track_count);

	if (cell_size == 0) return false;

	// Be ready to hold a track of up to 36 sectors (with gaps and marks)
	UINT8 trackdata[13000];

	int maxtrack, maxheads;
	image->get_maximal_geometry(maxtrack, maxheads);

	int file_size = io_generic_size(io);
	int track_size = get_track_size(cell_size, sector_count);

	// Problem: If the disk is improperly formatted, the track count will be
	// wrong. For instance, a disk could be reformatted to single-side.
	// We assume there is no disk with single side format beyond 40 tracks.
	if ((heads==1) && (file_size > track_size*40))
		heads = 2;

	int phys_track_count = file_size / (track_size*heads);

	// Some disks are known to have an incomplete header.
	// PASCAL disks have a track count of 0.
	if (log_track_count==0) log_track_count = phys_track_count;

	if (TRACE) osd_printf_info("ti99_dsk: logical tracks = %d, physical tracks = %d\n", log_track_count, phys_track_count);

	if (phys_track_count > maxtrack)
	{
		osd_printf_error("ti99_dsk: Floppy disk has too many tracks for this drive.\n");
		return false;
	}

	// Is this the first time that this disk is read in an 80-track drive?
	bool double_step = ((log_track_count * 2) <= maxtrack);
	bool first_time_double = ((phys_track_count * 2) <= maxtrack);

	if (first_time_double)
	{
		osd_printf_warning("ti99_dsk: 40-track image in an 80-track drive. On save, image size will double.\n");
	}

	int acttrack;

	// Read the image
	for (int head=0; head < heads; head++)
	{
		for (int track=0; track < phys_track_count; track++)
		{
			if (double_step && !first_time_double) acttrack = track/2;
			else acttrack = track;

			load_track(io, trackdata, head, track, acttrack, sector_count, phys_track_count, cell_size);

			if (first_time_double)
			{
				// Create two tracks from each medium track. This reflects the
				// fact that the drive head will find the same data after
				// a single step
				if (get_encoding(cell_size)==floppy_image::FM)
				{
					generate_track_fm(track*2, head, cell_size, trackdata, image);
					generate_track_fm(track*2+1, head, cell_size, trackdata, image);
				}
				else
				{
					generate_track_mfm(track*2, head, cell_size, trackdata, image);
					generate_track_mfm(track*2+1, head, cell_size, trackdata, image);
				}
			}
			else
			{
				// Normal tracks
				if (get_encoding(cell_size)==floppy_image::FM)
					generate_track_fm(track, head, cell_size, trackdata, image);
				else
					generate_track_mfm(track, head, cell_size, trackdata, image);
			}
		}
	}

	return true;
}
示例#22
0
bool ti99_floppy_format::save(io_generic *io, floppy_image *image)
{
	int act_track_size = 0;

	UINT8 bitstream[500000/8];
	UINT8 trackdata[9216];   // max size

	int cellsizes[] = { 2000, 4000, 1000, 2000 };

	// Do we use double-stepping?
	// If our image was loaded into a 80-track drive, we will always write 80 tracks.
	int maxtrack, maxheads;
	image->get_maximal_geometry(maxtrack, maxheads);

	if (maxtrack > 80) maxtrack = 80;
	else
	{
		if (maxtrack > 35 && maxtrack < 80) maxtrack = 40;
		else maxtrack = 35;
	}

	int attempt = 0;
	int sector[36];
	int maxsect = 18;
	bool write = true;

	// We expect a bitstream of length 50000 for FM and 100000 for MFM
	for(int head=0; head < 2; head++)
	{
		int track = 0;
		while (track < maxtrack)
		{
			int cell_size = cellsizes[attempt];
			int encoding = get_encoding(cell_size);
			int track_size = get_track_size(cell_size, 36); // max number of sectors

			// Retrieve the cells from the flux sequence
			generate_bitstream_from_track(track, head, cell_size, bitstream, act_track_size, image);

			// Maybe the track has become longer due to moving splices
			if (act_track_size > 200000000/cell_size) act_track_size = 200000000/cell_size;

			int marks = decode_bitstream(bitstream, trackdata, sector, act_track_size, encoding, (encoding==floppy_image::FM)? 0xff:0x4e, track_size);

			if (track==0)
			{
				if (head==0)
				{
					// Find the highest sector in the track
					// This is only needed for the SDF format
					int i=35;
					while (i>=0 && sector[i]==-1) i--;

					if (i>18) maxsect = 36;
					else
					{
						if (i>16) maxsect = 18;
						else
						{
							if (i>9) maxsect = 16;
							else maxsect = 9;
						}
					}
					if (TRACE) osd_printf_info("ti99_dsk: Sectors/track: %d\n", maxsect);

					// We try different cell sizes until we find a fitting size.
					// If this fails, we fall back to a size of 2000 ns
					// The criterion for a successful decoding is that we find at least
					// 6 ID or data address marks on the track. It is highly unlikely
					// to find so many marks with a wrong cell size.
					if (marks < 6 && attempt < 4)
					{
						if (TRACE) osd_printf_verbose("ti99_dsk: Decoding with cell size %d failed.\n", cell_size);
						attempt++;
						write = false;
					}
					else write = true;
				}
				else
				{
					if (marks < 6)
					{
						if (min_heads()==1)
						{
							if (TRACE) osd_printf_info("ti99_dsk: We don't have a second side and the format allows for single-sided recording.\n");
							return true;
						}
						else
						{
							osd_printf_warning("ti99_dsk: No second side, but this format requires two-sided recording. Saving empty tracks.\n");
						}
					}
				}
			}

			if (write)
			{
				if (TRACE)
				{
					if (head == 0 && track == 0)
					{
						if (marks >=6) { if (TRACE) osd_printf_info("ti99_dsk: Decoding with cell size %d successful.\n", cell_size); }
						else osd_printf_info("ti99_dsk: No address marks found on track 0. Assuming MFM format.\n");
					}
				}
				// Save to the file
				write_track(io, trackdata, sector, track, head, maxsect, maxtrack, track_size);
				track++;
			}
		}
	}

	return true;
}
示例#23
0
int 	__au_open_write	(SF_PRIVATE *psf)
{	AU_FMT			au_fmt ;
	unsigned int	dword, encoding, format, subformat, big_endian_file ;
	
	format = psf->sf.format & SF_FORMAT_TYPEMASK ;
	subformat = psf->sf.format & SF_FORMAT_SUBMASK ;
	if (format == SF_FORMAT_AU)
		big_endian_file = 1 ;
	else if (format == SF_FORMAT_AULE)
		big_endian_file = 0 ;
	else
		return	SFE_BAD_OPEN_FORMAT ;
		
	if (subformat == SF_FORMAT_ULAW || subformat == SF_FORMAT_ALAW)
		psf->bytewidth = 1 ;
	else
		psf->bytewidth = BITWIDTH2BYTES (psf->sf.pcmbitwidth) ;
		
	psf->endian      = big_endian_file ? SF_ENDIAN_BIG : SF_ENDIAN_LITTLE ;
	psf->sf.seekable = SF_TRUE ;
	psf->blockwidth  = psf->bytewidth * psf->sf.channels ;
 	psf->dataoffset  = 6 * sizeof (dword) ;
	psf->datalength  = psf->blockwidth * psf->sf.samples ;
	psf->filelength  = psf->datalength + psf->dataoffset ;
	psf->error       = 0 ;

	encoding = get_encoding (subformat, psf->bytewidth * 8) ;
	if (! encoding)
	{	printf ("Weird! Bad encoding.\n") ;
		return	SFE_BAD_OPEN_FORMAT ;
		} ;

	au_fmt.dataoffset = 24 ;
	au_fmt.datasize   = psf->datalength ;
	au_fmt.encoding   = encoding ;
	au_fmt.samplerate = psf->sf.samplerate ;
	au_fmt.channels   = psf->sf.channels ;
	
	if (__CPU_IS_LITTLE_ENDIAN__ && big_endian_file)
		endswap_au_fmt (&au_fmt) ;
	else if (__CPU_IS_BIG_ENDIAN__ && ! big_endian_file)
		endswap_au_fmt (&au_fmt) ;
	
	
	dword = big_endian_file ? DOTSND_MARKER : DNSDOT_MARKER ;	/* Marker */
	fwrite (&dword, sizeof (dword), 1, psf->file) ;
	
	fwrite (&au_fmt, sizeof (AU_FMT), 1, psf->file) ;
	
	psf->close = (func_close) __au_close ;
	
	switch (encoding)
	{	case  1 :	/* 8-but Ulaw encoding. */
					psf->write_short  = (func_short)  __ulaw_write_s2ulaw ;
					psf->write_int    = (func_int)    __ulaw_write_i2ulaw ;
					psf->write_double = (func_double) __ulaw_write_d2ulaw ;
					break ;
	
		case  2 :	/* 8-bit linear PCM. */
					psf->write_short  = (func_short)  __pcm_write_s2sc ;
					psf->write_int    = (func_int)    __pcm_write_i2sc ;
					psf->write_double = (func_double) __pcm_write_d2sc ;
					break ;

		case  3 :	/* 16-bit linear PCM. */
					if (big_endian_file)
					{	psf->write_short  = (func_short)  __pcm_write_s2bes ;
						psf->write_int    = (func_int)    __pcm_write_i2bes ;
						psf->write_double = (func_double) __pcm_write_d2bes ;
						}
					else
					{	psf->write_short  = (func_short)  __pcm_write_s2les ;
						psf->write_int    = (func_int)    __pcm_write_i2les ;
						psf->write_double = (func_double) __pcm_write_d2les ;
						} ;
					break ;

		case  4 :	/* 24-bit linear PCM */
					if (big_endian_file)
					{	psf->write_short  = (func_short)  __pcm_write_s2bet ;
						psf->write_int    = (func_int)    __pcm_write_i2bet ;
						psf->write_double = (func_double) __pcm_write_d2bet ;
						}
					else
					{	psf->write_short  = (func_short)  __pcm_write_s2let ;
						psf->write_int    = (func_int)    __pcm_write_i2let ;
						psf->write_double = (func_double) __pcm_write_d2let ;
						} ;
					break ;

		case  5 :	/* 32-bit linear PCM. */
					if (big_endian_file)
					{	psf->write_short  = (func_short)  __pcm_write_s2bei ;
						psf->write_int    = (func_int)    __pcm_write_i2bei ;
						psf->write_double = (func_double) __pcm_write_d2bei ;
						}
					else
					{	psf->write_short  = (func_short)  __pcm_write_s2lei ;
						psf->write_int    = (func_int)    __pcm_write_i2lei ;
						psf->write_double = (func_double) __pcm_write_d2lei ;
						} ;
					break ;
					
		case  27 :	/* 8-but Alaw encoding. */
					psf->write_short  = (func_short)  __alaw_write_s2alaw ;
					psf->write_int    = (func_int)    __alaw_write_i2alaw ;
					psf->write_double = (func_double) __alaw_write_d2alaw ;
					break ;
	
		default :   break ;
		} ;
		
	return 0 ;
} /* au_open_write */
示例#24
0
void
SocketInstance::reconnect_callback (void)
{
    m_peer_id = m_factory->create_peer_instance (get_encoding ());
}
示例#25
0
/* Fonction qui interprete une requette passee en parametre dans input,
   fournit le chemin du fichier demandé dans path,
   fournit le header dans output,
   index 
   précise s'il faut conserver la connection dans keep_alive (0/1) */
static int interpreter(client_t *client, int *index, int *keep_alive, char *encoding, int *endRequete)
{
  request_t requete = {0, {0}, {0}, client->ip, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, 0, 0, 0, 0, 0};
  reponse_t reponse = {200, {0}, {NULL, 0, 0}, 0, 10};
  reponse.header = bufinit(&reponse.header, BUFFER_SIZE, " 200 OK", 9);
  reponse.header.use = 9;
  reponse.time = time(NULL);

#ifndef NDEBUG
  printf("<interpreter> requete entrante :\n'%s'\n", client->requete.ptr);
#endif

  int ret = decode(&client->requete, &requete);
  if(ret != 0){
    erreur(ret, &reponse);
  }

  if(requete.method == 1){ // GET
    getVarGET(&requete, &client->vars);
  }else if(requete.method == 3){ // POST
    int size = min(requete.content_length, client->requete.use - *endRequete);
    bufstrcpy(&client->vars, client->requete.ptr+(*endRequete), size);
  }

  printf("variables : %s\n", client->vars.ptr);

  /* Validation du path */
  if(valider_path(&requete, &reponse)){
    erreur(404, &reponse);
  }

  
  struct stat file_stat;
  if(reponse.code == 200){
    if(stat(requete.path, &file_stat) == -1){
      perror("stats");
      erreur(500, &reponse);
    }
  }
    
  /*droit de lecture */
  if(reponse.code == 200){
    if(!valider_access(file_stat.st_mode)){
      erreur(403, &reponse);
    }
  }

  /* Authentification */
  if(reponse.code == 200){
    if(passFileExistInDir(requete.path)){
      char login[30] = {0};
      char password[15] = {0};
      
      if(!getAuthorization(requete.authorization, login, password) &&
	 !getLoginAndPassword(requete.query, login, password)){
	erreur(401,&reponse);
	requete.keep_alive = 0;
      }else{
	char pass_path[SMALL_BUFF];
	getPassFilePath(requete.path,pass_path,isDir(&file_stat));
	if(!authentifier(login,password,pass_path)){
	  
	  erreur(401,&reponse);
	  requete.keep_alive = 0;
	}
      }
    }
    
    /* Get content type*/
    getContentType(&requete, &reponse, &file_stat);
    if(requete.method == 2){
      *index = 4; // methode HEAD 
    }else{
      *index = requete.index;
    }
  }
  
  bufstrcpy(&client->path, requete.path, strlen(requete.path));
  
  /* On creer le header dans output */
  encoder(&client->reponse, &reponse, &requete);

  if(strlen(requete.encoding) > 0){
    get_encoding(requete.encoding,encoding);
  }

  makeLog(&requete,&reponse);

  *keep_alive = requete.keep_alive;
  *endRequete += requete.content_length;

  bufkill(&reponse.header);

  return reponse.code;
}
示例#26
0
文件: winapi.l.c 项目: ignacio/winapi
/// get the current text encoding.
// @return either `CP_ACP` or `CP_UTF8`
// @function get_encoding
def get_encoding () {
  lua_pushinteger(L, get_encoding());
  return 1;
}
示例#27
0
static int revert_or_cherry_pick(int argc, const char **argv)
{
	unsigned char head[20];
	struct commit *base, *next, *parent;
	int i;
	char *oneline, *reencoded_message = NULL;
	const char *message, *encoding;
	const char *defmsg = xstrdup(git_path("MERGE_MSG"));

	git_config(git_default_config);
	me = action == REVERT ? "revert" : "cherry-pick";
	setenv(GIT_REFLOG_ACTION, me, 0);
	parse_args(argc, argv);

	/* this is copied from the shell script, but it's never triggered... */
	if (action == REVERT && !no_replay)
		die("revert is incompatible with replay");

	if (no_commit) {
		/*
		 * We do not intend to commit immediately.  We just want to
		 * merge the differences in, so let's compute the tree
		 * that represents the "current" state for merge-recursive
		 * to work on.
		 */
		if (write_cache_as_tree(head, 0, NULL))
			die ("Your index file is unmerged.");
	} else {
		if (get_sha1("HEAD", head))
			die ("You do not have a valid HEAD");
		if (read_cache() < 0)
			die("could not read the index");
		if (index_is_dirty())
			die ("Dirty index: cannot %s", me);
		discard_cache();
	}

	if (!commit->parents)
		die ("Cannot %s a root commit", me);
	if (commit->parents->next) {
		/* Reverting or cherry-picking a merge commit */
		int cnt;
		struct commit_list *p;

		if (!mainline)
			die("Commit %s is a merge but no -m option was given.",
			    sha1_to_hex(commit->object.sha1));

		for (cnt = 1, p = commit->parents;
		     cnt != mainline && p;
		     cnt++)
			p = p->next;
		if (cnt != mainline || !p)
			die("Commit %s does not have parent %d",
			    sha1_to_hex(commit->object.sha1), mainline);
		parent = p->item;
	} else if (0 < mainline)
		die("Mainline was specified but commit %s is not a merge.",
		    sha1_to_hex(commit->object.sha1));
	else
		parent = commit->parents->item;

	if (!(message = commit->buffer))
		die ("Cannot get commit message for %s",
				sha1_to_hex(commit->object.sha1));

	/*
	 * "commit" is an existing commit.  We would want to apply
	 * the difference it introduces since its first parent "prev"
	 * on top of the current HEAD if we are cherry-pick.  Or the
	 * reverse of it if we are revert.
	 */

	msg_fd = hold_lock_file_for_update(&msg_file, defmsg, 1);

	encoding = get_encoding(message);
	if (!encoding)
		encoding = "utf-8";
	if (!git_commit_encoding)
		git_commit_encoding = "utf-8";
	if ((reencoded_message = reencode_string(message,
					git_commit_encoding, encoding)))
		message = reencoded_message;

	oneline = get_oneline(message);

	if (action == REVERT) {
		char *oneline_body = strchr(oneline, ' ');

		base = commit;
		next = parent;
		add_to_msg("Revert \"");
		add_to_msg(oneline_body + 1);
		add_to_msg("\"\n\nThis reverts commit ");
		add_to_msg(sha1_to_hex(commit->object.sha1));
		add_to_msg(".\n");
	} else {
		base = parent;
		next = commit;
		set_author_ident_env(message);
		add_message_to_msg(message);
		if (no_replay) {
			add_to_msg("(cherry picked from commit ");
			add_to_msg(sha1_to_hex(commit->object.sha1));
			add_to_msg(")\n");
		}
	}

	if (merge_recursive(sha1_to_hex(base->object.sha1),
				sha1_to_hex(head), "HEAD",
				sha1_to_hex(next->object.sha1), oneline) ||
			write_cache_as_tree(head, 0, NULL)) {
		add_to_msg("\nConflicts:\n\n");
		read_cache();
		for (i = 0; i < active_nr;) {
			struct cache_entry *ce = active_cache[i++];
			if (ce_stage(ce)) {
				add_to_msg("\t");
				add_to_msg(ce->name);
				add_to_msg("\n");
				while (i < active_nr && !strcmp(ce->name,
						active_cache[i]->name))
					i++;
			}
		}
		if (commit_lock_file(&msg_file) < 0)
			die ("Error wrapping up %s", defmsg);
		fprintf(stderr, "Automatic %s failed.%s\n",
			me, help_msg(commit->object.sha1));
		exit(1);
	}
	if (commit_lock_file(&msg_file) < 0)
		die ("Error wrapping up %s", defmsg);
	fprintf(stderr, "Finished one %s.\n", me);

	/*
	 *
	 * If we are cherry-pick, and if the merge did not result in
	 * hand-editing, we will hit this commit and inherit the original
	 * author date and name.
	 * If we are revert, or if our cherry-pick results in a hand merge,
	 * we had better say that the current user is responsible for that.
	 */

	if (!no_commit) {
		/* 6 is max possible length of our args array including NULL */
		const char *args[6];
		int i = 0;
		args[i++] = "commit";
		args[i++] = "-n";
		if (signoff)
			args[i++] = "-s";
		if (!edit) {
			args[i++] = "-F";
			args[i++] = defmsg;
		}
		args[i] = NULL;
		return execv_git_cmd(args);
	}
	free(reencoded_message);

	return 0;
}
示例#28
0
    void tsp_vrplc::compute_constraints_impl(constraint_vector &c, const decision_vector& x) const 
    {
        decision_vector::size_type n_cities = get_n_cities();

        switch( get_encoding() ) 
        {
            case FULL:
            {
                // 1 - We set the equality constraints
                for (size_t i = 0; i < n_cities; i++) {
                    c[i] = 0;
                    c[i+n_cities] = 0;
                    for (size_t j = 0; j < n_cities; j++) 
                    {
                        if(i==j) continue; // ignoring main diagonal
                        decision_vector::size_type rows = compute_idx(i, j, n_cities);
                        decision_vector::size_type cols = compute_idx(j, i, n_cities);
                        c[i] += x[rows];
                        c[i+n_cities] += x[cols];
                    }
                    c[i] = c[i]-1;
                    c[i+n_cities] = c[i+n_cities]-1;
                }

                //2 - We set the inequality constraints
                //2.1 - First we compute the uj (see http://en.wikipedia.org/wiki/Travelling_salesman_problem#Integer_linear_programming_formulation)
                //      we start always out tour from the first city, without loosing generality
                size_t next_city = 0,current_city = 0;
                std::vector<int> u(n_cities);
                for (size_t i = 0; i < n_cities; i++) 
                {
                    u[current_city] = i+1;
                    for (size_t j = 0; j < n_cities; j++) 
                    {
                        if (current_city==j) continue;
                        if (x[compute_idx(current_city, j, n_cities)] == 1) 
                        {
                            next_city = j;
                            break;
                        }
                    }
                    current_city = next_city;
                }
                int count=0;
                for (size_t i = 1; i < n_cities; i++) {
                    for (size_t j = 1; j < n_cities; j++) 
                    {
                        if (i==j) continue;
                        c[2*n_cities+count] = u[i]-u[j] + (n_cities+1) * x[compute_idx(i, j, n_cities)] - n_cities;
                        count++;
                    }
                }
                break;
            }
            case RANDOMKEYS:
                break;
            case CITIES:
            {
                std::vector<population::size_type> range(n_cities);
                for (std::vector<population::size_type>::size_type i=0; i<range.size(); ++i) 
                {
                    range[i]=i;
                }
                c[0] = !std::is_permutation(x.begin(),x.end(),range.begin());
                break;
            }
        }
        return;
    }
static GCharsetConverter *
guess_encoding (GeditDocumentOutputStream *stream,
		const void                *inbuf,
		gsize                      inbuf_size)
{
	GCharsetConverter *conv = NULL;

	if (inbuf == NULL || inbuf_size == 0)
	{
		stream->priv->is_utf8 = TRUE;
		return NULL;
	}

	if (stream->priv->encodings != NULL &&
	    stream->priv->encodings->next == NULL)
	{
		stream->priv->use_first = TRUE;
	}

	/* We just check the first block */
	while (TRUE)
	{
		const GeditEncoding *enc;

		if (conv != NULL)
		{
			g_object_unref (conv);
			conv = NULL;
		}

		/* We get an encoding from the list */
		enc = get_encoding (stream);

		/* if it is NULL we didn't guess anything */
		if (enc == NULL)
		{
			break;
		}

		gedit_debug_message (DEBUG_UTILS, "trying charset: %s",
				     gedit_encoding_get_charset (stream->priv->current_encoding->data));

		if (enc == gedit_encoding_get_utf8 ())
		{
			gsize remainder;
			const gchar *end;
			
			if (g_utf8_validate (inbuf, inbuf_size, &end) ||
			    stream->priv->use_first)
			{
				stream->priv->is_utf8 = TRUE;
				break;
			}

			/* Check if the end is less than one char */
			remainder = inbuf_size - (end - (gchar *)inbuf);
			if (remainder < 6)
			{
				stream->priv->is_utf8 = TRUE;
				break;
			}

			continue;
		}

		conv = g_charset_converter_new ("UTF-8",
						gedit_encoding_get_charset (enc),
						NULL);

		/* If we tried all encodings we use the first one */
		if (stream->priv->use_first)
		{
			break;
		}

		/* Try to convert */
		if (try_convert (conv, inbuf, inbuf_size))
		{
			break;
		}
	}

	if (conv != NULL)
	{
		g_converter_reset (G_CONVERTER (conv));
	}

	return conv;
}
示例#30
0
void TEWidget::inputMethodEvent( QInputMethodEvent * e)  // is a virtual function
{
  static int c=0;
  qDebug("in TEWidget::inputMethodEvent : %d", c++);
  static QString preedit_string;
  preedit_string=e->preeditString();
  if (!e->commitString().isEmpty())
  {
    qDebug("!e->commitString() : %d", e->commitString().length() );
    static QString commit_string;
    commit_string=e->commitString();
    const char *ch=commit_string.toStdString().c_str();
    for (int i=0 ; i < commit_string.toStdString().length() ; ++i)
      qDebug("ch[i] : %x", ch[i]);
    //input_text_->setText(preedit_string+"*"+commit_string);
    input_text_->clear();
    //input_text_->setText("test"+commit_string);
    //input_text_->set_text("commit"+e->commitString() );
    //input_text_->show();
    //onRcvBlock();


    // QKeyEvent ( Type type, int key, Qt::KeyboardModifiers modifiers, const QString & text = QString(), bool autorep = false, ushort count = 1 )
#if 0
    int encode=get_encoding();
    QTextDecoder* decoder;
    QTextCodec *codec;
    QByteArray qba;
    const QChar * qchar;



    if ( get_input_encoding() == DS::BIG5)
    {
      codec = QTextCodec::codecForName("BIG5");
      //qDebug("(encoding==DS::BIG5)");
      //qDebug("(encoding==DS::UTF8)");
      qDebug("in encode==DS::BIG5");

    }
    if ( get_input_encoding() == DS::UTF8)
    {
      codec = QTextCodec::codecForName("UTF-8");
      //qchar= e->commitString().unicode();
      //codec = QTextCodec::codecForName("UTF-8");
      //qDebug("in encode==DS::UTF8");
      //qba=e->commitString().toUtf8();
    }



    QByteArray ba = codec->fromUnicode(ev->text());
    char *ba_data=ba.data();
    emit sndBlock(ba_data ,strlen(ba_data));    


    //for (int i=0 ; i < e->commitString().length() ; ++i)
      //qDebug("qchar[i] : %x", qchar[i].unicode () );
      //qDebug("qchar[i] : %x", i);
    decoder = codec->makeDecoder();
    const char *c_str= e->commitString().toStdString().c_str();
      qDebug("c_str len: %d", strlen(c_str));

    for (int i=0 ; i < strlen(c_str) ; ++i)
      qDebug("c_str[i]: %x", c_str[i]);

    commit_string=decoder->toUnicode(c_str, strlen(c_str));
#endif
    //QString str(qba);

    QKeyEvent* ke = new QKeyEvent(QEvent::KeyPress, 0, Qt::NoModifier, commit_string);

    //actSel=0; // Key stroke implies a screen update, so TEWidget won't
              // know where the current selection is.

    emit keyPressedSignal(ke); // expose
    //preedit_string="";
    //commit_string="";
    //sleep(3);
  }
  else
  {
    qDebug("e->commitString()");
    #if 0
    if (!preedit_string.isEmpty())
    {
    input_text_->set_text("preedit"+preedit_string);
    input_text_->show();
    }
    #endif
  }
#if 0
  if (!preedit_string.isEmpty())
  {
    input_text_->set_text(preedit_string);
    input_text_->show();
  }
#endif
}