Ejemplo n.º 1
0
Archivo: main.cpp Proyecto: CCJY/coliru
bool sentence_has_word( std::string sentence, std::string word )
{
    sentence = sanitize(sentence) ;

    word = trim( sanitize(word) ) ;
    if( word.size() > sentence.size() ) return false ;
    if( word.size() == sentence.size() ) return word == sentence ;

    auto pos = sentence.find( word + ' ' ) ; // check for word at the beginning
    if( pos == 0 ) return true ;

    pos = sentence.find( ' ' + word + ' ' ) ; // check for word in the middle
    if( pos != std::string::npos ) return true ;

    word = ' ' + word ;
    return sentence.substr( sentence.size() - word.size() ) == word  ; // check for word at the end
}
Ejemplo n.º 2
0
/**
 * AdvanceSelection in the list of text items - simple!
 */
int16_t ListWidget::advanceSelection(int16_t iAdv /*= 1*/)
{
  //DEBUG_PRINT("ListWidget::advanceSelection "); DEBUG_PRINTDEC(iAdv); DEBUG_PRINTLN();
  if(m_selectionMode != smSingleSelection)
    return LB_ERR;
  setCurSel(sanitize(getCurSel() + iAdv));
  return 0;
}
Ejemplo n.º 3
0
void
ComplexBufferObject::recv()
{
    complex<float>* pyData =
      reinterpret_cast<complex<float>*>(PyArray_DATA((PyArrayObject*)_obj));
    memcpy(_data + 1, pyData + 1, (_samples - 2) * sizeof(complex<float>));
    _data[0] = complex<float>(pyData[0].real(), pyData[_samples - 1].real());
    sanitize(_samples * 2 - 2, (float*)PyArray_DATA((PyArrayObject*)_obj));
}
Ejemplo n.º 4
0
// Test case: TestLookUp:1
// This test calls lookUp() for the condition where 
// the query has an OR operator. 
int TestLookUp1() {
  START_TEST_CASE;
  INVERTED_INDEX* testIndex = NULL;

  int wordHash;
  int wordHash2;
  testIndex = initStructure(testIndex);

  wordHash = hash1("dog") % MAX_NUMBER_OF_SLOTS;
  DocumentNode* docNode = NULL;
  docNode = newDocNode(docNode, 15, 1);

  WordNode* wordNode = NULL;
  wordNode = newWordNode(wordNode, docNode, "dog");
  testIndex->hash[wordHash] = wordNode;


  wordHash2 = hash1("cat") % MAX_NUMBER_OF_SLOTS;
  DocumentNode* docNode2 = NULL;
  docNode2 = newDocNode(docNode2, 20, 2);

  WordNode* wordNode2 = NULL;
  wordNode2 = newWordNode(wordNode2, docNode2, "cat");

  testIndex->hash[wordHash2] = wordNode2;

  char query[1000] = "dog OR cat";
  sanitize(query);

  char* temp[1000];
  BZERO(temp, 1000);

  char* queryList[2];
  BZERO(queryList, 2);

  curateWords(queryList, query);
  SHOULD_BE(strcmp(queryList[0],"dog") == 0);
  SHOULD_BE(strcmp(queryList[1],"OR") == 0);
  SHOULD_BE(strcmp(queryList[2],"cat") == 0);

  DocumentNode* saved[1000];
  BZERO(saved, 1000);
  lookUp(saved, queryList, testIndex);

  SHOULD_BE(saved[0]->document_id == docNode->document_id);
  SHOULD_BE(saved[0]->page_word_frequency == docNode->page_word_frequency);
  SHOULD_BE(saved[1]->document_id == docNode2->document_id);
  SHOULD_BE(saved[1]->page_word_frequency == docNode2->page_word_frequency);
  
  cleanUpList(saved);
  cleanUpQueryList(queryList);
  BZERO(saved, 1000);

  cleanUpIndex(testIndex);

  END_TEST_CASE;
}
Ejemplo n.º 5
0
/// Insert event in heap deterministically
void HeapNode::insertDeterministic(Event *e)
{
#ifdef EH_SANITIZE
  sanitize();
#endif
  CmiAssert(this != NULL);
  CmiAssert(e->timestamp > this->e->timestamp || (e->timestamp == this->e->timestamp && e->evID >= this->e->evID));
  HeapNode *eh;
  if (left == NULL) {  // make it the left subheap
    eh = new HeapNode(e, 1, NULL, NULL);
    left = eh;
    subheapsize += 1;
  }
  else if (right == NULL) {  // make it the right subheap
    eh = new HeapNode(e, 1, NULL, NULL);
    right = eh;
    subheapsize += 1;
  }
  else if ((e->timestamp < left->e->timestamp) ||
	   ((e->timestamp == left->e->timestamp) &&
	    (e->evID <= left->e->evID))) { // make root of left subtree
    eh = new HeapNode(e, left->subheapsize+1, left, NULL);
    left = eh;
    subheapsize += 1;
  }
  else if ((e->timestamp < right->e->timestamp) ||
	   ((e->timestamp == right->e->timestamp) &&
	    (e->evID <= right->e->evID))) { // make root of right subtree
    eh = new HeapNode(e, right->subheapsize+1, right, NULL);
    right = eh;
    subheapsize += 1;
  }
  else if (left->subheapsize < right->subheapsize) { // insert in left subtree
    subheapsize += 1;
    left->insertDeterministic(e);
  }
  else { // insert in right subtree
    subheapsize += 1;
    right->insertDeterministic(e);
  }
#ifdef EH_SANITIZE
  sanitize();
#endif
}
Ejemplo n.º 6
0
int main(int argc, char** argv)
{
    struct sockaddr_in saddr;
    struct hostent *hp;
    char hostname[HOSTLEN];
    int sock_id, sock_fd;
    FILE *sock_fpi, *sock_fpo;
    FILE *pipe_fp;
    char dirname[BUFSIZ];
    char command[BUFSIZ];

    int dirlen, c;

    sock_id = socket( PF_INET, SOCK_STREAM, 0 );
    if ( sock_id == -1 )
        oops("socket");

    bzero((void *)&saddr, sizeof(saddr));
    gethostname( hostname, HOSTLEN );
    hp = gethostbyname( hostname );
    bcopy( (void *)hp->h_addr, (void *)&saddr.sin_addr, hp->h_length );
    saddr.sin_port = htons( PORTNUM );
    saddr.sin_family = AF_INET;
    if ( bind(sock_id, (struct sockaddr *)&saddr, sizeof(saddr)) != 0 )
        oops( "bind" );

    if ( listen(sock_id, 1) != 0 )
        oops("listen");

    while(1){
        sock_fd = accept(sock_id, NULL, NULL);
        if ( sock_fd == -1 )
            oops("accept");
        
        if ( (sock_fpi = fdopen( sock_fd, "r" )) == NULL )
            oops("fdopen reading");
        /* get a directory name from sock_fpi */
        if ( fgets(dirname, BUFSIZ - 5, sock_fpi) == NULL )
            oops("reading dirname");
        sanitize(dirname);

        if ( (sock_fpo = fdopen(sock_fd, "w")) == NULL )
            oops("fdopen writing");

        sprintf(command, "ls %s", dirname);
        if ( (pipe_fp = popen(command, "r")) == NULL )
            oops("popen");

        /* transfer data to socket from ls */
        while( (c = getc(pipe_fp)) != EOF)
            putc(c, sock_fpo);
        pclose(pipe_fp);
        fclose(sock_fpo);
        fclose(sock_fpi);
    }
}
Ejemplo n.º 7
0
/// Insert e in the queue in timestamp order
void eventQueue::InsertEvent(Event *e)
{
  tsOfLastInserted = e->timestamp;
  if(pose_config.deterministic)
    {
      InsertEventDeterministic(e);
    }
  else
    {
#ifdef EQ_SANITIZE
      sanitize();
#endif
      Event *tmp = backPtr->prev; // start at back of queue

      if (e->timestamp > largest) largest = e->timestamp;
      eventCount++;
      // check if new event should go on heap: 
      // greater than last timestamp in queue, 
      // or currentPtr is at back (presumably because heap is empty)
      //CkPrintf("Received event "); e->evID.dump(); CkPrintf(" at %d...\n", e->timestamp);
      if ((tmp->timestamp < e->timestamp || (tmp->timestamp == e->timestamp && tmp->evID < e->evID)) && (currentPtr != backPtr))
	eqh->InsertEvent(e); // insert in heap
      else { // tmp->timestamp > e->timestamp; insert in linked list
	if ((currentPtr != backPtr) && (currentPtr->timestamp > e->timestamp))
	  tmp = currentPtr; // may be closer to insertion point
	while (tmp->timestamp > e->timestamp || (tmp->timestamp == e->timestamp && tmp->evID > e->evID)) // search for position
	  tmp = tmp->prev;
	// insert e
	e->prev = tmp;
	e->next = tmp->next;
	e->next->prev = e;
	tmp->next = e;
	// if e is inserted before currPtr, move currPtr back to avoid rollback
	if ((currentPtr->prev == e) && (currentPtr->done < 1))
	  currentPtr = currentPtr->prev;
	else if ((currentPtr == backPtr) || (e->timestamp < currentPtr->timestamp || (e->timestamp == currentPtr->timestamp && e->evID < currentPtr->evID)))
	  SetRBevent(e);
      }
#ifdef EQ_SANITIZE
      sanitize();
#endif
    }
}
Ejemplo n.º 8
0
static long double getnum()
{
	while (*str==' ') str++;
#define prefix(name, func) if (!strnicmp(str, name, strlen(name))) { str+=strlen(name); long double val=getnum(); return sanitize(func); }
	prefix("-", -val);
	prefix("~", ~(int)val);
	prefix("+", val);
	//prefix("#", val);
#undef prefix
	return sanitize(getnumcore());
}
Ejemplo n.º 9
0
 static inline T _to(const std::string &s, const std::string &name)
 {
     std::istringstream is(s);
     T v;
     is >> v;
     if (is.fail() || !is.eof())
     {
         throw exc(std::string("cannot convert '") + sanitize(s) + "' to " + name, EINVAL);
     }
     return v;
 }
Ejemplo n.º 10
0
void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl)
{
    static int print_prefix = 1;
    static int count;
    static char prev[LINE_SZ];
    AVBPrint part[3];
    char line[LINE_SZ];
    static int is_atty;
    int type[2];

    if (level > av_log_level)
        return;
    format_line(ptr, level, fmt, vl, part, &print_prefix, type);
    snprintf(line, sizeof(line), "%s%s%s", part[0].str, part[1].str, part[2].str);

#if HAVE_ISATTY
    if (!is_atty)
        is_atty = isatty(2) ? 1 : -1;
#endif

    if (print_prefix && (flags & AV_LOG_SKIP_REPEATED) && !strcmp(line, prev) &&
        *line && line[strlen(line) - 1] != '\r'){
        count++;
        if (is_atty == 1)
            fprintf(stderr, "    Last message repeated %d times\r", count);
        av_bprint_finalize(part+2, NULL);
        return;
    }
    if (count > 0) {
        fprintf(stderr, "    Last message repeated %d times\n", count);
        count = 0;
    }
    strcpy(prev, line);
    sanitize(part[0].str);
    colored_fputs(type[0], part[0].str);
    sanitize(part[1].str);
    colored_fputs(type[1], part[1].str);
    sanitize(part[2].str);
    colored_fputs(av_clip(level >> 3, 0, 6), part[2].str);
    av_bprint_finalize(part+2, NULL);
}
Ejemplo n.º 11
0
	void dump(x0::Buffer& out, x0::HttpConnection* c, bool debug)
	{
		out << "<tr>";

		out << "<td class='cid'>" << c->id() << "</td>";
		out << "<td class='wid'>" << c->worker().id() << "</td>";
		out << "<td class='rn'>" << c->requestCount() << "</td>";
		out << "<td class='ip'>" << c->remoteIP() << "</td>";

		out << "<td class='state'>" << c->status_str();
		if (c->status() == x0::HttpConnection::ReadingRequest)
			out << " (" << c->state_str() << ")";
		out << "</td>";

		out << "<td class='age'>" << (c->worker().now() - c->socket()->startedAt()).str() << "</td>";
		out << "<td class='idle'>" << (c->worker().now() - c->socket()->lastActivityAt()).str() << "</td>";
		out << "<td class='read'>" << c->inputOffset() << "/" << c->inputSize() << "</td>";

		const x0::HttpRequest* r = c->request();
		if (r && c->status() != x0::HttpConnection::KeepAliveRead) {
			out << "<td class='written'>" << r->bytesTransmitted() << "</td>";
			out << "<td class='host'>" << sanitize(r->hostname) << "</td>";
			out << "<td class='method'>" << sanitize(r->method) << "</td>";
			out << "<td class='uri'>" << sanitize(r->unparsedUri) << "</td>";
			out << "<td class='status'>" << r->statusStr(r->status) << "</td>";
		} else {
			out << "<td colspan='5'>" << "</td>";
		}

		if (debug) {
			out << "<td class='debug'>";
			out << "refcount:" << c->refCount() << ", ";
			c->socket()->inspect(out);
			if (c->request()) {
				c->request()->inspect(out);
			}
			out << "</td>";
		}

		out << "</tr>\n";
	}
Ejemplo n.º 12
0
void AudioRecord::initFilename(const std::string &peerNumber)
{
    RING_DBG("Initialize audio record for peer  : %s", peerNumber.c_str());
    // if savePath_ don't contains filename
    if (savePath_.find(".wav") == std::string::npos) {
        filename_ = createFilename();
        filename_.append("-" + sanitize(peerNumber) + "-" PACKAGE);
        filename_.append(".wav");
    } else {
        filename_ = "";
    }
}
Ejemplo n.º 13
0
/// Return event on top of heap, deleting it from the heap
Event *EqHeap::GetAndRemoveTopEvent()
{
#ifdef EH_SANITIZE
    sanitize();
#endif
  CmiAssert(top != NULL);
  CmiAssert(top->subheapsize > 0);
  HeapNode *tmp = top;
  Event *result;

  if (top->left) top = top->left->conjoin(top->right);
  else top = top->right;
  result = tmp->e;
  tmp->e = NULL;
  tmp->left = tmp->right = NULL;
  delete(tmp);
  heapSize--;
#ifdef EH_SANITIZE
    sanitize();
#endif
  return result;
}
Ejemplo n.º 14
0
/// Basic Constructor
eventQueue::eventQueue()
{
  lastLoggedVT = 0;
  Event *e;
  eqh = new EqHeap();  // create the heap for incoming events
  largest = POSE_UnsetTS;
  mem_usage = 0;
  eventCount = 0;
  tsOfLastInserted = 0;
  // create the front sentinel node
  e = new Event();
  e->timestamp = POSE_UnsetTS;
  e->done = -1;
  e->fnIdx = -99;
  e->msg = NULL;
  e->commitBfr = NULL;
  e->spawnedList = NULL;
  e->commitBfrLen = 0;
  e->next = e->prev = NULL;
  frontPtr = e;
  // create the back sentinel node
  e = new Event();
  e->timestamp=POSE_UnsetTS;
  e->done = -1;
  e->fnIdx = -100;
  e->msg = NULL;
  e->commitBfr = NULL;
  e->spawnedList = NULL;
  e->commitBfrLen = 0;
  e->next = e->prev = NULL;
  currentPtr = backPtr = e; // when no unprocessed events, currentPtr=backPtr
  // link them together
  frontPtr->next = backPtr;
  backPtr->prev = frontPtr;
  RBevent = NULL;
  // other variables
  recentAvgEventSparsity = 1;
  sparsityStartTime = 0;
  sparsityCalcCount = 0;
  tsDiffCount = 0;
  lastCommittedTS = 0;
  for (int i = 0; i < DIFFS_TO_STORE; i++) {
    tsCommitDiffs[i] = 0;
  }
#ifdef MEM_TEMPORAL
  localTimePool = (TimePool *)CkLocalBranch(TempMemID);
#endif
#ifdef EQ_SANITIZE
  sanitize();
#endif
}
Ejemplo n.º 15
0
Archivo: log.c Proyecto: odit/rv042
/* format a string for the log, with suitable prefixes.
 * A format starting with ~ indicates that this is a reprocessing
 * of the message, so prefixing and quoting is suppressed.
 */
static void
fmt_log(char *buf, size_t buf_len, const char *fmt, va_list ap)
{
    bool reproc = *fmt == '~';
    size_t ps;
    struct connection *c = cur_state != NULL ? cur_state->st_connection
	: cur_connection;

    buf[0] = '\0';
    if (reproc)
	fmt++;	/* ~ at start of format suppresses this prefix */
    else if (c != NULL)
    {
	/* start with name of connection */
	char *const be = buf + buf_len;
	char *bp = buf;

	snprintf(bp, be - bp, "(%s)", c->name);
	bp += strlen(bp);

	/* if it fits, put in any connection instance information */
	if (be - bp > CONN_INST_BUF)
	{
	    fmt_conn_instance(c, bp);
	    bp += strlen(bp);
	}

	if (cur_state != NULL)
	{
	    /* state number */
	    snprintf(bp, be - bp, " #%lu", cur_state->st_serialno);
	    bp += strlen(bp);
	}
	snprintf(bp, be - bp, ": ");
    }
    else if (cur_from != NULL)
    {
	/* peer's IP address */
	/* Note: must not use ip_str() because our caller might! */
	char ab[ADDRTOT_BUF];

	(void) addrtot(cur_from, 0, ab, sizeof(ab));
	snprintf(buf, buf_len, "packet from %s:%u: "
	    , ab, (unsigned)cur_from_port);
    }

    ps = strlen(buf);
    vsnprintf(buf + ps, buf_len - ps, fmt, ap);
    if (!reproc)
	(void)sanitize(buf, buf_len);
}
Ejemplo n.º 16
0
int
exec_shlib(int argc, char **argv)
{
	struct pkgdb	*db = NULL;
	char		 libname[MAXPATHLEN + 1];
	int		 retcode = EPKG_OK;
	int		 ch;
	bool		 provides_only = false;
	bool		 requires_only = false;

	while ((ch = getopt(argc, argv, "PR")) != -1) {
		switch (ch) {
		case 'P':
			provides_only = true;
			break;
		case 'R':
			requires_only = true;
			break;
		default:
			usage_shlib();
			return (EX_USAGE);
		}
	}
	argc -= optind;
	argv += optind;

	if (argc < 1 || (provides_only && requires_only)) {
		usage_shlib();
		return (EX_USAGE);
	}

	if (sanitize(libname, argv[0], sizeof(libname)) == NULL) {
		usage_shlib();
		return (EX_USAGE);
	}

	retcode = pkgdb_open(&db, PKGDB_DEFAULT);

	if (retcode == EPKG_OK && !provides_only)
		retcode = pkgs_providing_lib(db, libname);

	if (retcode == EPKG_OK && !requires_only)
		retcode = pkgs_requiring_lib(db, libname);

	if (retcode != EPKG_OK)
		retcode = (EX_IOERR);
		
	pkgdb_close(db);
	return (retcode);
}
void writeMsg(boolean tx, char *msg, int size) {
   static const char SEND_PREFIX1[]    = " ==>";
   static const char SEND_PREFIX2[]    = "    ";
   static const char RECEIVE_PREFIX1[] = "<== ";
   static const char RECEIVE_PREFIX2[] = "    ";
   static const int  BUFF_SIZE        = 100;

   const char *prefix;
   if (tx) {
      prefix = SEND_PREFIX1;
   }
   else {
      prefix = RECEIVE_PREFIX1;
   }
   char buff[BUFF_SIZE];
   while (size>0) {
      int portion = BUFF_SIZE-10;
      if (portion > size) {
         portion = size;
      }
      if (tx) {
         sanitize(buff, msg, portion);
         strcat(buff, prefix);
         fprintf(stdout, "%s\n", buff); fflush(stdout);
         prefix = SEND_PREFIX2;
      }
      else {
         strcpy(buff, prefix);
         sanitize(buff+sizeof(RECEIVE_PREFIX1)-1, msg, portion);
         fprintf(stdout, "%*s%s\n", BUFF_SIZE, "", buff); fflush(stdout);
         prefix = RECEIVE_PREFIX2;
      }
      msg   += portion;
      size  -= portion;
   }
}
Ejemplo n.º 18
0
bool writeJson(const QVariantMap &variant, const QString &fileName)
{
#ifdef Q_OS_WIN
    QFile file(fileName);
#else
    QFile file(QString::fromLatin1("../") + fileName);
#endif
    if (!file.open(QIODevice::WriteOnly|QIODevice::Truncate)) {
        return false;
    }
    QVariant saneVariant(variant);
    sanitize(saneVariant);
    file.write(QJsonDocument::fromVariant(saneVariant).toJson());
    return true;
}
Ejemplo n.º 19
0
static DDS_StdString
main_file_identifier()
{
   DDS_StdString mainFile = BaseName(idl_global->main_filename()->get_string());
   char *dot = (char*)strrchr((const char*)mainFile, '.');

   if (dot)
   {
      *dot = 0;
   }

   sanitize(mainFile);

   return mainFile;
}
Ejemplo n.º 20
0
static int call(int (*action)(svc_t *), char *buf, size_t len)
{
	int result = 0;
	char *input, *token, *pos;

	input = sanitize(buf, len);
	if (!input)
		return -1;

	token = strtok_r(input, " ", &pos);
	while (token) {
		svc_t *svc;
		char *ptr = strchr(token, ':');

		if (isdigit(token[0])) {
			int job = atonum(token);

			if (!ptr) {
				svc = svc_job_iterator(1, job);
				while (svc) {
					result += action(svc);
					svc = svc_job_iterator(0, job);
				}
			} else {
				*ptr++ = 0;
				job = atonum(token);
				result += action(svc_find_by_jobid(job, atonum(ptr)));
			}

		} else {
			if (!ptr) {
				svc = svc_named_iterator(1, token);
				while (svc) {
					result += action(svc);
					svc = svc_named_iterator(0, token);
				}
			} else {
				*ptr++ = 0;
				result += action(svc_find_by_nameid(token, atonum(ptr)));
			}
		}

		token = strtok_r(NULL, " ", &pos);
	}

	return result;
}
Ejemplo n.º 21
0
static int do_handle_emit(char *buf, size_t len)
{
	int result = 0;
	char *input, *event, *pos;

	input = sanitize(buf, len);
	if (!input)
		return -1;

	event = strtok_r(input, " ", &pos);
	while (event) {
		result += do_handle_event(event);
		event = strtok_r(NULL, " ", &pos);
	}

	return result;
}
Ejemplo n.º 22
0
static GString *sanitize_contents(GumboNode* node, GPtrArray *inlines_ary) {
  GString *contents = g_string_new(NULL);
  GString *tagname  = get_tag_name(node);

  gchar *key = g_strjoin(NULL, "|", tagname->str, "|", NULL);
  g_string_free(tagname, TRUE);

  // Since we include pipes (|) we have to escape the regex string
  gchar *key_pattern = g_regex_escape_string(key, -1);
  g_free(key);

  gboolean no_entity_substitution = g_regex_match_simple(key_pattern, no_entity_sub, G_REGEX_CASELESS, 0);
  g_free(key_pattern);

  // build up result for each child, recursively if need be
  GumboVector* children = &node->v.element.children;
  guint i;
  for (i = 0; i < children->length; ++i) {
    GumboNode* child = (GumboNode*) (children->data[i]);

    if (child->type == GUMBO_NODE_TEXT) {
      if (no_entity_substitution) {
        g_string_append(contents, child->v.text.text);
      } else {
        GString *subd = gstr_substitute_xml_entities_into_text(child->v.text.text);
        g_string_append(contents, subd->str);
        g_string_free(subd, TRUE);
      }

    } else if (child->type == GUMBO_NODE_ELEMENT ||
               child->type == GUMBO_NODE_TEMPLATE) {

      GString *child_ser = sanitize(child, inlines_ary);
      g_string_append(contents, child_ser->str);
      g_string_free(child_ser, TRUE);

    } else if (child->type == GUMBO_NODE_WHITESPACE) {
      // keep all whitespace to keep as close to original as possible
      g_string_append(contents, child->v.text.text);
    } else if (child->type != GUMBO_NODE_COMMENT) {
      // Does this actually exist: (child->type == GUMBO_NODE_CDATA)
      fprintf(stderr, "unknown element of type: %d\n", child->type);
    }
  }
  return contents;
}
Ejemplo n.º 23
0
void
DBG_log(const char *message, ...)
{
    va_list args;
    char m[1024];	/* longer messages will be truncated */

    va_start(args, message);
    vsnprintf(m, sizeof(m), message, args);
    va_end(args);

    (void)sanitize(m, sizeof(m));

    if (log_to_stderr)
	fprintf(stderr, "| %s\n", m);
    if (log_to_syslog)
	syslog(LOG_DEBUG, "| %s", m);
}
Ejemplo n.º 24
0
// Test case: TestCurate:1
// This test case calls curateWords() for the condition where the query
// are all keywords (no non-alpha characters)
int TestCurate1() {
  START_TEST_CASE;

  char query[1000] = "dog cat mouse world";
  sanitize(query);

  char* queryList[1000];
  curateWords(queryList, query);

  SHOULD_BE(strcmp(queryList[0],"dog") == 0);
  SHOULD_BE(strcmp(queryList[1],"cat") == 0);
  SHOULD_BE(strcmp(queryList[2],"mouse") == 0);
  SHOULD_BE(strcmp(queryList[3],"world") == 0);

  cleanUpQueryList(queryList);
  END_TEST_CASE;
}
Ejemplo n.º 25
0
int action_run(Graph g, char *act_name)
{
    int error;
    Node n;
    n = find_node(g, act_name);
    if (n != NULL) {
        set_node_state(n, ACT_RUN, &error); //only raise error when state is set to ready and done
	make_other_run_suspend(g, act_name);
	mark_iter_nodes(n);  /* handle iterations */
	handle_selection(n); /* handle selections */
	set_super_nodes_run(n); /*set super nodes to run */
        sanitize(g); /* sanitize the markers used */
    } else {
	return -1;
    }
    return 1;
}
Ejemplo n.º 26
0
void NavigationControl::LineCallback(const Robosub::Line msg) {
	if(LINEMODE == OFF)
		return;

    OnLine = moveToLine(msg.x, msg.y);
    //Once it's on top of the line, rotate
    if (!OnLine){
        return; //keep rotating
    }

    int target_rot = sanitize(msg.rotation);
    if(!target_rot){
	 start_rot = 0;
         Rotating = 0;
	 setTurn(0);
	 return; //Stoppped by Higher Level
    }
    if(!Rotating){
        start_rot = target_rot;
    }

    float per_rot = (target_rot/180);//start_rot);


    //This needs to be implemented better (any ideas?)
    //int direction = 1; //always rotate right?
    int direction = target_rot>0 ? 1 : -1; //-1 Rotate left


    int rate = 0;
    int range=40;
    int minR = 50;

    if(abs(per_rot)<MAX_THRESHOLD ){
        if(abs(per_rot)>.01)
            rate = -60*direction;
        else
            rate = 0;
    } else {
        rate = (range*per_rot+minR)*direction;
    }

    setTurn(rate);

}
Ejemplo n.º 27
0
// Test case: TestCurate:2
// This test case calls curateWords() for the condition where the query
// are invalid (non-alpha characters).
int TestCurate2() {
  START_TEST_CASE;

  char empty[1000] = "$$";
  sanitize(empty);

  char* list[1000];
  BZERO(list, 1000);
  list[0] = (char*) malloc(sizeof(char) * 1000);
  BZERO(list[0], 1000); 

  curateWords(list, empty);

  SHOULD_BE(strcmp(list[0], "") == 0);

  free(list[0]);
  END_TEST_CASE;
}
Ejemplo n.º 28
0
void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl)
{
    static int print_prefix=1;
    static int count;
    static char prev[1024];
    char line[1024];
    static int is_atty;
    AVClass* avc= ptr ? *(AVClass**)ptr : NULL;
    if(level>av_log_level)
        return;
    line[0]=0;
#undef fprintf
    if(print_prefix && avc) {
        if(avc->version >= (50<<16 | 15<<8 | 3) && avc->parent_log_context_offset){
            AVClass** parent= *(AVClass***)(((uint8_t*)ptr) + avc->parent_log_context_offset);
            if(parent && *parent){
                snprintf(line, sizeof(line), "[%s @ %p] ", (*parent)->item_name(parent), parent);
            }
        }
        snprintf(line + strlen(line), sizeof(line) - strlen(line), "[%s @ %p] ", avc->item_name(ptr), ptr);
    }

    vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, vl);

    print_prefix= line[strlen(line)-1] == '\n';

#if HAVE_ISATTY
    if(!is_atty) is_atty= isatty(2) ? 1 : -1;
#endif

    if(print_prefix && (flags & AV_LOG_SKIP_REPEATED) && !strcmp(line, prev)){
        count++;
        if(is_atty==1)
            fprintf(stderr, "    Last message repeated %d times\r", count);
        return;
    }
    if(count>0){
        fprintf(stderr, "    Last message repeated %d times\n", count);
        count=0;
    }
    strcpy(prev, line);
    sanitize(line);
    colored_fputs(av_clip(level>>3, 0, 6), line);
}
Ejemplo n.º 29
0
  void parse(const string& data) {
    reset();

    lstring lines = data.split("\n");
    for(auto& line : lines) {
      lstring part = line.split(":", 1L).strip();
      if(part.size() != 2) continue;

      if(part[0] == "offset") offset = eval(part[1]);
      if(part[0] == "width") width = eval(part[1]);
      if(part[0] == "height") height = eval(part[1]);
      if(part[0] == "count") count = eval(part[1]);

      if(part[0] == "endian") endian = eval(part[1]);
      if(part[0] == "order") order = eval(part[1]);
      if(part[0] == "depth") depth = eval(part[1]);

      if(part[0] == "blockWidth") blockWidth = eval(part[1]);
      if(part[0] == "blockHeight") blockHeight = eval(part[1]);
      if(part[0] == "blockStride") blockStride = eval(part[1]);
      if(part[0] == "blockOffset") blockOffset = eval(part[1]);
      if(part[0] == "block") eval(block, part[1]);

      if(part[0] == "tileWidth") tileWidth = eval(part[1]);
      if(part[0] == "tileHeight") tileHeight = eval(part[1]);
      if(part[0] == "tileStride") tileStride = eval(part[1]);
      if(part[0] == "tileOffset") tileOffset = eval(part[1]);
      if(part[0] == "tile") eval(tile, part[1]);

      if(part[0] == "mosaicWidth") mosaicWidth = eval(part[1]);
      if(part[0] == "mosaicHeight") mosaicHeight = eval(part[1]);
      if(part[0] == "mosaicStride") mosaicStride = eval(part[1]);
      if(part[0] == "mosaicOffset") mosaicOffset = eval(part[1]);
      if(part[0] == "mosaic") eval(mosaic, part[1]);

      if(part[0] == "paddingWidth") paddingWidth = eval(part[1]);
      if(part[0] == "paddingHeight") paddingHeight = eval(part[1]);
      if(part[0] == "paddingColor") paddingColor = eval(part[1]);
      if(part[0] == "palette") eval(palette, part[1]);
    }

    sanitize();
  }
Ejemplo n.º 30
0
/*
 * This function is called to read the first row and store
 * the field names as the header names.
 */
int get_field_headers() {
  char token[MAX_TOKEN+1];
  int status;

  status=1;
  fieldcount=0;
  memset(&fields,0,sizeof(fields));
  while(fieldcount<MAX_FIELDS && status>0) {
    status=get_csv_token((char*)&token,MAX_TOKEN);
    if(status<0) { break; }
    if(token[0]==0) { fatal("Header row has null string"); }
    if(xmlmode!=2) { sanitize((char*)&token); }
    fields[fieldcount]=new char[strlen(token)+1];
    strcpy(fields[fieldcount],token);
    fieldcount++;
    }
    if(fieldcount==MAX_FIELDS) { fatal("Too many columns in this csv file"); }

  return(status);
  }