示例#1
0
文件: util.C 项目: Sidnicious/sfslite
int
open_file (const str &nm, int flags)
{
  char *s = strdup (nm.cstr ());
  int rc = 0;

  rc = mkdir_p (s);
  if (rc == 0)
    rc = ::open (nm.cstr (), flags, 0666);

  if (s) free (s);
  return rc;
}
示例#2
0
文件: escape.C 项目: LeadsPlus/okws
str
html_filter_t::run (const str &in)
{
  if (!in) return in;

  const char *cp = in.cstr ();
  const char *ep = in.cstr () + in.len ();
  if (*ep != '\0') { return NULL; }

  buf_t buf;

  while (*cp) {
    
    str add;
    
    switch (*cp) {
    case '<':
      handle_tag (&buf, &cp, ep);
      break;
	
    case '&':
      {
	const char *inner = cp + 1;
	const char *etp = strchr (inner, ';');
	if (etp && is_safe_entity (inner, etp)) {
	  buf.add_s (str (cp, etp - cp + 1));
	  cp = etp + 1;
	} else {
	  buf.add_cc ("&amp;");
	  cp ++;
	}
      }
      break;
      
    case '#':
      buf.add_cc ("&#35;");
      cp ++;
      break;
      
    case '"':
      buf.add_cc ("&quot;");
      cp ++;
      
    default:
      buf.add_ch (*cp++);
      break;
      
    }
  }
  return buf.to_str ();
}
//
// Name:        UseActorWeapon()
// Parameters:  const str &weaponName
// Description: Sets the weapon to be active, and attaches it
//
void CombatSubsystem::UseActorWeapon(const str& weaponName, weaponhand_t hand)
{
  //First see if we just want to put our current item away
  if (!stricmp(weaponName.c_str(), "none"))
  {
    act->DeactivateWeapon(WEAPON_LEFT);
    act->DeactivateWeapon(WEAPON_RIGHT);
    act->DeactivateWeapon(WEAPON_DUAL);
    act->AddStateFlag(StateFlagChangedWeapon);
    act->ClearTorsoAnim();
    _activeWeapon.weapon = nullptr;

    return;
  }

  auto weapon = dynamic_cast<Weapon *>(act->FindItem(weaponName.c_str()));

  // Check to see if player has the weapon
  if (!weapon)
  {
    act->warning("CombatSubsystem::UseActorWeapon", "Actor does not have weapon %s", weaponName.c_str());
    return;
  }

  // If we don't already have an active weapon, just go ahead and make this one active
  if (!_activeWeapon.weapon)
  {
    _activeWeapon.weapon = weapon;
    _activeWeapon.hand = hand;
    _activeWeapon.weapon->SetOwner(act);
    act->ActivateWeapon(weapon, hand);
    act->AddStateFlag(StateFlagChangedWeapon);
    return;
  }

  // See if we are already using this weapon
  if (weapon == _activeWeapon.weapon && hand == _activeWeapon.hand)
    return;

  // Well, we have a weapon in the same hand, put away the weapon thats there.
  auto oldweapon = act->GetActiveWeapon(hand);
  if (oldweapon)
    act->DeactivateWeapon(hand);

  // Activate this weapon
  _activeWeapon.weapon = weapon;
  _activeWeapon.hand = hand;
  _activeWeapon.weapon->SetOwner(act);
  act->ActivateWeapon(weapon, hand);
  act->AddStateFlag(StateFlagChangedWeapon);
}
示例#4
0
int
start_logger (const str &priority, const str &tag, const str &line, 
	      const str &logfile, int flags, mode_t mode)
{
  str logger;
#ifdef PATH_LOGGER
  logger = PATH_LOGGER;
#endif

  if (logger) {
    const char *av[] = { NULL, "-p", NULL, "-t", NULL, NULL, NULL };
    av[0] = const_cast<char *> (logger.cstr ());
    av[2] = const_cast<char *> (priority.cstr ());
  
    if (line)
      av[5] = const_cast<char *> (line.cstr ());
    else
      av[5] = "log started";
    
    if (tag)
      av[4] = const_cast<char *> (tag.cstr ());
    else 
      av[4] = "";
    
    pid_t pid;
    int status;
    if ((pid = spawn (av[0], av, 0, 0, errfd)) < 0) {
      warn ("%s: %m\n", logger.cstr ());
      return start_log_to_file (line, logfile, flags, mode);
    } 
    if (waitpid (pid, &status, 0) <= 0 || !WIFEXITED (status) || 
	WEXITSTATUS (status)) 
      return start_log_to_file (line, logfile, flags, mode);
    
    int fds[2];
    if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0)
      fatal ("socketpair: %m\n");
    close_on_exec (fds[0]);
    if (fds[1] != 0)
      close_on_exec (fds[1]);
    
    av[5] = NULL;
    if (spawn (av[0], av, fds[1], 0, 0) >= 0) {
      close (fds[1]);
      return fds[0];
    } else {
      warn ("%s: %m\n", logger.cstr ());
    }
  } 
  return start_log_to_file (line, logfile, flags, mode);
}
示例#5
0
/**
 * Returns the config version of the cluster pointed at by the connection string.
 *
 * @return OK if version found successfully, error status if something bad happened.
 */
Status getConfigVersion(CatalogManager* catalogManager, VersionType* versionInfo) {
    try {
        versionInfo->clear();

        ScopedDbConnection conn(grid.shardRegistry()->getConfigServerConnectionString(), 30);

        unique_ptr<DBClientCursor> cursor(_safeCursor(conn->query("config.version", BSONObj())));

        bool hasConfigData = conn->count(ShardType::ConfigNS) ||
            conn->count(DatabaseType::ConfigNS) || conn->count(CollectionType::ConfigNS);

        if (!cursor->more()) {
            // Version is 1 if we have data, 0 if we're completely empty
            if (hasConfigData) {
                versionInfo->setMinCompatibleVersion(UpgradeHistory_UnreportedVersion);
                versionInfo->setCurrentVersion(UpgradeHistory_UnreportedVersion);
            } else {
                versionInfo->setMinCompatibleVersion(UpgradeHistory_EmptyVersion);
                versionInfo->setCurrentVersion(UpgradeHistory_EmptyVersion);
            }

            conn.done();
            return Status::OK();
        }

        BSONObj versionDoc = cursor->next();
        auto versionInfoResult = VersionType::fromBSON(versionDoc);
        if (!versionInfoResult.isOK()) {
            conn.done();

            return Status(ErrorCodes::UnsupportedFormat,
                          stream() << "invalid config version document " << versionDoc
                                   << versionInfoResult.getStatus().toString());
        }
        *versionInfo = versionInfoResult.getValue();

        if (cursor->more()) {
            conn.done();

            return Status(ErrorCodes::RemoteValidationError,
                          stream() << "should only have 1 document "
                                   << "in config.version collection");
        }
        conn.done();
    } catch (const DBException& e) {
        return e.toStatus();
    }

    return Status::OK();
}
示例#6
0
void
dhash_download::add_data (str sdata, int off)
{
    int len = sdata.len ();
    const char *data = sdata.cstr ();

    if ((unsigned)(off + len) > (u_int)buf_len)
        fail (strbuf ("bad chunk: off %d, len %d, block %ld",
                      off, len, buf_len));
    else {
        memcpy (buffer + off, data, len);
        bytes_read += len;
    }
}
示例#7
0
void dfs(str& s, int u) {
   vis[u] = true;
   for (auto child: v[u]) if (!vis[child]) {
      str* cs = new(str);
      dfs(*cs, child);
      merge(s, *cs);
      delete(cs);
   }
   s.insert(c[u], 1);
   for (auto query: q[u]) {
      int pos = query.second, k = query.first;
      result[pos] = s.query(k);
   }
}
示例#8
0
文件: dsl_out.cpp 项目: xkp/XKP
      std::vector<str> load_lines(const str& s)
        {
          std::vector<str> result;
          size_t curr = 0;
          for(size_t i = 0; i < s.length(); i++)
            {
              if (s[i] == '\n')
                {
                  result.push_back( s.substr(curr, i) );
                  curr = i;
                }
            }

          return result;
        }
示例#9
0
文件: gencfile.C 项目: okws/sfslite
static str
makehdrname (str fname)
{
  strbuf hdr;
  const char *p;

  if ((p = strrchr (fname.cstr(), '/')))
    p++;
  else p = fname.cstr();

  hdr.buf (p, strlen (p) - 1);
  hdr.cat ("h");

  return hdr;
}
示例#10
0
文件: str.cpp 项目: sookee/rconteam
str::size_type extract_delimited_text(const str& in, const str& d1, const str& d2, str& out, size_t pos)
{
	if(pos == str::npos)
		return pos;

	size_t end = pos;

	if((pos = in.find(d1, pos)) != str::npos)
		if((end = in.find(d2, (pos = pos + d1.size()))) != str::npos)
		{
			out = in.substr(pos, end - pos);
			return end + d2.size();
		}
	return str::npos;
}
示例#11
0
bool TFxSprite::Init(str particleSystem, TFxSpriteAnimTask * task, bool reset )
{
	TFxSpriteRef s = GetRef();

	if (reset)
	{
		mDrawnOnce = false;
		s->GetLPS()->NewScript();
	}

	if (particleSystem.has_data())
	{
		s->GetLPS()->RegisterDataSource("dLocus",&s->mEmitterLocus);
		s->GetLPS()->RegisterDataSource("dUp",&s->mEmitterUp);

		if( !s->GetLPS()->Load(particleSystem) )
		{
			return false;
		}
		s->mName = particleSystem ;
		if (!task)
		{
			task = ((TFxSpriteAnimTask*)GetAnimTask());
		}
		task->mSpriteList.insert( s );
	}
	return true;
}
Status CatalogManagerReplicaSet::getChunks(const Query& query,
                                           int nToReturn,
                                           vector<ChunkType>* chunks) {
    chunks->clear();

    auto configShard = grid.shardRegistry()->getShard("config");
    auto readHostStatus = configShard->getTargeter()->findHost(kConfigReadSelector);
    if (!readHostStatus.isOK()) {
        return readHostStatus.getStatus();
    }

    auto findStatus = grid.shardRegistry()->exhaustiveFind(readHostStatus.getValue(),
                                                           NamespaceString(ChunkType::ConfigNS),
                                                           query.obj,
                                                           boost::none);  // no limit
    if (!findStatus.isOK()) {
        return findStatus.getStatus();
    }

    for (const BSONObj& obj : findStatus.getValue()) {
        auto chunkRes = ChunkType::fromBSON(obj);
        if (!chunkRes.isOK()) {
            chunks->clear();
            return {ErrorCodes::FailedToParse,
                    stream() << "Failed to parse chunk with id ("
                             << obj[ChunkType::name()].toString()
                             << "): " << chunkRes.getStatus().toString()};
        }

        chunks->push_back(chunkRes.getValue());
    }

    return Status::OK();
}
Status CatalogManagerReplicaSet::getAllShards(vector<ShardType>* shards) {
    const auto configShard = grid.shardRegistry()->getShard("config");
    const auto readHost = configShard->getTargeter()->findHost(kConfigReadSelector);
    if (!readHost.isOK()) {
        return readHost.getStatus();
    }

    auto findStatus = grid.shardRegistry()->exhaustiveFind(readHost.getValue(),
                                                           NamespaceString(ShardType::ConfigNS),
                                                           BSONObj(),     // no query filter
                                                           boost::none);  // no limit
    if (!findStatus.isOK()) {
        return findStatus.getStatus();
    }

    for (const BSONObj& doc : findStatus.getValue()) {
        auto shardRes = ShardType::fromBSON(doc);
        if (!shardRes.isOK()) {
            shards->clear();
            return {ErrorCodes::FailedToParse,
                    stream() << "Failed to parse shard with id ("
                             << doc[ShardType::name()].toString()
                             << "): " << shardRes.getStatus().toString()};
        }

        shards->push_back(shardRes.getValue());
    }

    return Status::OK();
}
示例#14
0
文件: rxx.C 项目: gildafnai82/craq
int
split (vec<str> *out, rxx pat, str expr, size_t lim, bool emptylast)
{
  const char *p = expr;
  const char *const e = p + expr.len ();
  size_t n;
  if (out)
    out->clear ();

  // check p < e to see that we're not dealing with an empty
  // string (especially since x? matches "").
  for (n = 0; p < e && n + 1 < lim; n++) {
    if (!pat._exec (p, e - p, 0)) {
      return 0;
    }
    if (!pat.success ())
      break;
    if (out)
      out->push_back (str (p, pat.start (0)));
    p += max (pat.end (0), 1);
  }

  if (lim && (p < e || emptylast)) {
    n++;
    if (out) {
      out->push_back (str (p, e - p));
    }
  }
  return n;
}
StatusWith<CollectionType> CatalogManagerReplicaSet::getCollection(const std::string& collNs) {
    auto configShard = grid.shardRegistry()->getShard("config");

    auto readHostStatus = configShard->getTargeter()->findHost(kConfigReadSelector);
    if (!readHostStatus.isOK()) {
        return readHostStatus.getStatus();
    }

    auto statusFind =
        grid.shardRegistry()->exhaustiveFind(readHostStatus.getValue(),
                                             NamespaceString(CollectionType::ConfigNS),
                                             BSON(CollectionType::fullNs(collNs)),
                                             1);

    if (!statusFind.isOK()) {
        return statusFind.getStatus();
    }

    const auto& retVal = statusFind.getValue();
    if (retVal.empty()) {
        return Status(ErrorCodes::NamespaceNotFound,
                      stream() << "collection " << collNs << " not found");
    }

    invariant(retVal.size() == 1);

    return CollectionType::fromBSON(retVal.front());
}
示例#16
0
文件: util.cpp 项目: vis15/fractions
bool isNumeric(const str& token)
{
    if(token == "")
        return false;

    for(uint i=0; i<token.length(); i++)
    {
        const char num = token.at(i);
        if(i == 0 && Util::toString(num) == kSubtract() && token.size() > 1) //token.size > 1 because "-" is not a number
            continue;
        if(isdigit(num) == false && Util::toString(num) != kDot())
            return false;
    }

    return true;
}
示例#17
0
Writer xml_writer::create_node(const str& name)
  {
    TiXmlElement* node = new TiXmlElement(name.c_str());
    node_->LinkEndChild( node );
    
    return Writer( new xml_writer(node, types_) );
  }
示例#18
0
文件: pub3debug.C 项目: aosmith/okws
 void
 dumpable_t::s_dump (dumper_t *d, str prfx, const dumpable_t *obj)
 {
   if (prfx) { d->dump (strbuf ("%s ", prfx.cstr ()), false); }
   if (obj) { obj->dump (d); }
   else { d->dump ("(null)", true); }
 }
示例#19
0
 str escape(str t)
 {
     //обработка escape последовательностей в строке
    str  res="";
    t=t+" ";
         for(int i=1;i<=t.Length()-1;i++)
                  if(t[i]=='\\' && t[i+1]=='\\')
                          res=res+t[i++] ;
                  else
                  if(t[i]=='\\' && t[i+1]=='n')
                  {
                          res=res+'\n';
                          i++;
                  }
                  else
                   if(t[i]=='\\' && t[i+1]=='s')
                  {
                          res=res+' ';
                          i++;
                  }
                  else
                  if(t[i]=='\\')
                          res=res+t[++i];
                  else
                          res=res+t[i];

        return res;
 }
示例#20
0
static str
pathexpand (str lookup, str *sch, int recdepth = 0)
{
  char readlinkbuf [PATH_MAX + 1];
  str s;

  struct stat sb;
  while (1) {
//     warn << print_indent (recdepth) << "looking up " << lookup << "\n";

    stat (lookup.cstr (), &sb);
    
    errno = 0;
    if ((s = slashsfs2sch (lookup))) {
//       warn << print_indent (recdepth) << "--------FOUND-----: " 
// 	   << s << "\n";
      *sch = s;
      return lookup;
    }
    else {
      int len = readlink (lookup, readlinkbuf, PATH_MAX);
      if (len < 0) {
// 	warn << print_indent (recdepth) << "readlink of " 
// 	     << lookup << " returned error: " << strerror (errno) << "\n";
	return lookup;
      }
      readlinkbuf[len] = 0;
//       warn << print_indent (recdepth) << "readlink of " << lookup 
// 	   << " returned " << readlinkbuf << "\n";
      lookup = mk_readlinkres_abs (readlinkbuf, lookup);
    }
  }
}
示例#21
0
//for looking up self-certifying hostnames in certprog interface
int
path2sch (str path, str *sch)
{
  *sch = NULL;

  if (!path || !path.len ())
    return ENOENT;
  
  if (sfs_parsepath (path)) {
    *sch = path;
    return 0;
  }

  str lookup;
  if (path[0] == '/')
    lookup = path;
  else
    lookup = strbuf () << sfsroot << "/" << path;

  str result = pathiterate (lookup, sch, 0, true);
  //  warn << "RESULT: " << result << "\n";

  if (errno == EINVAL)
    errno = 0;
//   if (*sch)
//     warn << "RETURNING: " << *sch << "\n";
//   warn << "RETURNING ERROR CODE: " << strerror (errno) << "\n";
  return errno;
}
StatusWith<string> CatalogManagerReplicaSet::getTagForChunk(const std::string& collectionNs,
                                                            const ChunkType& chunk) {
    auto configShard = grid.shardRegistry()->getShard("config");
    auto readHostStatus = configShard->getTargeter()->findHost(kConfigReadSelector);
    if (!readHostStatus.isOK()) {
        return readHostStatus.getStatus();
    }

    BSONObj query =
        BSON(TagsType::ns(collectionNs) << TagsType::min() << BSON("$lte" << chunk.getMin())
                                        << TagsType::max() << BSON("$gte" << chunk.getMax()));
    auto findStatus = grid.shardRegistry()->exhaustiveFind(
        readHostStatus.getValue(), NamespaceString(TagsType::ConfigNS), query, BSONObj(), 1);
    if (!findStatus.isOK()) {
        return findStatus.getStatus();
    }

    const auto& docs = findStatus.getValue();
    if (docs.empty()) {
        return string{};
    }

    invariant(docs.size() == 1);
    BSONObj tagsDoc = docs.front();

    const auto tagsResult = TagsType::fromBSON(tagsDoc);
    if (!tagsResult.isOK()) {
        return {ErrorCodes::FailedToParse,
                stream() << "error while parsing " << TagsType::ConfigNS << " document: " << tagsDoc
                         << " : " << tagsResult.getStatus().toString()};
    }
    return tagsResult.getValue().getTag();
}
示例#23
0
文件: err.C 项目: gildafnai82/craq
void
setprogname (char *argv0)
{
  char *cp;
  if ((cp = strrchr (argv0, '/')))
    cp++;
  else
    cp = argv0;
  /* Libtool shell wrappers leave lt- in argv[0] */
  if (cp[0] == 'l' && cp[1] == 't' && cp[2] == '-')
    progname = cp + 3;
  else
    progname = cp;
  if (cp > argv0)
    progdir.setbuf (argv0, cp - argv0);
  else
    progdir = NULL;
#ifdef DMALLOC
  if (dmalloc_logpath) {
    str logname;
    const char *p;
    if (!(p = strrchr (dmalloc_logpath, '/')) || !(p = strrchr (p, '.')))
      p = dmalloc_logpath + strlen (dmalloc_logpath);
    logname = strbuf ("%.*s.%s", int (p - dmalloc_logpath), dmalloc_logpath,
		      progname.cstr ());
    static char *lp;
    if (lp)
      xfree (lp);
    lp = xstrdup (logname);
    dmalloc_logpath = lp;
  }
#endif /* DMALLOC */
}
示例#24
0
文件: amysql.C 项目: imosts/flume
sth_t
mysql_t::prepare (const str &q, u_int l_opts)
{
  if (l_opts & AMYSQL_DEFAULT)
    l_opts = opts;
  sth_t *rp = cache[q];
  if (rp) return (*rp);

  sth_t r = NULL;
  if (l_opts & AMYSQL_PREPARED) {
#if defined(HAVE_MYSQL_BINDFUNCS) && defined(HAVE_MYSQL_BIND)
    MYSQL_STMT *s = mysql_stmt_init (&mysql);
    if (!s) {
      err = strbuf ("MySQL ran out of memory on statment init: ")
	<< mysql_error (&mysql);
      return NULL;
    }

    if (mysql_stmt_prepare (s, q, q.len ())) {
      err = strbuf ("could not prepare query (") 
	<< q << "): " << mysql_error (&mysql);
      return NULL;
    }
    r = sth_prepared_t::alloc (s, q, l_opts);
#endif // HAVE_MYSQL_BINDFUNCS && HAVE_MYSQL_BIND
  } else {
    ptr<sth_parsed_t> r2 = sth_parsed_t::alloc (&mysql, q, l_opts);
    if (!r2->parse ())
      return NULL;
    r = r2;
  }
  if (!(l_opts & AMYSQL_NOCACHE))
    cache.insert (q, r);
  return r;
}
示例#25
0
文件: spawn.C 项目: maxtaco/sfslite
str
fix_exec_path (str path, str dir)
{
  const char *prog = strrchr (path, '/');
  if (prog)
    return path;

  if (!dir)
    dir = execdir;
  path = dir << "/" << path;
  prog = strrchr (path, '/');
  if (!prog)
    panic ("No EXECDIR for unqualified path %s.\n", path.cstr ());

#ifdef MAINTAINER
  if (builddir && dir == execdir) {
    str np;
    np = builddir << prog;
    if (execok (np))
      return np;
    np = builddir << prog << prog;
    if (execok (np))
      return np;
    if (np = searchdir (builddir, prog))
      return np;
    if (np = searchdir (builddir << "/lib", prog))
      return np;
  }
#endif /* MAINTAINER */

  return path;
}
示例#26
0
void print_table(str s, const Ptable& T) {
	printf("%s", s.c_str()); printf("\n");
	int l = T.size();
	if (l==0) {
		printf("   ! Empty table\n");
		return;
	}
	int c = T[0].size();
	for (int i=0; i<l; i++) {
		if (T[i].size()!=c) {
			printf("   ! Table has different number of columns depending to the lines\n");
			return;
		}
	}
	str s0(" ",10);
	const char* space = s0.c_str();
	printf("%s", space);
	for (int j=0; j<c; j++) printf("%11d",j);
	printf("\n");
	for (int i=0; i<l; i++) {
		printf("%4d",i);
		for (int j=0; j<c; j++) printf("%11s",p2s(T[i][j]).c_str());
		printf("\n");
	}
	printf("\n");
}
示例#27
0
    virtual void str_(const str& value)
      {
        TiXmlElement* node = new TiXmlElement("string");
        node_->LinkEndChild( node );

        node->SetAttribute("value", value.c_str());
      }
示例#28
0
void Personality::SetBehaviorTendency( const str &packageName , float tendency )
{
	PackageTendency_t      pEntry;
	BehaviorPackageType_t  *package;
	PackageTendency_t      *checkEntry;
	
	for ( int i = 1 ; i <= PackageList.NumObjects() ; i++ )
	{
		package = PackageList.ObjectAt( i );
		
		if ( !Q_stricmp( packageName.c_str() , package->packageName.c_str() ) )
		{
			// We have a match, let's check to make sure we're not doubling up
			for ( int j = 1 ; j <= _PackageTendencies.NumObjects() ; j++ )
			{
				checkEntry = &_PackageTendencies.ObjectAt( j );
				
				if ( checkEntry->packageIndex == i )
				{
					checkEntry->tendency = tendency;
					return;
				}
				
			}
			
			// We don't have a match, so lets add the package
			pEntry.lastTendencyCheck = 0.0f;
			pEntry.tendency = tendency;
			pEntry.packageIndex = i;
			
			_PackageTendencies.AddObject( pEntry );
			return;
		}
	}   
}
示例#29
0
void print_hist(str s, int i0, List hist, bool latex) {
	str et = latex ? " & " : " | ";
	str slash = latex ? "\\\\ \n" : "\n";

	str rrr(10,'r');
	if (latex) printf("\\begin{table}[H]\\begin{center} \n \\caption{%s (interval %d)} \n \\begin{tabular}{%s}\n",s.c_str(),i0,rrr.c_str());
	else printf("%s (interval %d)\n",s.c_str(),i0);

	int size = hist.size();
	for (int i=0; i<size; i++) {
		str s = ((i+1)%10==0 || i==size-1) ? slash : et;
		printf("%4s %s",f(hist[i]).c_str(),s.c_str());
	}
	if (latex) printf("\\end{tabular}\\end{center}\\end{table} \n");
	fl();
}
示例#30
0
void
json_XDR_t::error_wrong_type (str s, ptr<const pub3::expr_t> x)
{
  str got = x->type_to_str ();
  strbuf msg ("got type %s; expected %s", got.cstr (), s.cstr ());
  error_generic (msg);
}