Exemple #1
0
static void parse_insert(char *str, int slideid, char origin) {
    char  *s = str;
    char  *w;
    char  *index_entry;
    short  kw;
    int    len;
    char   done = 0;

    if (str) {
      record_special(str, slideid, origin);
      while (*s) {
        while (*s && !isalpha(*s) && (*s != get_kw())) {
          s++;
        }
        if (*s == get_kw()) {
          kw = 1;
          s++;
        }
        if (*s) {
          len = 1;
          w = s;
          s++;
          while (isalnum(*s) || (*s == '\'')) {
            len++;
            s++; 
          }
          if (*s) { 
            *s = '\0';
          } else {
            done = 1;
          }
          if (get_mode() & OPT_IFILE) {
            // Only insert the "word" if found in the list of words
            // to index. Note that "word" may be a variant of the
            // real word to index.
            if ((index_entry = must_index(w, &kw))!= (char *)NULL) {
              new_word(index_entry, slideid, origin, kw);
            }
          } else {
            if (len >= MIN_WORD_LEN) {
              if (!must_ignore(w)) {
                new_word(w, slideid, origin, kw);
              }
            }
          }
          if (!done) {
            s++;
          }
        }
      }
    }
}
BOOL CMFCApplication1Dlg::PreTranslateMessage(MSG* pMsg) {
	CWnd* temp_time = GetDlgItem(IDC_TIMER);
	CString t_time;

	switch (pMsg->message)
	{
		

		case WM_TIMER: //ako traje igra, svakih 0.1 sekundi provjerava da li je "duration" manji od 0, ako je poziva se "game over", ako nije da se "duration" smanji za 0.1
			if (game == true) {
				duration -= 0.1;
				if (duration < 0)
					game_over();
				t_time.Format(_T("%.1f"), duration);
				temp_time->SetWindowText(LPCTSTR(t_time));
				return false;
			}

		case WM_KEYUP: //prepoznavanje stisnute tipke
			if (pMsg->wParam == VK_RETURN) { // poèetak ili reset igre
				new_game();
				CWnd *_help = GetDlgItem(IDC_INST);
				_help->SetWindowText(_T(""));
			}
			else if (pMsg->wParam == VK_ESCAPE) { // izlazak iz igre
				EndDialog(IDCANCEL);

			}
			else if (GetAsyncKeyState(current_word[0]) && game == true) { //provjera da li je pritisnuta tipka jednaka traženom slovu

				if (current_word.Mid(1).IsEmpty()) { //ako nema više slova poveæava se "score"  i postavlja se nova rijeè

					set_score();
					new_word();
				}

				else { //za svako pogoðeno slovo, to slovo se mièe iz prikaza rijeèi i svira zvuk za pogoðeno slovo

					sound_path.LoadString(IDS_S_WRITE);
					PlaySound(sound_path, GetModuleHandle(NULL), SND_ASYNC); //zvuk za dobro upisano slovo
					current_word = current_word.Mid(1); //mièe se prvi znak(slovo) iz rijeèi
					change_text(); //postavlja se tekst bez prvog znaka
				}
			}
			else if (GetAsyncKeyState('H') && game == false) //kada igra ne traje ako je "H" pritisnut prikazuju se instrukcije za igranje igre
			{
				CString res;
				CString res2;
				res.LoadString(IDS_M_HELP);
				res2.LoadString(IDS_M_HELP_T);
				MessageBox(res, res2);
			}
			else if (game == true) //ako igra traje i nije pogoðeno slovo, poziva se "game over"
				game_over();

			return true;

	}
		return false;
}
Exemple #3
0
word *factor_vm::allot_word(cell name_, cell vocab_, cell hashcode_)
{
	data_root<object> vocab(vocab_,this);
	data_root<object> name(name_,this);

	data_root<word> new_word(allot<word>(sizeof(word)),this);

	new_word->hashcode = hashcode_;
	new_word->vocabulary = vocab.value();
	new_word->name = name.value();
	new_word->def = special_objects[OBJ_UNDEFINED];
	new_word->props = false_object;
	new_word->counter = tag_fixnum(0);
	new_word->pic_def = false_object;
	new_word->pic_tail_def = false_object;
	new_word->subprimitive = false_object;
	new_word->profiling = NULL;
	new_word->code = NULL;

	jit_compile_word(new_word.value(),new_word->def,true);
	if(counting_profiler_p)
	{
		code_block *profiling_block = compile_profiling_stub(new_word.value());
		new_word->profiling = profiling_block;
		initialize_code_block(new_word->profiling);
	}

	update_word_entry_point(new_word.untagged());

	return new_word.untagged();
}
    unordered_map<string, unordered_set<string> > build_graph(
        const unordered_set<string>& dict) {
        unordered_map<string, unordered_set<string> > adjacency_list;

        for (const auto& word : dict) {
            for (size_t i = 0; i < word.size(); ++i) {
                string new_word(word);
                for (char c = 'a'; c <= 'z'; c++) {
                    // 防止同字母替换
                    if (c == new_word[i]) continue;

                    swap(c, new_word[i]);

                    if ((dict.find(new_word) != dict.end())) {
                        auto iter = adjacency_list.find(word);
                        if (iter != adjacency_list.end()) {
                            iter->second.insert(new_word);
                        }
                        else {
                            adjacency_list.insert(pair<string,
                                unordered_set<string >> (word, unordered_set<string>()));
                            adjacency_list[word].insert(new_word);
                        }
                    }
                    swap(c, new_word[i]); // 恢复该单词
                }
            }
        }
        return adjacency_list;
    }
Exemple #5
0
static void declare_scheduler_interface(data_declaration task_decl)
{
  region r = parse_region;
  location loc = task_decl->ast->location;
  word task_name;
  interface_ref task_interface;
  rp_interface task_uses;
  int osection;

  /* We save the task's replacement interface in its interface field... */
  if (task_decl->interface)
    return;

  /* Build the (uses) 'interface Scheduler as X' ast, declare the interface. */
  /* This specific AST structure is assumed in wire_scheduler below */
  task_name = new_word(r, loc, str2cstring(r, task_decl->name));
  task_interface = new_interface_ref(r, loc, make_scheduler_interfacedef_name(loc),
				     NULL, task_name, NULL, NULL, NULL);
  osection = current.spec_section;
  current.spec_section = spec_uses;
  declare_interface_ref(task_interface, NULL, current.container->env, NULL);
  current.spec_section = osection;
  task_decl->interface = task_interface->ddecl;

  /* Build the 'uses <interface>' AST, add it to the component */
  task_uses = new_rp_interface(r, loc, TRUE, CAST(declaration, task_interface));
  all_tasks = declaration_chain(CAST(declaration, task_uses), all_tasks);
}
/* Divide each of the words in the sentence into one character words,
   without changing the positions of those characters.
 */
static void
split_words (state *s, sentence *se)
{
  word **words2;
  int nwords2 = 0;
  int i, j;
  for (i = 0; i < se->nwords; i++)
    nwords2 += strlen (se->words[i]->text);

  words2 = (word **) calloc (nwords2, sizeof(*words2));

  for (i = 0, j = 0; i < se->nwords; i++)
    {
      word *ow = se->words[i];
      int L = strlen (ow->text);
      int k;

      int x  = ow->x;
      int y  = ow->y;
      int sx = ow->start_x;
      int sy = ow->start_y;
      int tx = ow->target_x;
      int ty = ow->target_y;

      for (k = 0; k < L; k++)
        {
          char *t2 = malloc (2);
          word *w2;
          int xoff, yoff;

          t2[0] = ow->text[k];
          t2[1] = 0;
          w2 = new_word (s, se, t2, True);
          words2[j++] = w2;

          xoff = (w2->lbearing - ow->lbearing);
          yoff = (ow->ascent - w2->ascent);

          w2->x        = x  + xoff;
          w2->y        = y  + yoff;
          w2->start_x  = sx + xoff;
          w2->start_y  = sy + yoff;
          w2->target_x = tx + xoff;
          w2->target_y = ty + yoff;

          x  += w2->rbearing;
          sx += w2->rbearing;
          tx += w2->rbearing;
        }

      free_word (s, ow);
      se->words[i] = 0;
    }
  free (se->words);

  se->words = words2;
  se->nwords = nwords2;
}
Exemple #7
0
    int ladderLength(const string& start, const string &end,
            const unordered_set<string> &dict) {
        queue<string> current, next;
        unordered_set<string> visited;

        int level = 0;
        bool found = false;

        auto state_is_target = [&](const string &s) {return s == end;};
        auto state_extend = [&](const string &s) {
            vector<string> result;

            for (size_t i = 0; i < s.size(); ++i) {
                string new_word(s);
                for (char c = 'a'; c <= 'z'; c++) {
                    if (c == new_word[i]) continue;

                    swap(c, new_word[i]);

                    if ((dict.count(new_word) > 0 || new_word == end) &&
                            !visited.count(new_word)) {
                        result.push_back(new_word);
                        visited.insert(new_word);
                    }
                    swap(c, new_word[i]);
                }
            }

            return result;
        };

        current.push(start);
        while (!current.empty() && !found) {
            ++level;
            while (!current.empty() && !found) {
                const string str = current.front();
                current.pop();

                const auto& new_states = state_extend(str);
                for (const auto& state : new_states) {
                    next.push(state);
                    if (state_is_target(state)) {
                        found = true;
                        break;
                    }
                }
            }
            swap(next, current);
        }
        if (found) return level + 1;
        else return 0;
    }
Exemple #8
0
int ladderLength(string start, string end, const unordered_set<string> &dict)
{
    if (start.size() != end.size()) return 0;

    if (start.empty() || end.empty()) return 0;

    queue<string> next, current; // 当前层,下一层
    unordered_set<string> visited; // 判重
    unordered_map<string, string > father;
    int level = 0; // 层次
    bool found = false;

    current.push(start);
    while (!current.empty() && !found)
    {
        ++level;
        while (!current.empty() && !found) //处理一层
        {
            const string str(current.front());
            current.pop();
            for (size_t i = 0; i < str.size(); ++i)
            {
                string new_word(str);
                for (char c = 'a'; c <= 'z'; c++)
                {
                    if (c == new_word[i]) continue;
                    swap(c, new_word[i]);//确保只更换一个一个字母

                    if (new_word == end)
                    {
                        found = true; //找到了
                        father[new_word] = str;
                        break;
                    }

                    if (dict.count(new_word) > 0 && !visited.count(new_word))//在dict中并且未visited
                    {
                        next.push(new_word);
                        visited.insert(new_word);
                        father[new_word] = str;
                    }
                    swap(c, new_word[i]); // 恢复该单词
                }
            }
        }

        swap(next, current); //!!! 交换两个队列
    }

    if (found) return level + 1;
    else return 0;
}
Exemple #9
0
static word make_scheduler_interfacedef_name(location l)
{
  static bool alloc;
  static cstring ascstring;

  if (!alloc)
    {
      alloc = TRUE;
      ascstring = str2cstring(permanent, scheduler_interfacedef_name);
    }

  return new_word(parse_region, l, ascstring);
}
void CMFCApplication1Dlg::new_game() { //poèetak igre


	srand(time(NULL));

	game = false; //postavlja se indicator "game" na "false" da bi se "score" postavio na nulu
	set_score(); //"score" se postavlja na 0
	game = true; // indicator se postavlja na "true" da kada se postavi rijeè za upisivanje, program provjerava da li je pritisnuta tipka jednaka traženom slovu
	new_word(); // postavlja se nova rijeè

	//std::async(std::launch::async, &CMFCApplication1Dlg::timer, this);

	timer(); //postavlja se timer
}
Exemple #11
0
void handle_task_definition(function_decl fdecl)
{
  function_declarator fd;

  declare_scheduler_interface(fdecl->ddecl);
  replace_task_with_event(fdecl->modifiers);

  /* Replace foo with foo.run. We only bother doing this if the declarator
     is a valid task declarator (function_declarator with nested
     identifier_declarator) - if it isn't, we have an error in the form of
     a misdeclared task. */
  /* (we only get here for something which really is a function declaration) */
  fd = CAST(function_declarator, fdecl->declarator);
  if (is_identifier_declarator(fd->declarator))
    {
      data_declaration rundecl;
      identifier_declarator oldd = CAST(identifier_declarator, fd->declarator);
      identifier_declarator rund =
	new_identifier_declarator(parse_region, fd->location,
				  make_scheduler_run_name());
      interface_ref_declarator ird =
	new_interface_ref_declarator(parse_region, fd->location,
				     CAST(declarator, rund),
				     new_word(parse_region, fd->location, oldd->cstring));
      fd->declarator = CAST(declarator, ird);

      /* Update task's declaration object */
      rundecl = interface_lookup(fdecl->ddecl->interface, scheduler_run_name);
      if (!rundecl || rundecl->ftype != function_event)
	{
	  static int oneerror;

	  if (!oneerror)
	    {
	      oneerror = TRUE;
	      error("task interface `%s' has no event named `%s'",
		    scheduler_interface_name, scheduler_run_name);
	    }
	}
      else
	{
	  /* Don't lose safe flag */
	  rundecl->safe = fdecl->ddecl->safe;
	  fdecl->ddecl = rundecl;
	  rundecl->definition = CAST(declaration, fdecl);
	}
    }
}
 unordered_set<string> state_extend(const string &s, string endWord, unordered_set<string> &wordList, unordered_set<string>& visited){
     unordered_set<string> result;
     for(size_t i=0; i<s.size(); i++){
         string new_word(s);
         for(char c='a'; c<='z'; c++){
             if(c==new_word[i])  continue;
             swap(c, new_word[i]);
             if((wordList.find(new_word)!=wordList.end() || new_word==endWord) && 
                    visited.find(new_word)==visited.end()){
                 result.insert(new_word);           
             }
             swap(c, new_word[i]);
         }
     }
     return result;
 }
Exemple #13
0
int main(){
	FILE *fp;
	char c, file_name[sizeof(char)], oneword[sizeof(char)];
	TreeBase* tree = new_base(compareWords, freeNode, printWordCount);

   	printf("Enter the name of file you wish to see\n> ");
    scanf("%s", file_name);
    fp = fopen(file_name,"r");

	// Check error
    if (fp == NULL){
    	perror("Error while opening the file.\n");
      	exit(EXIT_FAILURE);
    }
    int i = 0;
	// Read the whole file
    while ((c = fgetc(fp)) != EOF){ 	// get charachters from the file until the end		
    	// if in is not alphanumeric
      	if (!((c >= 'a' && c <= 'z') || ((c >= 'A' && c <= 'Z') || c == '\0'|| c == '\''))){  
      		oneword[i] = '\0'; 	// end of the string
		    if (strlen(oneword) > 0){	// Word cannot be empty
	      		WordCount* wc = new_word(oneword);
		    	insert(tree, wc);
		    	i = 0; 
		    }
	    }
	    else{
		    c = tolower(c); // convert all letters in the word to lowercase	
			oneword[i] = c;
			i++;
		}
    }

    fclose(fp);
    printTree(tree);

    int max = maxCount(tree->base); // find most common word counter

    printf("The most common word \"%s\" occurs %d times\n", mostUsedWord(tree->base, max), max);
    printf("Total number of characters in all words: %d\n", sumWordLength(tree->base));
    printf("Average word length: %d\n", averageWordLength(tree->base));
    printf("Total number of words: %d", totalNumOfWords(tree->base));
    freeTree(tree);
}
Exemple #14
0
// Allocates memory
word* factor_vm::allot_word(cell name_, cell vocab_, cell hashcode_) {
  data_root<object> vocab(vocab_, this);
  data_root<object> name(name_, this);

  data_root<word> new_word(allot<word>(sizeof(word)), this);

  new_word->hashcode = hashcode_;
  new_word->vocabulary = vocab.value();
  new_word->name = name.value();
  new_word->def = special_objects[OBJ_UNDEFINED];
  new_word->props = false_object;
  new_word->pic_def = false_object;
  new_word->pic_tail_def = false_object;
  new_word->subprimitive = false_object;
  new_word->entry_point = 0;

  jit_compile_word(new_word.value(), new_word->def, true);

  return new_word.untagged();
}
Exemple #15
0
word build_word(region r, const char *cword)
{
  return new_word(r, dummy_location, str2cstring(r, cword));
}
Exemple #16
0
void get_word(int flag)
{
	unsigned int size = 0, n = 0, i = 0;
	char ans[500];
	int frame_n;
	void *buffer = NULL;
	frame *frames = NULL;
	mfcc_frame *mfcc_frames = NULL;
	voice_signal *signals = NULL;
	printf("\nFale agora e pressione enter\n");
	capture_start(NULL);
	getchar();
	getchar();
	capture_stop(&size, &buffer);
	n = split(buffer, size / 2, &signals);
	for (i = 0; i < n; i++)
	{
		frame_n = make_frames_hamming(signals[i].buffer, signals[i].number, &frames);
		mfcc_frames = malloc(sizeof(mfcc_frame) * frame_n);
		mfcc_features(frames, frame_n, mfcc_frames);
		if (!flag)
		{
			record(NULL, signals[i].buffer, signals[i].number * 2);
			printf("Escreva a palavra: ");
			scanf("%s", (char *)ans);
			if (!(ans[0] == 'x' && ans[1] == '\0'))
			{
				new_word(mfcc_frames, frame_n, (char *)ans);
				chdir("waves");
				char *path = malloc(strlen(ans) + 5);
				char *ext = ".wav";
				memcpy(path, ans, strlen(ans));
				memcpy(path + strlen(ans), ext, 5);
				write_pcm(signals[i].buffer, signals[i].number * 2, path);
				free(path);
				chdir("..");
			}
		}
		else
		{
			/*laço de reconhecimento*/	
			puts("analisando dados...");
			word *words = malloc(sizeof(word));
			double best = 1e10;
			char *name = NULL;
			void **word_adresses;
			unsigned int n = 0, i = 0, count = 0;
			if ((n = get_list(words)))
			{
				word_adresses = malloc(n * sizeof(void *));
				while (words != NULL)
				{
					double now = compare(mfcc_frames, frame_n, words->frames, words->n);
					word_adresses[count++] = words;
					if (now < best)
					{
						best = now;
						name = words->name;
					}
					words = words->next;
				}
				for (i = 0; i < count; i++)
					free(word_adresses[i]);
				free(word_adresses);
			}
			if (best < 3.5)
				printf("%f %s", best, name);
		}
		free(mfcc_frames);
		free(frames);
	}
	if (flag)
		printf("\n");
	free(buffer);
	
}
/* Fill the sentence with new words: in "page" mode, fills the page
   with text; in "scroll" mode, just makes one long horizontal sentence.
   The sentence might have *no* words in it, if no text is currently
   available.
 */
static void
populate_sentence (state *s, sentence *se)
{
  int i = 0;
  int left, right, top, x, y;
  int space = 0;
  int line_start = 0;
  Bool done = False;

  int array_size = 100;

  se->move_chars_p = (s->mode == SCROLL ? False :
                      (random() % 3) ? False : True);
  se->alignment = (random() % 3);

  recolor (s, se);

  if (se->words)
    {
      for (i = 0; i < se->nwords; i++)
        free_word (s, se->words[i]);
      free (se->words);
    }

  se->words = (word **) calloc (array_size, sizeof(*se->words));
  se->nwords = 0;

  switch (s->mode)
    {
    case PAGE:
      left  = random() % (s->xgwa.width / 3);
      right = s->xgwa.width - (random() % (s->xgwa.width / 3));
      top = random() % (s->xgwa.height * 2 / 3);
      break;
    case SCROLL:
      left = 0;
      right = s->xgwa.width;
      top = random() % s->xgwa.height;
      break;
    default:
      abort();
      break;
    }

  x = left;
  y = top;

  while (!done)
    {
      char *txt = get_word_text (s);
      word *w;
      if (!txt)
        {
          if (se->nwords == 0)
            return;		/* If the stream is empty, bail. */
          else
            break;		/* If EOF after some words, end of sentence. */
        }

      if (! se->font)           /* Got a word: need a font now */
        {
          pick_font (s, se);
          if (y < se->font->ascent)
            y += se->font->ascent;
          space = XTextWidth (se->font, " ", 1);
        }

      w = new_word (s, se, txt, !se->move_chars_p);

      /* If we have a few words, let punctuation terminate the sentence:
         stop gathering more words if the last word ends in a period, etc. */
      if (se->nwords >= 4)
        {
          char c = w->text[strlen(w->text)-1];
          if (c == '.' || c == '?' || c == '!')
            done = True;
        }

      /* If the sentence is kind of long already, terminate at commas, etc. */
      if (se->nwords >= 12)
        {
          char c = w->text[strlen(w->text)-1];
          if (c == ',' || c == ';' || c == ':' || c == '-' ||
              c == ')' || c == ']' || c == '}')
            done = True;
        }

      if (se->nwords >= 25)  /* ok that's just about enough out of you */
        done = True;

      if (s->mode == PAGE &&
          x + w->rbearing > right)			/* wrap line */
        {
          align_line (s, se, line_start, x, right);
          line_start = se->nwords;

          x = left;
          y += se->font->ascent;

          /* If we're close to the bottom of the screen, stop, and 
             unread the current word.  (But not if this is the first
             word, otherwise we might just get stuck on it.)
           */
          if (se->nwords > 0 &&
              y + se->font->ascent > s->xgwa.height)
            {
              unread_word (s, w);
              /* done = True; */
              break;
            }
        }

      w->target_x = x + w->lbearing;
      w->target_y = y - w->ascent;

      x += w->rbearing + space;
      se->width = x;

      if (se->nwords >= (array_size - 1))
        {
          array_size += 100;
          se->words = (word **) realloc (se->words,
                                         array_size * sizeof(*se->words));
          if (!se->words)
            {
              fprintf (stderr, "%s: out of memory (%d words)\n",
                       progname, array_size);
              exit (1);
            }
        }

      se->words[se->nwords++] = w;
    }

  se->width -= space;

  switch (s->mode)
    {
    case PAGE:
      align_line (s, se, line_start, x, right);
      if (se->move_chars_p)
        split_words (s, se);
      scatter_sentence (s, se);
      shuffle_words (s, se);
      break;
    case SCROLL:
      aim_sentence (s, se);
      break;
    default:
      abort();
      break;
    }

# ifdef DEBUG
  if (s->debug_p)
    {
      fprintf (stderr, "%s: sentence %d:", progname, se->id);
      for (i = 0; i < se->nwords; i++)
        fprintf (stderr, " %s", se->words[i]->text);
      fprintf (stderr, "\n");
    }
# endif
}