Example #1
0
  static size_t curl_read(char *data, size_t size, size_t nmemb, void *ctx) {
    CurlResource *ch = (CurlResource *)ctx;
    ReadHandler *t  = &ch->m_read;

    int length = -1;
    switch (t->method) {
    case PHP_CURL_DIRECT:
      if (!t->fp.isNull()) {
        int data_size = size * nmemb;
        String ret = t->fp->read(data_size);
        length = ret.size();
        if (length) {
          memcpy(data, ret.data(), length);
        }
      }
      break;
    case PHP_CURL_USER:
      {
        int data_size = size * nmemb;
        Variant ret = ch->do_callback(
          t->callback, make_packed_array(Resource(ch), t->fp, data_size));
        if (ret.isString()) {
          String sret = ret.toString();
          length = data_size < sret.size() ? data_size : sret.size();
          memcpy(data, sret.data(), length);
        }
        break;
      }
    }
    return length;
  }
Example #2
0
	String::size_type findAndMark(const String& search, const String& replaceWith, String::size_type cur)
	{
		ReplacementMark mark;
		mark.pos = String::npos;
		mark.len = search.size();
		mark.replaceWith = replaceWith;
		while (cur < source.size())
		{
			cur = source.find(search, cur);
			if (cur == String::npos)
				break;
			mark.pos = cur;
			cur += search.size();
			// check if previous or following character continue an identifier
			// in that case, skip this occurrence as it's part of a longer identifier
			if (mark.pos > 0)
			{
				char c = source[mark.pos-1];
				if (c == '_' || std::isalnum(c))
					continue;
			}
			if (mark.pos+1 < search.size())
			{
				char c = source[mark.pos+1];
				if (c == '_' || std::isalnum(c))
					continue;
			}
			replacements.push_back(mark);
		}
		if (mark.pos != String::npos)
			return mark.pos + search.size();
		else
			return String::npos;
	}
Example #3
0
vector<pair<size_t, size_t> > StupidMatch(
    const vector<String>& input, const String& toMatch)
{
    vector<pair<size_t, size_t> > matched;
    for (size_t start = 0; start < toMatch.size(); ++start)
    {
        for (size_t strIndex = 0; strIndex < input.size(); ++strIndex)
        {
            bool got = true;
            for (size_t i = 0; i < input[strIndex].size(); ++i)
            {
                if (start + i >= toMatch.size())
                {
                    got = false;
                    break;
                }
                if (input[strIndex][i] != toMatch[start + i])
                {
                    got = false;
                    break;
                }
            }
            if (got)
            {
                matched.emplace_back(start, strIndex);
            }
        }
    }
    std::sort(matched.begin(), matched.end());
    return matched;
}
Example #4
0
void Wikidiff2::printText(const String & input)
{
	size_t start = 0;
	size_t end = input.find_first_of("<>&");
	while (end != String::npos) {
		if (end > start) {
			result.append(input, start, end - start);
		}
		switch (input[end]) {
			case '<':
				result.append("&lt;");
				break;
			case '>':
				result.append("&gt;");
				break;
			default /*case '&'*/:
				result.append("&amp;");
		}
		start = end + 1;
		end = input.find_first_of("<>&", start);
	}
	// Append the rest of the string after the last special character
	if (start < input.size()) {
		result.append(input, start, input.size() - start);
	}
}
Example #5
0
void cv::viz::writeCloud(const String& file, InputArray cloud, InputArray colors, InputArray normals, bool binary)
{
    CV_Assert(file.size() > 4 && "Extension is required");
    String extension = file.substr(file.size()-4);

    vtkSmartPointer<vtkCloudMatSource> source = vtkSmartPointer<vtkCloudMatSource>::New();
    source->SetColorCloudNormals(cloud, colors, normals);

    vtkSmartPointer<vtkWriter> writer;
    if (extension == ".xyz")
    {
        writer = vtkSmartPointer<vtkXYZWriter>::New();
        vtkXYZWriter::SafeDownCast(writer)->SetFileName(file.c_str());
    }
    else if (extension == ".ply")
    {
        writer = vtkSmartPointer<vtkPLYWriter>::New();
        vtkPLYWriter::SafeDownCast(writer)->SetFileName(file.c_str());
        vtkPLYWriter::SafeDownCast(writer)->SetFileType(binary ? VTK_BINARY : VTK_ASCII);
        vtkPLYWriter::SafeDownCast(writer)->SetArrayName("Colors");
    }
    else if (extension == ".obj")
    {
        writer = vtkSmartPointer<vtkOBJWriter>::New();
        vtkOBJWriter::SafeDownCast(writer)->SetFileName(file.c_str());
    }
    else
        CV_Error(Error::StsError, "Unsupported format");

    writer->SetInputConnection(source->GetOutputPort());
    writer->Write();
}
Example #6
0
String Path::ExtractPathFromCmdLine(String& input)
{
	String r;
	input.Trim();
	bool q = input[0] == '"';
	size_t i = q ? 1 : 0;
	while(i < input.size())
	{
		if(q)
		{
			if(input[i] == '"')
			{
				break;
			}
		}
		else
		{
			if(input[i] == ' ')
			{
				break;
			}
		}
		r += input[i];
		i++;
	}
	input.erase(input.begin(), input.begin() + r.size() + (q ? 2 : 0));
	input.Trim();
	return r;
}
Example #7
0
bool MySQLStmtVariables::init_params(MYSQL_STMT *stmt, const String& types) {
    assert(m_arr.size() == types.size());

    for (int i = 0; i < types.size(); i++) {
        MYSQL_BIND *b = &m_vars[i];
        switch (types[i]) {
        case 'i':
            b->buffer_type = MYSQL_TYPE_LONGLONG;
            break;
        case 'd':
            b->buffer_type = MYSQL_TYPE_DOUBLE;
            break;
        case 's':
            b->buffer_type = MYSQL_TYPE_STRING;
            break;
        case 'b':
            b->buffer_type = MYSQL_TYPE_LONG_BLOB;
            break;
        default:
            assert(false);
        }
    }

    return !mysql_stmt_bind_param(stmt, m_vars);
}
Example #8
0
Variant HHVM_FUNCTION(vprintf, const Variant& vformat, const Variant& args) {
    String format = vformat.toString();
    String output = string_printf(format.data(), format.size(), args.toArray());
    if (output.isNull()) return false;
    g_context->write(output.data(), output.size());
    return output.size();
}
Example #9
0
String dami::convert(String data, ID3_TextEnc sourceEnc, ID3_TextEnc targetEnc)
{
  String target;
  if ((sourceEnc != targetEnc) && (data.size() > 0 ))
  {
#if !defined HAVE_ICONV_H
    target = oldconvert(data, sourceEnc, targetEnc);
#else
    const char* targetFormat = getFormat(targetEnc);
    const char* sourceFormat = getFormat(sourceEnc);
   
    iconv_t cd = iconv_open (targetFormat, sourceFormat);
    if (cd != (iconv_t) -1)
    {
      target = convert_i(cd, data);
      if (target.size() == 0)
      {
        //try it without iconv
        target = oldconvert(data, sourceEnc, targetEnc);
      }
    }
    else
    {
      target = oldconvert(data, sourceEnc, targetEnc);
    }
    iconv_close (cd);
#endif
  }
  return target;
}
Example #10
0
/**
 * @return path of parent directory, ending with a slash.
 * Returns empty string on error.
 */
static String FileGetParentDirectory(const String& fullPath)
{
	String path = fullPath;

	// Get path to parent directory.

	// The path name may end with a slash.
	char lastChar = path[path.size() - 1];
	if (lastChar == '/')
	{
		// In this case, strip off the ending slash.
		path = path.substr(0, path.size() - 1);
	}

	// Get last slash.
	int pos = path.findLastOf('/');
	if (String::npos == pos)
	{
		return "";
	}

	lprintfln("@@@@@@@ FileGetParentDirectory: %s", (path.substr(0, pos + 1)).c_str());

	// Return parent path, including the slash.
	return path.substr(0, pos + 1);
}
  void CompNovoIdentificationBase::getCIDSpectrumLight_(PeakSpectrum & spec, const String & sequence, DoubleReal prefix, DoubleReal suffix)
  {
    static DoubleReal h2o_mass = EmpiricalFormula("H2O").getMonoWeight();
    Peak1D p;
    DoubleReal b_pos(0.0 + prefix);
    DoubleReal y_pos(h2o_mass + suffix);
    for (Size i = 0; i != sequence.size() - 1; ++i)
    {
      char aa(sequence[i]);
      b_pos += aa_to_weight_[aa];

      char aa2(sequence[sequence.size() - i - 1]);
      y_pos += aa_to_weight_[aa2];

      if (b_pos > min_mz_ && b_pos < max_mz_)
      {
        p.setPosition(b_pos + Constants::PROTON_MASS_U);
        p.setIntensity(1.0f);
        spec.push_back(p);
      }

      if (y_pos > min_mz_ && y_pos < max_mz_)
      {
        p.setPosition(y_pos + Constants::PROTON_MASS_U);
        p.setIntensity(1.0f);
        spec.push_back(p);
      }
    }

    spec.sortByPosition();
    return;
  }
Example #12
0
String trimContentData(String const & path)
{
	if (path.size() < 2)
		return String();

	return path.substr(2, path.size() - 3);
}
Example #13
0
bool HHVM_FUNCTION(error_log, const String& message, int message_type /* = 0 */,
                              const Variant& destination /* = null */,
                              const Variant& extra_headers /* = null */) {
  // error_log() should not invoke the user error handler,
  // so we use Logger::Error() instead of raise_warning() or raise_error()
  switch (message_type) {
  case 0:
  {
    std::string line(message.data(),
                     // Truncate to 512k
                     message.size() > (1<<19) ? (1<<19) : message.size());
    Logger::Error(line);
    return true;
  }
  case 3:
  {
    // open for append only
    auto outfile = HHVM_FN(fopen)(destination.toString(), "a");
    if (outfile.isNull()) {
      Logger::Error("can't open error_log file!\n");
      return false;
    }
    HHVM_FN(fwrite)(outfile.toResource(), message);
    HHVM_FN(fclose)(outfile.toResource());
    return true;
  }
  case 2: // not used per PHP
  default:
    Logger::Error("error_log does not support message_type %d!", message_type);
    break;
  }
  return false;
}
Example #14
0
bool cutAfter(String &str, const String& pat)
{
    int pos = str.indexOf(pat);
    if(pos < 0) return false;
    pos += pat.size();
    str.remove(pos, str.size() - pos);
    return true;
}
Example #15
0
void FieldVisitorHash::operator() (const String & x) const
{
    UInt8 type = Field::Types::String;
    hash.update(reinterpret_cast<const char *>(&type), sizeof(type));
    size_t size = x.size();
    hash.update(reinterpret_cast<const char *>(&size), sizeof(size));
    hash.update(x.data(), x.size());
}
Example #16
0
String Directory::fixPath(String path)
{
	if(path.empty()) throw Exception("Empty path");	
  	if(path.size() >= 2 && path[path.size()-1] == Separator) path.resize(path.size()-1);
#ifdef WINDOWS
	if(path.size() == 2 && path[path.size()-1] == ':') path+= Separator;
#endif
	return path;
}
Example #17
0
int String::rfind(const String& s, int pos /* = 0 */,
                  bool caseSensitive /* = true */) const {
  if (empty()) return -1;
  if (s.size() == 1) {
    return rfind(*s.data(), pos, caseSensitive);
  }
  return string_rfind(m_str->data(), m_str->size(),
                      s.data(), s.size(), pos, caseSensitive);
}
Example #18
0
String findMarkedSegment(String segmented, const String& marker)
{
    if(!segmented.contains(marker)) return ""; // Not present.

    int pos = segmented.indexOf(marker);
    int end = findAnyMarker(segmented, pos + marker.size());
    if(end < 0) end = segmented.size();
    return segmented.mid(pos + marker.size(), end - pos - marker.size());
}
Example #19
0
static String HHVM_FUNCTION(mysql_escape_string,
                            const String& unescaped_string) {
  String new_str((size_t)unescaped_string.size() * 2 + 1, ReserveString);
  unsigned long new_len = mysql_escape_string(new_str.bufferSlice().begin(),
                                    unescaped_string.data(),
                                    unescaped_string.size());
  new_str.shrink(new_len);
  return new_str;
}
Example #20
0
 String ExpandToRight(const String & value, size_t count)
 {
     assert(count >= value.size());
     std::stringstream ss;
     ss << value;
     for(size_t i = value.size(); i < count; i++)
         ss << " ";
     return ss.str();
 }
Example #21
0
Variant f_range(CVarRef low, CVarRef high, CVarRef step /* = 1 */) {
  bool is_step_double = false;
  double dstep = 1.0;
  if (step.isDouble()) {
    dstep = step.toDouble();
    is_step_double = true;
  } else if (step.isString()) {
    int64_t sn;
    double sd;
    DataType stype = step.toString()->isNumericWithVal(sn, sd, 0);
    if (stype == KindOfDouble) {
      is_step_double = true;
      dstep = sd;
    } else if (stype == KindOfInt64) {
      dstep = (double)sn;
    } else {
      dstep = step.toDouble();
    }
  } else {
    dstep = step.toDouble();
  }
  /* We only want positive step values. */
  if (dstep < 0.0) dstep *= -1;
  if (low.isString() && high.isString()) {
    String slow = low.toString();
    String shigh = high.toString();
    if (slow.size() >= 1 && shigh.size() >=1) {
      int64_t n1, n2;
      double d1, d2;
      DataType type1 = slow->isNumericWithVal(n1, d1, 0);
      DataType type2 = shigh->isNumericWithVal(n2, d2, 0);
      if (type1 == KindOfDouble || type2 == KindOfDouble || is_step_double) {
        if (type1 != KindOfDouble) d1 = slow.toDouble();
        if (type2 != KindOfDouble) d2 = shigh.toDouble();
        return ArrayUtil::Range(d1, d2, dstep);
      }

      int64_t lstep = (int64_t) dstep;
      if (type1 == KindOfInt64 || type2 == KindOfInt64) {
        if (type1 != KindOfInt64) n1 = slow.toInt64();
        if (type2 != KindOfInt64) n2 = shigh.toInt64();
        return ArrayUtil::Range((double)n1, (double)n2, lstep);
      }

      return ArrayUtil::Range((unsigned char)slow.charAt(0),
                              (unsigned char)shigh.charAt(0), lstep);
    }
  }

  if (low.is(KindOfDouble) || high.is(KindOfDouble) || is_step_double) {
    return ArrayUtil::Range(low.toDouble(), high.toDouble(), dstep);
  }

  int64_t lstep = (int64_t) dstep;
  return ArrayUtil::Range(low.toDouble(), high.toDouble(), lstep);
}
Example #22
0
int SSLSocket::passwdCallback(char* buf, int num, int /*verify*/, void* data) {
  /* TODO: could expand this to make a callback into PHP user-space */
  SSLSocket *stream = (SSLSocket *)data;
  String passphrase = stream->m_context[s_passphrase].toString();
  if (!passphrase.empty() && passphrase.size() < num - 1) {
    memcpy(buf, passphrase.data(), passphrase.size() + 1);
    return passphrase.size();
  }
  return 0;
}
Example #23
0
/**
This function aligns the string table to a 4-byte boundary
@internalComponent
@released
@return Error status
@param aStr - string to be aligned
*/
void ElfProducer::AlignString(String& aStr) {

	if( aStr.size() %4 ){
		PLUCHAR	aPad = (PLUCHAR)(4 - (aStr.size() %4));

		while(aPad--) {
			aStr.insert(aStr.end(), 0);
		}
	}
}
Example #24
0
std::size_t String::roverlap(const String &y) const {
  std::size_t i = size() < y.size() ? size() : y.size();
  for (; i > 0; i--) {
    String s = prefix(i);
    String p = y.suffix(i);
    if (s == p) {
      return i;
    }
  }
  return i;
}
Example #25
0
int String::cmp(const String &y) const {
  if (size() != y.size()) {
    return size() < y.size() ? -1 : 1;
  }
  for (unsigned int i = 0; i < size(); ++i) {
    if (d_str[i] != y.d_str[i]) {
      return getUnsignedCharAt(i) < y.getUnsignedCharAt(i) ? -1 : 1;
    }
  }
  return 0;
}
Example #26
0
  char* rb_str_copied_ptr(VALUE self) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    String* str = c_as<String>(env->get_object(self));

    char* data = (char*)malloc(sizeof(char) * str->size() + 1);
    memcpy(data, str->c_str(), str->size());
    data[str->size()] = 0;

    return data;
  }
Example #27
0
bool HHVM_METHOD(XMLReader, XML,
                 const String& source,
                 const Variant& encoding /*= null_variant*/,
                 int64_t options /*= 0*/) {
  auto* data = Native::data<XMLReader>(this_);
  const String& str_encoding = encoding.isNull()
                            ? null_string
                            : encoding.toString();
  xmlParserInputBufferPtr inputbfr = xmlParserInputBufferCreateMem(
    source.c_str(), source.size(), XML_CHAR_ENCODING_NONE);

  if (inputbfr != nullptr) {
    char *uri = nullptr;
    String directory = g_context->getCwd();
    if (!directory.empty()) {
      if (directory[directory.size() - 1] != '/') {
        directory += "/";
      }
      uri = (char *) xmlCanonicPath((const xmlChar *) directory.c_str());
    }

    xmlTextReaderPtr reader = xmlNewTextReader(inputbfr, uri);

    if (reader != nullptr) {
      int ret = 0;
#if LIBXML_VERSION >= 20628
      ret = xmlTextReaderSetup(reader, nullptr, uri, str_encoding.data(),
                               options);
#endif
      if (ret == 0) {
        data->m_ptr = reader;
        data->m_input = inputbfr;

        if (uri) {
          xmlFree(uri);
        }

        return true;
      }
    }

    if (uri) {
      xmlFree(uri);
    }
  }

  if (inputbfr) {
    xmlFreeParserInputBuffer(inputbfr);
  }

  raise_warning("Unable to load source data");
  return false;
}
Example #28
0
Variant HHVM_FUNCTION(snappy_uncompress, const String& data) {
  size_t dsize;
  if (!snappy::GetUncompressedLength(data.data(), data.size(), &dsize)) {
    return false;
  }

  String s = String(dsize, ReserveString);
  if (!snappy::RawUncompress(data.data(), data.size(), s.mutableData())) {
    return false;
  }
  return s.setSize(dsize);
}
Example #29
0
CachedUnit createUnitFromString(const char* path,
                                const String& contents) {
  auto const md5 = MD5 {
    mangleUnitMd5(string_md5(contents.data(), contents.size())).c_str()
  };
  // Try the repo; if it's not already there, invoke the compiler.
  if (auto const unit = Repo::get().loadUnit(path, md5)) {
    return CachedUnit { unit, RDS::allocBit() };
  }
  auto const unit = compile_file(contents.data(), contents.size(), md5, path);
  return CachedUnit { unit, RDS::allocBit() };
}
Example #30
0
const char *ProjectileData::getScaledValue( void *obj, const char *data)
{

	S32 value = dAtoi(data);
   value = scaleValue(value, false);

   String stringData = String::ToString(value);
   char *strBuffer = Con::getReturnBuffer(stringData.size());
   dMemcpy( strBuffer, stringData, stringData.size() );

   return strBuffer;
}