int main(int argc, char *argv[]) { AutoData *Data; doublereal u[3] = {0., 0., 0.}; integer ipar[3] = {0, 1, 2}; doublereal par[3] = {0., 14., 2.}; Data = (AutoData *)MALLOC(sizeof(AutoData)); BlankData(Data); DefaultData(Data); // Equilibrium points CreateSpecialPoint(Data,3,1,u,3,ipar,par,NULL,NULL,NULL,NULL); // 9 = Beginning point, 1 = branch label Data->iap.irs = 1; // Start from this point Data->print_input = 0; Data->print_output = 0; printf("\nEquilibrium points...\n"); AUTO(Data); system("touch d.ab"); system("cat fort.9 >> d.ab"); system("rm fort.9"); // Periodic orbits CleanupSolution(Data); DefaultData(Data); Data->iap.ips = 2; // BVP Data->iap.irs = 4; // Label of Hopf point Data->iap.ilp = 0; // No detection of folds Data->iap.nicp = 2; // Number of free parameters Data->iap.nmx = 150; // Number of points on branch Data->iap.npr = 30; // Output point and cycle after every npr steps Data->rap.dsmax = 0.5; // Maximum arclength stepsize Data->icp = (integer *)REALLOC(Data->icp,Data->iap.nicp*sizeof(integer)); Data->icp[1] = 10; // Adds period to free parameters printf("\nPeriodic orbits...\n"); AUTO(Data); system("touch d.ab"); system("cat fort.9 >> d.ab"); system("rm fort.9"); // Fold points CleanupSolution(Data); DefaultData(Data); Data->iap.irs = 2; // Label of limit point Data->iap.nicp = 2; // Number of free parameters Data->iap.isp = 1; // Turn on detection of branch points Data->iap.isw = 2; // Controls branch switching (?) Data->rap.dsmax = 0.5; // Maximum arclength stepsize Data->icp[1] = 2; // 3rd parameter is free printf("\nFold points...\n"); AUTO(Data); system("touch d.ab"); system("cat fort.9 >> d.ab"); system("rm fort.9"); // Fold points (reverse) CleanupSolution(Data); DefaultData(Data); Data->iap.irs = 2; // Label of limit point Data->iap.nicp = 2; // Number of free parameters Data->iap.isp = 1; // Turn on detection of branch points Data->iap.isw = 2; // Controls branch switching (?) Data->rap.dsmax = 0.5; // Maximum arclength stepsize Data->icp[1] = 2; // 3rd parameter is free Data->rap.ds = -0.01; // Stepsize (reverse) printf("\nFold points (reverse)...\n"); AUTO(Data); system("touch d.ab"); system("cat fort.9 >> d.ab"); system("rm fort.9"); // Hopf points (reverse) CleanupSolution(Data); DefaultData(Data); Data->iap.irs = 4; // Label of hopf point Data->iap.nicp = 2; // Number of free parameters Data->iap.isw = 2; // Controls branch switching (?) Data->rap.dsmax = 0.5; // Maximum arclength stepsize Data->icp[1] = 2; // 3rd parameter is free Data->rap.ds = -0.01; // Stepsize (reverse) printf("\nHopf points (reverse)...\n"); AUTO(Data); system("touch d.ab"); system("cat fort.9 >> d.ab"); system("rm fort.9"); CleanupAll(Data); return 0; }
gchar *cairo_dock_edit_themes (GHashTable **hThemeTable, gboolean bSafeMode) { //\___________________ On recupere la liste des themes existant (pre-installes et utilisateur). GError *erreur = NULL; gchar *cThemesDir = CAIRO_DOCK_SHARE_THEMES_DIR; *hThemeTable = cairo_dock_list_themes (cThemesDir, NULL, &erreur); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); erreur = NULL; } g_hash_table_insert (*hThemeTable, g_strdup (""), g_strdup ("")); cThemesDir = g_strdup_printf ("%s/%s", g_cCairoDockDataDir, CAIRO_DOCK_THEMES_DIR); *hThemeTable = cairo_dock_list_themes (cThemesDir, *hThemeTable, &erreur); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); erreur = NULL; } GHashTable *hUserThemeTable = cairo_dock_list_themes (cThemesDir, NULL, NULL); g_free (cThemesDir); gchar *cUserThemeNames = cairo_dock_write_table_content (hUserThemeTable, (GHFunc) cairo_dock_write_one_name, TRUE, FALSE); //\___________________ On cree un fichier de conf temporaire. const gchar *cTmpDir = g_get_tmp_dir (); gchar *cTmpConfFile = g_strdup_printf ("%s/cairo-dock-init", cTmpDir); gchar *cCommand = g_strdup_printf ("cp %s/%s %s", CAIRO_DOCK_SHARE_DATA_DIR, CAIRO_DOCK_THEME_CONF_FILE, cTmpConfFile); system (cCommand); g_free (cCommand); //\___________________ On met a jour ce fichier de conf. GKeyFile *pKeyFile = g_key_file_new (); g_key_file_load_from_file (pKeyFile, cTmpConfFile, G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, &erreur); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); return NULL; } cairo_dock_update_conf_file_with_themes (pKeyFile, cTmpConfFile, *hThemeTable, "Themes", "chosen theme"); cairo_dock_update_conf_file_with_hash_table (pKeyFile, cTmpConfFile, hUserThemeTable, "Delete", "wanted themes", NULL, (GHFunc) cairo_dock_write_one_name, TRUE, FALSE); cairo_dock_update_conf_file_with_hash_table (pKeyFile, cTmpConfFile, hUserThemeTable, "Save", "theme name", NULL, (GHFunc) cairo_dock_write_one_name, TRUE, FALSE); g_hash_table_destroy (hUserThemeTable); g_key_file_set_string (pKeyFile, "Delete", "wanted themes", cUserThemeNames); // sThemeNames g_free (cUserThemeNames); cairo_dock_write_keys_to_file (pKeyFile, cTmpConfFile); g_key_file_free (pKeyFile); //\___________________ On laisse l'utilisateur l'editer. gchar *cPresentedGroup = (cairo_dock_theme_need_save () ? "Save" : NULL); const gchar *cTitle = (bSafeMode ? _("< Safe Mode >") : _("Manage Themes")); CairoDialog *pDialog = NULL; if (bSafeMode) { pDialog = cairo_dock_show_general_message (_("You are running Cairo-Dock in safe mode.\nWhy ? Probably because a plug-in has messed into your dock,\n or maybe your theme has got corrupted.\nSo, no plug-in will be available, and you can now save your current theme if you want\n before you start using the dock.\nTry with your current theme, if it works, it means a plug-in is wrong.\nOtherwise, try with another theme.\nSave a config that is working, and restart the dock in normal mode.\nThen, activate plug-ins one by one to guess which one is wrong."), 0.); } gboolean bChoiceOK = cairo_dock_edit_conf_file (NULL, cTmpConfFile, cTitle, CAIRO_DOCK_THEME_PANEL_WIDTH, CAIRO_DOCK_THEME_PANEL_HEIGHT, 0, cPresentedGroup, NULL, NULL, NULL, NULL); if (! bChoiceOK) { g_remove (cTmpConfFile); g_free (cTmpConfFile); cTmpConfFile = NULL; } if (bSafeMode) cairo_dock_dialog_unreference (pDialog); return cTmpConfFile; }
static int makeflow_s3_archive_copy_task_files(struct archive_instance *a, char *id, char *task_path, struct batch_task *t){ char *taskTarFile = string_format("%s/%s",task_path,id); // Check to see if the task is already in the local archive so it is not downloaded twice if(access(taskTarFile,R_OK) != 0){ // Copy tar file from the s3 bucket struct timeval start_time; struct timeval end_time; char *copyTar = string_format("%s/%s",task_path,id); FILE *taskFile = fopen(copyTar,"wb"); gettimeofday(&start_time,NULL); if(s3_get(taskFile,id) != 0){ gettimeofday(&end_time,NULL); float run_time = ((end_time.tv_sec*1000000 + end_time.tv_usec) - (start_time.tv_sec*1000000 + start_time.tv_usec)) / 1000000.0; total_down_time += run_time; debug(D_MAKEFLOW_HOOK," It took %f seconds for %s to fail downloading to %s",run_time, id, a->s3_dir); debug(D_MAKEFLOW_HOOK," The total download time is %f second(s)",total_down_time); free(copyTar); return 0; } gettimeofday(&end_time,NULL); float run_time = ((end_time.tv_sec*1000000 + end_time.tv_usec) - (start_time.tv_sec*1000000 + start_time.tv_usec)) / 1000000.0; total_down_time += run_time; printf("Download %s from %s/%s\n",id,a->s3_dir,id); debug(D_MAKEFLOW_HOOK," It took %f seconds for %s to download from %s",run_time, id, a->s3_dir); debug(D_MAKEFLOW_HOOK," The total download time is %f second(s)",total_down_time); free(copyTar); fclose(taskFile); char *extractTar = string_format("tar -xzvf %s/%s -C %s",task_path,id,task_path); if(system(extractTar) == -1){ free(extractTar); return 0; } free(extractTar); struct batch_file *f; struct list_cursor *cur = list_cursor_create(t->output_files); // Iterate through output files for(list_seek(cur, 0); list_get(cur, (void**)&f); list_next(cur)) { char *output_file_path = string_format("%s/output_files/%s", task_path, basename(f->inner_name)); char buf[1024]; ssize_t len; // Read what the symlink is actually pointing to if((len = readlink(output_file_path, buf, sizeof(buf)-1)) != -1) buf[len] = '\0'; free(output_file_path); // Grabs the actual name of the file from the buffer char *file_name = basename(buf); debug(D_MAKEFLOW_HOOK,"The FILE_NAME is %s",file_name); // Check to see if the file was already copied to the /files/ directory char *filePath = string_format("%s/files/%.2s/%s",a->dir,file_name,file_name); char *fileDir = string_format("%s/files/%.2s",a->dir,file_name); if(access(filePath,R_OK) != 0){ debug(D_MAKEFLOW_HOOK,"COPYING %s to /files/ from the s3 bucket",file_name); // Copy the file to the local archive /files/ directory gettimeofday(&start_time,NULL); create_dir(fileDir,0777); FILE *fileLocal = fopen(filePath, "wb"); if(s3_get(fileLocal, file_name) != 0){ gettimeofday(&end_time,NULL); run_time = ((end_time.tv_sec*1000000 + end_time.tv_usec) - (start_time.tv_sec*1000000 + start_time.tv_usec)) / 1000000.0; total_down_time += run_time; debug(D_MAKEFLOW_HOOK," It took %f seconds for %s to fail downloading from %s",run_time, id, a->s3_dir); debug(D_MAKEFLOW_HOOK," The total download time is %f second(s)",total_down_time); return 0; } gettimeofday(&end_time,NULL); run_time = ((end_time.tv_sec*1000000 + end_time.tv_usec) - (start_time.tv_sec*1000000 + start_time.tv_usec)) / 1000000.0; total_down_time += run_time; printf("Download %s from %s/%s\n",file_name,a->s3_dir, file_name); debug(D_MAKEFLOW_HOOK," It took %f seconds for %s to download from %s",run_time, id, a->s3_dir); debug(D_MAKEFLOW_HOOK," The total download time is %f second(s)",total_down_time); fclose(fileLocal); //Extract the tar file of a directory (always run even if it isnt a tar file) char *extractDirTar = string_format("tar -xzvf %s -C %s/foo >&/dev/null",filePath,fileDir); char *makeDir = string_format("mkdir %s/foo",fileDir); system(makeDir); free(makeDir); if(system(extractDirTar) != 0){ debug(D_MAKEFLOW_HOOK,"%s is either a file or the tar file could not be extracted",file_name); free(extractDirTar); char *removeFooDir = string_format("rm -rf %s/foo",fileDir); system(removeFooDir); continue; } char *removeTar = string_format("rm %s",filePath); system(removeTar); free(removeTar); char *renameFile = string_format("mv %s/foo %s", fileDir, filePath); system(renameFile); free(renameFile); free(extractDirTar); } free(fileDir); free(filePath); } free(taskTarFile); return 1; } debug(D_MAKEFLOW_HOOK,"TASK already exist in local archive, not downloading from s3 bucket"); free(taskTarFile); return 1; }
/////////////// DO FUNCTIONS /////////////////// void do_kingdom(CHAR_DATA * ch, char *argument) { KINGDOM_DATA *kingdom; CHAR_DATA *vch = 0; DESCRIPTOR_DATA *d = 0; char buf[MAX_STRING_LENGTH]; char arg1[MAX_STRING_LENGTH]; char arg2[MAX_STRING_LENGTH]; char arg3[MAX_STRING_LENGTH]; long id = 0; long i = 0; if(IS_NPC(ch)) return; smash_tilde(argument); argument = one_argument_case(argument, arg1); argument = one_argument_case(argument, arg2); strcpy(arg3, argument); if(IS_IMMORTAL(ch) && ch->level == MAX_LEVEL) { if(!str_cmp(arg1, "save")) { write_kingdoms(); sprintf(buf,"cp %s %s.bak",KINGDOM_FILE,KINGDOM_FILE); system(buf); send_to_char("Done, and made backup.\n\r", ch); return; } if(arg1[0] == '\0') { send_to_char("Syntax: kingdom create\n\r", ch); return; } if(!str_cmp(arg1, "create")) { create_kingdom(); write_kingdoms(); send_to_char("Done.\n\r", ch); return; } if((!is_number(arg1) || !str_cmp(arg1, "help"))) { send_to_char("Syntax: kingdom <id #> <attribute> <value>\n\r", ch); send_to_char(" kingdom <id #> delete\n\r", ch); send_to_char("\n\r", ch); send_to_char("Attributes:\n\r", ch); send_to_char(" leader name points pks pds realpoints\n\r", ch); send_to_char(" noansiname\n\r", ch); send_to_char("\n\r", ch); } else { id = atoi(arg1); if((kingdom = get_kingdom(id)) == &kingdom_default) { send_to_char("There is no such kingdom with that ID.\n\r", ch); return; } if(!str_cmp(arg2, "leader")) { if((vch = get_char_world(ch, arg3)) == 0) { send_to_char("The leader must be logged on.\n\r", ch); return; } free_string(kingdom->leader); kingdom->leader = str_dup(arg3); vch->pcdata->kingdom = id; send_to_char("Done.\n\r", ch); return; } if(!str_cmp(arg2, "name")) { free_string(kingdom->name); kingdom->name = str_dup(arg3); send_to_char("Done.\n\r", ch); return; } if(!str_cmp(arg2, "noansiname")) { free_string(kingdom->noansiname); kingdom->noansiname = str_dup(arg3); send_to_char("Done.\n\r", ch); return; } if(!str_cmp(arg2, "delete") && !str_cmp(arg3, "yes")) { delete_kingdom(kingdom->id); return; } i = atoi(arg3); if(!str_cmp(arg2, "points")) { kingdom->points = i; send_to_char("Done.\n\r", ch); return; } if(!str_cmp(arg2, "realpoints")) { kingdom->realpoints = i; send_to_char("Done.\n\r", ch); return; } if(!str_cmp(arg2, "pds")) { kingdom->pds = i; send_to_char("Done.\n\r", ch); return; } if(!str_cmp(arg2, "pks")) { kingdom->pks = i; send_to_char("Done.\n\r", ch); return; } if(!str_cmp(arg2, "assists")) { kingdom->assists = i; send_to_char("Done.\n\r", ch); return; } } } if(ch->pcdata->kingdom == 0) // player not in a kingdom { if(!str_cmp(arg1, "create")) { if(ch->pcdata->quest < 1000) { send_to_char("You need 1000 quest points to create a new kingdom.\n\r", ch); return; } if(!arg2 || arg2[0] == '\0' || !arg3 || arg3[0] == '\0') { send_to_char ("Syntax (DO NOT MESS THIS UP!): kingdom create \"name WITH ansi\" \"name WITHOUT ansi\"\n\r", ch); send_to_char("I suggest you SAY the name a few times to make SURE THE ANSI IS CORRECT.\n\r", ch); send_to_char("And if you dont put a final {{x your kingdom will be DELETED.\n\r", ch); send_to_char("If your kingdom name has more than one word surround it in QUOTES!\n\r", ch); return; } if(ansistrlen(arg2) > 20 || strlen(arg3) > 20) { send_to_char("String length is limited to 20 characters!\n\r", ch); return; } kingdom = create_kingdom(); ch->pcdata->kingdom = kingdom->id; ch->pcdata->quest -= 1000; free_string(kingdom->leader); kingdom->leader = str_dup(ch->name); free_string(kingdom->name); kingdom->name = str_dup(arg2); free_string(kingdom->noansiname); kingdom->noansiname = str_dup(arg3); kingdom_message(0, "%s has {WCREATED{X The %s Kingdom!", ch->name, kingdom->name); write_kingdoms(); return; } if(ch->pcdata->kingdom_invite == 0) { send_to_char("You don't belong to a kingdom.\n\r", ch); return; } // make sure kingdom still exists if(get_kingdom(ch->pcdata->kingdom_invite) == &kingdom_default) { send_to_char("That kingdom was destroyed.\n\r", ch); return; } if(!str_cmp(arg1, "accept")) { add_member(ch->pcdata->kingdom_invite, ch); return; } if(!str_cmp(arg1, "decline")) { send_to_char("You decline the kingdom's invitation.\n\r", ch); if((vch = get_char_world(ch, get_kingdom(ch->pcdata->kingdom_invite)->leader)) != 0) { sprintf(buf, "%s has declined your invitation.\n\r", ch->name); send_to_char(buf, vch); } ch->pcdata->kingdom_invite = 0; return; } send_to_char("Type either kingdom accept or kingdom decline.\n\r", ch); return; } kingdom = get_kingdom(ch->pcdata->kingdom); if(!str_cmp(arg1, "leave") && !str_cmp(arg2, "for") && !str_cmp(arg3, "good")) { send_to_char("You leave the kingdom!\n\r", ch); remove_member(kingdom->id, ch->name); remove_trustee(kingdom->id, ch->name); return; } if(!str_prefix(arg1, "report")) { long percent; char *color; buf[0] = '\0'; sprintf(buf, "%-4s %-12s{X %5s :: %s\n\r", "CMBT", "Name", "Hits", "Room" ); for(d = descriptor_list; d; d = d->next) { if(d->connected != CON_PLAYING || !(vch = d->character) || vch->pcdata->kingdom != kingdom->id) continue; percent = (long) ((float) UMAX(1, vch->hit) / (float) UMAX(1, vch->max_hit) * 100); if(percent < 10) color = "{R"; else if(percent < 40) color = "{B"; else if(percent < 70) color = "{Y"; else color = "{C"; sprintf(buf + strlen(buf), "%-4s %s%-12s{X %5li :: %s\n\r", vch->fighting ? !IS_NPC(vch->fighting) ? "{R(PK){X" : "{r(F){X" : "", color, vch->name, vch->hit, !vch->in_room ? "somewhere" : vch->in_room->name); } send_to_char(buf, ch); return; } if(!is_trustee(ch, kingdom->id)) { send_to_char("Only leaders and trustees have power to modify their kingdom.\n\r", ch); return; } if(arg1[0] == '\0' || arg2[0] == '\0') { if(is_leader(ch, kingdom->id) || IS_IMMORTAL(ch)) { send_to_char("Syntax:\n\r", ch); send_to_char(" kingdom report\n\r", ch); send_to_char(" kingdom invite <player>\n\r", ch); send_to_char(" kingdom outcast <member>\n\r", ch); send_to_char(" kingdom war <kingdom ID>\n\r", ch); send_to_char(" kingdom treaty <kingdom ID>\n\r", ch); send_to_char(" kingdom rank <member> <rank>\n\r", ch); send_to_char(" kingdom trust <member>\n\r", ch); send_to_char(" kingdom recall\n\r", ch); send_to_char("\n\r", ch); } send_to_char("Syntax: kingdom scry <person>\n\r", ch); return; } if(is_leader(ch, kingdom->id)) { if(!str_cmp(arg1, "recall")) { if(kingdom->points < KINGDOM_RECALL_COST) { sprintf(buf, "It costs %d kingdom points to set a recall point.\n\r", KINGDOM_RECALL_COST); send_to_char(buf, ch); return; } if(ch->in_room == 0) { send_to_char("You are in a 0 room, eek.\n\r", ch); return; } kingdom->points -= KINGDOM_RECALL_COST; kingdom->recall = ch->in_room->vnum; kingdom_message(kingdom->id, "{MThe Kingdom Recall has been set to -> [%s]", ch->in_room->name); return; } if(!str_cmp(arg1, "trust")) { if((vch = get_char_world(ch, arg2)) == 0 || IS_NPC(vch)) { send_to_char("They need to be logged on.\n\r", ch); return; } if(vch->pcdata->kingdom != ch->pcdata->kingdom) { send_to_char("They aren't in your kingdom!\n\r", ch); return; } arg2[0] = UPPER(arg2[0]); if( strstr(kingdom->trustees, arg2) == 0 ) add_trustee(kingdom->id, vch); else remove_trustee(kingdom->id, arg2); return; } if(!str_cmp(arg1, "invite")) { if((vch = get_char_world(ch, arg2)) == 0) { send_to_char("They aren't logged on.\n\r", ch); return; } if(IS_NPC(vch)) { send_to_char("That's an NPC.\n\r", ch); return; } if(vch->pcdata->kingdom) { send_to_char("They are already a part of another kingdom!\n\r", ch); return; } vch->pcdata->kingdom_invite = ch->pcdata->kingdom; sprintf(buf, "You are invited to join the %s Kingdom by %s.\n\r" "Type kingdom accept or kingdom decline.\n\r", kingdom->name, ch->name); send_to_char(buf, vch); sprintf(buf, "You invite %s to join your glorious kingdom.\n\r", vch->name); send_to_char(buf, ch); return; } if(!str_cmp(arg1, "outcast")) { arg2[0] = UPPER(arg2[0]); if( strstr(kingdom->members, arg2) == 0 ) { send_to_char("That person isn't a member!\n\r",ch); return; } if(remove_member(ch->pcdata->kingdom, arg2)) kingdom_message(0, "%s has been outcasted from the %s Kingdom!", capitalize(arg2), kingdom->name); remove_trustee(kingdom->id, arg2); return; } if(!str_cmp(arg1, "treaty")) { if(kingdom->treaty_pending) { if(!get_kingdom(kingdom->treaty_pending)) { kingdom->treaty_pending = 0; return; } if(has_treaty(kingdom->id, kingdom->treaty_pending)) { send_to_char("You already have a treaty with them.\n\r", ch); return; } if(!str_cmp(arg2, "accept")) { add_treaty(kingdom->id, kingdom->treaty_pending); kingdom->treaty_pending = 0; return; } if(!str_cmp(arg2, "decline")) { kingdom_message(kingdom->id, "Your kingdom declines a treaty with the %s Kingdom.", get_kingdom(kingdom->treaty_pending)->name); kingdom_message(kingdom->treaty_pending, "%s Kingdom has declined your treaty offer.", kingdom->name); kingdom->treaty_pending = 0; return; } sprintf(buf, "You have a treaty offer pending with the %s Kingdom.\n\r" "Please type kingdom treaty accept or kingdom treaty decline.\n\r", get_kingdom(kingdom->treaty_pending)->name); send_to_char(buf, ch); return; } if(!is_number(arg2) || get_kingdom(atoi(arg2)) == &kingdom_default) { send_to_char("There is no such kingdom to make a treaty with.\n\r", ch); return; } i = atoi(arg2); if(kingdom->id == i) { send_to_char("You already have a treaty with yourself, smart one.\n\r", ch); return; } if(is_at_war(kingdom->id, i)) { send_to_char("You are at {RWAR{N with that kingdom!\n\r", ch); return; } if(has_treaty(kingdom->id, i)) { remove_treaty(kingdom->id, i); return; } if(get_kingdom(i)->treaty_pending) { send_to_char("They are already pending a treaty confirmation.\n\r", ch); return; } get_kingdom(i)->treaty_pending = kingdom->id; kingdom_message(i, "The %s Kingdom is asking for a treaty with your kingdom.", kingdom->name); kingdom_message(kingdom->id, "You ask the %s Kingdom for a treaty.", get_kingdom(i)->name); return; } if(!str_cmp(arg1, "war")) { if(!is_number(arg2) || get_kingdom(atoi(arg2)) == &kingdom_default) { send_to_char("There is no such kingdom to make war with.\n\r", ch); return; } i = atoi(arg2); if(i == kingdom->id) { send_to_char("That wouldn't be a very smart political move.\n\r", ch); return; } if(get_kingdom(i) == &kingdom_default) { send_to_char("That kingdom doesn't exist.\n\r", ch); return; } if(has_treaty(kingdom->id, i)) { send_to_char("But you have a treaty with them!\n\r", ch); return; } if(is_at_war(kingdom->id, i)) { remove_war(kingdom->id, i); return; } add_war(kingdom->id, i); return; } if(!str_cmp(arg1, "rank")) { if(!arg3 || arg3[0] == '\0') { send_to_char("Rank who as what?\n\r", ch); return; } if((vch = get_char_world(ch, arg2)) == 0 || IS_NPC(vch)) { send_to_char("They aren't on at the moment.\n\r", ch); return; } if(vch->pcdata->kingdom != ch->pcdata->kingdom) { send_to_char("They aren't apart of your kingdom!\n\r", ch); return; } if(ansistrlen(arg3) > 15) { send_to_char("String length is limited to 20 characters.\n\r", ch); return; } free_string(vch->pcdata->krank); if(!str_cmp(arg3, "clear")) { vch->pcdata->krank = str_dup(""); return; } arg3[0] = UPPER(arg3[0]); vch->pcdata->krank = str_dup(arg3); send_to_char("Done.\n\r", ch); return; } } if(!str_cmp(arg1, "scry")) { if(arg2[0] == '\0') { send_to_char("You must supply the name of the person.\n\r", ch); return; } if((vch = get_char_world(ch, arg2)) == 0 || IS_NPC(vch)) { send_to_char("They are not online.\n\r", ch); return; } if(kingdom->points < KINGDOM_SCRY_COST) { sprintf(buf, "It costs %d Kingdom Points to do this.\n\r", KINGDOM_SCRY_COST); send_to_char(buf, ch); return; } kingdom_message(kingdom->id, "%s has {cscryed{N %s {C. o O{N ({C%s{N)", ch->name, vch->name, vch->in_room == 0 ? "Nowhere" : vch->in_room->name); kingdom->points -= KINGDOM_SCRY_COST; return; } // default message do_kingdom(ch, "blah"); }
// Find files in the specified directory matching the file wildcard int FileList::FindFiles(std::string dir, std::string file, std::list<std::string> &dirs, std::list<std::string> &files) { std::string dir_sep = (dir.empty() == false) ? dir + DIR_SEPARATOR_STR : ""; // Get the current search path std::string path = dir_sep + file; // If the file does not contain a wildcard add as is if(strchr(file.c_str(), '*') == NULL) { int size = 0; if(File::IsFile(path.c_str(), &size) == true) { files.push_back(path); _size += size; return 0; } } #ifdef WIN32 struct _finddata_t fileInfo; int searchHandle = _findfirst(path.c_str(), &fileInfo); if(searchHandle == -1) return 0; do { // If a file is found, add it to the list if(File::IsFile(&fileInfo)) { std::string foundFile = dir_sep; foundFile += fileInfo.name; files.push_back(foundFile); // Total size in bytes _size += fileInfo.size; } else // if a directory found (skipping "." and "..") and to the directory list for further processing if(File::IsDirectory(&fileInfo)) { std::string foundDir = dir_sep; foundDir += fileInfo.name; dirs.push_back(foundDir); } } while(_findnext(searchHandle, &fileInfo) == 0); _findclose(searchHandle); #else // Get the name of temporary file to store directory listing char temp[256]; *temp = '\x0'; sprintf(temp, "sl_ls_%d.txt", getpid()); std::string command = "ls -1 -d "; command += path; command += " 2>/dev/null > "; command += temp; // Read matched files if(system(command.c_str()) != -1) { FILE *file = fopen(temp, "r"); char fileName[1024]; *fileName = '\x0'; if(file) { // Read file content line by line while(fgets(fileName, 1024, file)) { // Remove new line from path, otherwise stat() will fail int len = strlen(fileName); if(len && fileName[len-1] == '\n') fileName[len-1] = '\x0'; int size = 0; bool file = File::IsFile(fileName, &size); bool dir = File::IsDirectory(fileName); if(file == true) { files.push_back(fileName); _size += size; } } } fclose(file); } // delete the temporary file unlink(temp); #endif return 0; }
bool Application::openURL(const std::string &url) { std::string op = std::string("open ").append(url); return system(op.c_str())!=-1; }
/* proceeds installation/deinstallation/update action */ void proceed_action(List *l) { extern List *lcats; extern Config config; extern bool redraw_dimensions; Iter itr = l->head; Iter citr; /* cat iterator */ Iter oitr; /* option iterator */ Iter ditr; /* dependency iterator */ Port *p; char execstr[1000]; char option[MAX_TOKEN]; char wdir[MAX_PATH]; int result = 0; /* leaving curses ... */ def_prog_mode(); /* save current tty modes */ endwin(); /* restore original tty modes */ getcwd(wdir, MAX_PATH); /* action loop */ while ((itr != NULL) && (result == 0)) { if (((Port *)itr->item)->type == PORT) { p = (Port *)itr->item; if (p->lopts != NULL) oitr = p->lopts->head; switch (p->state) { case STATE_INSTALL: sprintf(execstr, "%s %s", config.make_cmd, config.make_target[MK_TARGET_INST]); break; case STATE_UPDATE: sprintf(execstr, "%s %s", config.make_cmd, config.make_target[MK_TARGET_UPDATE]); break; case STATE_DEINSTALL: sprintf(execstr, "%s %s", config.make_cmd, config.make_target[MK_TARGET_DEINST]); break; } /* cat compile options */ while (oitr != NULL) { Option *opt = (Option *)oitr->item; if (opt->state == STATE_SELECTED) { sprintf(option, " %s", opt->arg); strcat(execstr, option); } oitr = oitr->next; } /* fire up make */ chdir(p->path); result = system(execstr); switch (result) { case -1: error("fork() could not be invoked"); return; break; case 127: error("execution of shell failed"); return; break; case 0: /* build/installation/deinstallation successful */ switch (p->state) { case STATE_INSTALL: case STATE_UPDATE: p->state = STATE_INSTALLED; ditr = p->lbdep->head; while (ditr != NULL) { if (((Port *)ditr->item)->state != STATE_INSTALLED) ((Port *)ditr->item)->state = STATE_INSTALLED; ditr = ditr->next; } ditr = p->lrdep->head; while (ditr != NULL) { if (((Port *)ditr->item)->state != STATE_INSTALLED) ((Port *)ditr->item)->state = STATE_INSTALLED; ditr = ditr->next; } break; case STATE_DEINSTALL: p->state = STATE_NOT_SELECTED; break; } break; } } itr = itr->next; } chdir(wdir); refresh_cat_states(); /* ... coming back to curses */ refresh(); redraw_dimensions = TRUE; }
//Método Main - Entry Point do Programa int mainJogoDeDados() { //Declaração de variáveis locais double valorApostado = 0.0; double valorGanhoNaPartida = 0.0; double saldoDoJogador = 0.0; int valorDoPrimeiroDadoDoJogador; int valorDoSegundoDadoDoJogador; int valorDoPrimeiroDadoDoCroupier; int valorDoSegundoDadoDoCroupier; bool dadosDeEntradaValidos = true; bool sairDaColetaDeDadosDoJogo = false; int quantidadeDePartidas = 0; int quantidadeDePartidasSemGanhos = 0; double maiorValorGanhoEmUmaPartida = MENOR_VALOR_DE_APOSTA_POSSIVEL; int contadoresDeValoresDeDadoQueSairam[TAMANHO_DO_VETOR_DE_VALORES_DE_DADO_QUE_SAIRAM]; int maiorValorDeDadoQueSaiu = 0; //zerar vetor de contadores de valores dos dados que sairam for (int i = 0; i < TAMANHO_DO_VETOR_DE_VALORES_DE_DADO_QUE_SAIRAM; i++) { contadoresDeValoresDeDadoQueSairam[i] = 0; } //Título do Programa e autor printf(" << UEFS - PGCA 2014.1 - Programa Jogo de Dados>>"); printf("\n\n ## Autor: Leonardo Melo"); do{ do{ dadosDeEntradaValidos = true; printf_s("\n\n\nDigite o valor apostado (R$): "); scanf_s("%lf", &valorApostado); fflush(stdin); if (valorApostado <= VALOR_MAXIMO_DE_FINALIZACAO_DO_JOGO) { sairDaColetaDeDadosDoJogo = true; break; } if (valorApostado < MENOR_VALOR_DE_APOSTA_POSSIVEL) { printf_s("\n\nEntrada Invalida!\nO valor apostado nao pode ser menor que R$ %.2lf.", MENOR_VALOR_DE_APOSTA_POSSIVEL); dadosDeEntradaValidos = false; } } while (!dadosDeEntradaValidos); if (sairDaColetaDeDadosDoJogo) { break; } quantidadeDePartidas++; saldoDoJogador -= valorApostado; do{ dadosDeEntradaValidos = true; printf_s("\n\nDigite o valor do primeiro dado do jogador: "); scanf_s("%d", &valorDoPrimeiroDadoDoJogador); fflush(stdin); if (valorDoPrimeiroDadoDoJogador > MAIOR_VALOR_DE_UM_DADO || valorDoPrimeiroDadoDoJogador < MENOR_VALOR_DE_UM_DADO) { printf_s("\n\nEntrada Invalida!\nO valor do dado nao pode ser menor que %d ou maior que %d.", MENOR_VALOR_DE_UM_DADO, MAIOR_VALOR_DE_UM_DADO); dadosDeEntradaValidos = false; } } while (!dadosDeEntradaValidos); contadoresDeValoresDeDadoQueSairam[valorDoPrimeiroDadoDoJogador - 1]++; do{ dadosDeEntradaValidos = true; printf_s("\n\nDigite o valor do segundo dado do jogador: "); scanf_s("%d", &valorDoSegundoDadoDoJogador); fflush(stdin); if (valorDoSegundoDadoDoJogador > MAIOR_VALOR_DE_UM_DADO || valorDoSegundoDadoDoJogador < MENOR_VALOR_DE_UM_DADO) { printf_s("\n\nEntrada Invalida!\nO valor do dado nao pode ser menor que %d ou maior que %d.", MENOR_VALOR_DE_UM_DADO, MAIOR_VALOR_DE_UM_DADO); dadosDeEntradaValidos = false; } } while (!dadosDeEntradaValidos); contadoresDeValoresDeDadoQueSairam[valorDoSegundoDadoDoJogador - 1]++; do{ dadosDeEntradaValidos = true; printf_s("\n\nDigite o valor do primeiro dado do croupier: "); scanf_s("%d", &valorDoPrimeiroDadoDoCroupier); fflush(stdin); if (valorDoPrimeiroDadoDoCroupier > MAIOR_VALOR_DE_UM_DADO || valorDoPrimeiroDadoDoCroupier < MENOR_VALOR_DE_UM_DADO) { printf_s("\n\nEntrada Invalida!\nO valor do dado nao pode ser menor que %d ou maior que %d.", MENOR_VALOR_DE_UM_DADO, MAIOR_VALOR_DE_UM_DADO); dadosDeEntradaValidos = false; } } while (!dadosDeEntradaValidos); contadoresDeValoresDeDadoQueSairam[valorDoPrimeiroDadoDoCroupier - 1]++; do{ dadosDeEntradaValidos = true; printf_s("\n\nDigite o valor do segundo dado do croupier: "); scanf_s("%d", &valorDoSegundoDadoDoCroupier); fflush(stdin); if (valorDoSegundoDadoDoCroupier > MAIOR_VALOR_DE_UM_DADO || valorDoSegundoDadoDoCroupier < MENOR_VALOR_DE_UM_DADO) { printf_s("\n\nEntrada Invalida!\nO valor do dado nao pode ser menor que %d ou maior que %d.", MENOR_VALOR_DE_UM_DADO, MAIOR_VALOR_DE_UM_DADO); dadosDeEntradaValidos = false; } } while (!dadosDeEntradaValidos); contadoresDeValoresDeDadoQueSairam[valorDoSegundoDadoDoCroupier - 1]++; bool ganhouAlgumValor = false; //resultao da partida (Calculos) if ((valorDoPrimeiroDadoDoJogador == valorDoPrimeiroDadoDoCroupier && valorDoSegundoDadoDoJogador == valorDoSegundoDadoDoCroupier) || (valorDoPrimeiroDadoDoJogador == valorDoSegundoDadoDoCroupier && valorDoSegundoDadoDoJogador == valorDoPrimeiroDadoDoCroupier)) { valorGanhoNaPartida = valorApostado * 6; ganhouAlgumValor = true; saldoDoJogador += valorGanhoNaPartida; if (maiorValorGanhoEmUmaPartida < valorGanhoNaPartida) { maiorValorGanhoEmUmaPartida = valorGanhoNaPartida; } printf_s("\n\nO jogador ganhou R$ %.2lf.", valorGanhoNaPartida); } if (!ganhouAlgumValor) { if ((valorDoPrimeiroDadoDoJogador + valorDoSegundoDadoDoJogador) == (valorDoPrimeiroDadoDoCroupier + valorDoSegundoDadoDoCroupier)) { valorGanhoNaPartida = valorApostado * 3; ganhouAlgumValor = true; saldoDoJogador += valorGanhoNaPartida; if (maiorValorGanhoEmUmaPartida < valorGanhoNaPartida) { maiorValorGanhoEmUmaPartida = valorGanhoNaPartida; } printf_s("\n\nO jogador ganhou R$ %.2lf.", valorGanhoNaPartida); } } if (!ganhouAlgumValor) { if (((valorDoPrimeiroDadoDoJogador + valorDoSegundoDadoDoJogador) % 2 == 0) && ((valorDoPrimeiroDadoDoCroupier + valorDoSegundoDadoDoCroupier) % 2 == 0) || ((valorDoPrimeiroDadoDoJogador + valorDoSegundoDadoDoJogador) % 2 != 0) && ((valorDoPrimeiroDadoDoCroupier + valorDoSegundoDadoDoCroupier) % 2 != 0)) { valorGanhoNaPartida = valorApostado / 2; ganhouAlgumValor = true; saldoDoJogador += valorGanhoNaPartida; if (maiorValorGanhoEmUmaPartida < valorGanhoNaPartida) { maiorValorGanhoEmUmaPartida = valorGanhoNaPartida; } printf_s("\n\nO jogador ganhou R$ %.2lf.", valorGanhoNaPartida); } } if (!ganhouAlgumValor) { valorGanhoNaPartida = 0.0; quantidadeDePartidasSemGanhos++; printf_s("\n\nO jogador perdeu."); } } while (true); printf_s("\n\n\n\nJogo Encerrado!"); printf_s("\n\n\nO jogador jogou %d vez(es).", quantidadeDePartidas); printf_s("\n\nO saldo final foi de %.2lf reais.", saldoDoJogador); for (int i = 0; i < TAMANHO_DO_VETOR_DE_VALORES_DE_DADO_QUE_SAIRAM; i++) { if (contadoresDeValoresDeDadoQueSairam[i] > maiorValorDeDadoQueSaiu) { maiorValorDeDadoQueSaiu = contadoresDeValoresDeDadoQueSairam[i]; } } for (int i = 0; i < TAMANHO_DO_VETOR_DE_VALORES_DE_DADO_QUE_SAIRAM; i++) { if (contadoresDeValoresDeDadoQueSairam[i] == maiorValorDeDadoQueSaiu) { printf_s("\n\nO valor do dado que mais saiu foi %d, %d vez(es).", i + 1, contadoresDeValoresDeDadoQueSairam[i]); } } printf_s("\n\nO maior valor ganho em uma partida foi %.2lf reais.", maiorValorGanhoEmUmaPartida); printf_s("\n\nO jogador perdeu %d vez(es).", quantidadeDePartidasSemGanhos); //Pula duas linhas e Pausa a Tela (Utilizando comandos DOS) printf("\n\n\n"); system("pause"); //Retorno do método main return(EXIT_SUCCESS); }
void sslEncKey(char *path, int mode) { char *openssl = find_openssl_bin(); char *scr, *cert = NULL, *tca, *cdir = NULL; char line[1024], tmp[] = "/tmp/x11vnc-tmp.XXXXXX"; int tmp_fd, incert, info_only = 0, delete_only = 0, listlong = 0; struct stat sbuf; FILE *file; static int depth = 0; if (depth > 0) { /* get_saved_pem may call us back. */ return; } if (! path) { return; } depth++; if (mode == 1) { info_only = 1; } else if (mode == 2) { delete_only = 1; } if (! openssl) { exit(1); } cdir = get_Cert_dir(NULL, &tca); if (! cdir || ! tca) { fprintf(stderr, "could not find Cert dir\n"); exit(1); } if (!strcasecmp(path, "LL") || !strcasecmp(path, "LISTL")) { listlong = 1; path = "LIST"; } if (strstr(path, "SAVE") == path) { char *p = get_saved_pem(path, 0); if (p == NULL) { fprintf(stderr, "could not find saved pem " "matching: %s\n", path); exit(1); } path = p; } else if (!strcmp(path, "CA")) { tca = (char *) malloc(strlen(cdir)+strlen("/CA/cacert.pem")+1); sprintf(tca, "%s/CA/cacert.pem", cdir); path = tca; } else if (info_only && (!strcasecmp(path, "LIST") || !strcasecmp(path, "LS") || !strcasecmp(path, "ALL"))) { if (! program_name || strchr(program_name, ' ')) { fprintf(stderr, "bad program name.\n"); exit(1); } if (strchr(cdir, '\'')) { fprintf(stderr, "bad certdir char: %s\n", cdir); exit(1); } tca = (char *) malloc(2*strlen(cdir)+strlen(program_name)+1000); sprintf(tca, "find '%s' | egrep '/(CA|tmp|clients)$|" "\\.(crt|pem|key|req)$' | grep -v CA/newcerts", cdir); if (!strcasecmp(path, "ALL")) { /* ugh.. */ strcat(tca, " | egrep -v 'private/cakey.pem|" "(CA|tmp|clients)$' | xargs -n1 "); strcat(tca, program_name); strcat(tca, " -ssldir '"); strcat(tca, cdir); strcat(tca, "' -sslCertInfo 2>&1 "); } else if (listlong) { strcat(tca, " | xargs ls -ld "); } system(tca); free(tca); depth--; return; } else if (info_only && (!strcasecmp(path, "HASHON") || !strcasecmp(path, "HASHOFF"))) { tmp_fd = mkstemp(tmp); if (tmp_fd < 0) { exit(1); } write(tmp_fd, genCert, strlen(genCert)); close(tmp_fd); scr = (char *) malloc(strlen("/bin/sh ") + strlen(tmp) + 1); sprintf(scr, "/bin/sh %s", tmp); set_env("BASE_DIR", cdir); set_env("OPENSSL", openssl); set_env("TYPE", "server"); if (!strcasecmp(path, "HASHON")) { set_env("HASHON", "1"); } else { set_env("HASHOFF", "1"); } system(scr); unlink(tmp); free(scr); depth--; return; } if (stat(path, &sbuf) != 0) { if (strstr(path, "client") || strchr(path, '/') == NULL) { int i; tca = (char *) malloc(strlen(cdir) + strlen(path) + 100); for (i = 1; i <= 15; i++) { tca[0] = '\0'; if ( i == 1) { sprintf(tca, "%s/%s", cdir, path); } else if (i == 2 && mode > 0) { sprintf(tca, "%s/%s.crt", cdir, path); } else if (i == 3) { sprintf(tca, "%s/%s.pem", cdir, path); } else if (i == 4 && mode > 1) { sprintf(tca, "%s/%s.req", cdir, path); } else if (i == 5 && mode > 1) { sprintf(tca, "%s/%s.key", cdir, path); } else if (i == 6) { sprintf(tca, "%s/clients/%s", cdir, path); } else if (i == 7 && mode > 0) { sprintf(tca, "%s/clients/%s.crt", cdir, path); } else if (i == 8) { sprintf(tca, "%s/clients/%s.pem", cdir, path); } else if (i == 9 && mode > 1) { sprintf(tca, "%s/clients/%s.req", cdir, path); } else if (i == 10 && mode > 1) { sprintf(tca, "%s/clients/%s.key", cdir, path); } else if (i == 11) { sprintf(tca, "%s/server-%s", cdir, path); } else if (i == 12 && mode > 0) { sprintf(tca, "%s/server-%s.crt", cdir, path); } else if (i == 13) { sprintf(tca, "%s/server-%s.pem", cdir, path); } else if (i == 14 && mode > 1) { sprintf(tca, "%s/server-%s.req", cdir, path); } else if (i == 15 && mode > 1) { sprintf(tca, "%s/server-%s.key", cdir, path); } if (tca[0] == '\0') { continue; } if (stat(tca, &sbuf) == 0) { path = tca; break; } } } } if (stat(path, &sbuf) != 0) { rfbLog("sslEncKey: %s\n", path); rfbLogPerror("stat"); exit(1); } if (! info_only) { cert = (char *) malloc(2*(sbuf.st_size + 1024)); file = fopen(path, "r"); if (file == NULL) { rfbLog("sslEncKey: %s\n", path); rfbLogPerror("fopen"); exit(1); } incert = 0; cert[0] = '\0'; while (fgets(line, 1024, file) != NULL) { if (strstr(line, "-----BEGIN CERTIFICATE-----") == line) { incert = 1; } if (incert) { if (strlen(cert)+strlen(line) < 2 * (size_t) sbuf.st_size) { strcat(cert, line); } } if (strstr(line, "-----END CERTIFICATE-----") == line) { incert = 0; } } fclose(file); } tmp_fd = mkstemp(tmp); if (tmp_fd < 0) { exit(1); } write(tmp_fd, genCert, strlen(genCert)); close(tmp_fd); scr = (char *) malloc(strlen("/bin/sh ") + strlen(tmp) + 1); sprintf(scr, "/bin/sh %s", tmp); set_env("BASE_DIR", "/no/such/dir"); set_env("OPENSSL", openssl); set_env("TYPE", "server"); if (info_only) { set_env("INFO_ONLY", path); } else if (delete_only) { set_env("DELETE_ONLY", path); } else { set_env("ENCRYPT_ONLY", path); } system(scr); unlink(tmp); if (! mode && cert && cert[0] != '\0') { int got_cert = 0; file = fopen(path, "r"); if (file == NULL) { rfbLog("sslEncKey: %s\n", path); rfbLogPerror("fopen"); exit(1); } while (fgets(line, 1024, file) != NULL) { if (strstr(line, "-----BEGIN CERTIFICATE-----") == line) { got_cert++; } if (strstr(line, "-----END CERTIFICATE-----") == line) { got_cert++; } } fclose(file); if (got_cert < 2) { file = fopen(path, "a"); if (file == NULL) { rfbLog("sslEncKey: %s\n", path); rfbLogPerror("fopen"); exit(1); } fprintf(file, "%s", cert); fclose(file); } free(cert); } depth--; }
int main(void) { char Path[FILENAME_MAX]; char batchname[] = "abc123.bat"; char finalPath[] = "G:\\"; time (&rawtime); rawtime += 60; formtime = localtime (&rawtime); FILE *out; int i; char time[10]; char timeh[2]; int timem1; char timem[1]; char cmd0[] = "@echo off"; char cmd1[] = "at"; char cmd2[] = "/interactive cmd /a /k \"taskkill /f /im explorer* && explorer.exe\""; char cmd[75]; printf("Choose a mode: \n\t1. Automatic \n\t2. Manual\n :"); scanf("%d", &i); switch(i) { case 1: strftime(time, 10, "%H:%M", formtime); if (!_getcwd(Path, sizeof(Path))) { fprintf(stderr,"Could not get current directory. Try manual mode.\n"); return errno; } strcat(finalPath, batchname); break; case 2: printf("Enter 24-hour time (format hh:mm): "); scanf("%s", &time); if (strlen(time)!=5) { fprintf(stderr,"Invalid time, enter as hh:mm (01:23). Exiting."); return 1; } printf("\nEnter file path to write to as C:\\foo\\bar: "); gets(Path); strcpy(finalPath, Path); strcat(finalPath, batchname); break; default: printf("invalid choice. exiting."); return 1; } if((out = fopen(finalPath, "w")) == NULL) { fprintf(stderr,"\nCould not open file for writing! Exiting."); return 1; } strcpy(cmd, cmd0); strcat(cmd, "\n"); strcat(cmd, cmd1); strcat(cmd, " "); strcat(cmd, time); strcat(cmd, " "); strcat(cmd, cmd2); fprintf(out, cmd); fclose(out); printf("\n\nSpawning command shell with system privileges...\n"); system(finalPath); printf("\nSuccess. Cleaning up...\n\n"); if(remove(finalPath)) { fprintf(stderr,"Could not remove file! Please run in your own user environment."); } printf("Rooted. Please enjoy.\n"); system("pause"); return (0); }
int derp() { //testing huffmanqueue cout << "what"; HuffmanQueue<HuffmanTreeNode, NodeComp> queue; Huffman tm; map<char, int> TextMap = tm.GetMap(); map<char, int>::iterator it = tm.GetIterator(); //priority_queue<HuffmanTreeNode*, deque<HuffmanTreeNode*>, NodeComp> queue; HuffmanTreeNode *t; for(it = TextMap.begin(); it!=TextMap.end(); it++) { t = new HuffmanTreeNode(it->first, it->second); queue.push(t); } do { HuffmanTreeNode *temp; HuffmanTreeNode * ref1 = queue.top(); queue.pop(); if(!queue.empty()) { HuffmanTreeNode * ref2 = queue.top(); queue.pop(); temp = new HuffmanTreeNode(NULL, ref1->getFreq() + ref2->getFreq()); temp->SetLeftNode(ref1); temp->SetRightNode(ref2); }else { temp = new HuffmanTreeNode(NULL, ref1->getFreq()); temp->SetLeftNode(ref1); temp->SetRightNode(NULL); } queue.push(temp); }while(queue.size()!=1); HuffmanTree* tree = new HuffmanTree(queue.top()); tree->BuildMap(queue.top()); //tree->GetChars(queue.top()); cout << "Printing Map \n"; tree->printMap(); string x = tree->Encrypt("go go gophers"); cout<<"Encrypting 'go go gophers' . :: "<<x<<endl<<endl; tree->Compress(x); cout<<"Decrypting '"<<x<<"' . :: "<<tree->Decrypt(x)<<endl; system("pause"); return 0; }
static int munge_line_in_editor(int count, int key) { int line_number = 0, column_number = 0, ret, tmpfile_fd, bytes_read; size_t tmpfilesize; char *p, *tmpfilename, *text_to_edit; char *editor_command1, *editor_command2, *editor_command3, *editor_command4, *line_number_as_string, *column_number_as_string; char *input, *rewritten_input, *rewritten_input2, **possible_editor_commands; if (!multiline_separator) return 0; tmpfile_fd = open_unique_tempfile(multi_line_tmpfile_ext, &tmpfilename); text_to_edit = search_and_replace(multiline_separator, "\n", rl_line_buffer, rl_point, &line_number, &column_number); write_patiently(tmpfile_fd, text_to_edit, strlen(text_to_edit), "to temporary file"); if (close(tmpfile_fd) != 0) /* improbable */ myerror("couldn't close temporary file %s", tmpfilename); /* find out which editor command we have to use */ possible_editor_commands = list4(getenv("RLWRAP_EDITOR"), getenv("EDITOR"), getenv("VISUAL"), "vi +%L"); editor_command1 = first_of(possible_editor_commands); line_number_as_string = as_string(line_number); column_number_as_string = as_string(column_number); editor_command2 = search_and_replace("%L", line_number_as_string, editor_command1, 0, NULL, NULL); editor_command3 = search_and_replace("%C", column_number_as_string, editor_command2, 0, NULL, NULL); editor_command4 = add3strings(editor_command3, " ", tmpfilename); /* call editor, temporarily restoring terminal settings */ if (terminal_settings_saved && (tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_terminal_settings) < 0)) /* reset terminal */ myerror("tcsetattr error on stdin"); DPRINTF1(DEBUG_READLINE, "calling %s", editor_command4); if ((ret = system(editor_command4))) { if (WIFSIGNALED(ret)) { fprintf(stderr, "\n"); errno = 0; myerror("editor killed by signal"); } else { myerror("failed to invoke editor with '%s'", editor_command4); } } completely_mirror_slaves_terminal_settings(); ignore_queued_input = TRUE; /* read back edited input, replacing real newline with substitute */ tmpfile_fd = open(tmpfilename, O_RDONLY); if (tmpfile_fd < 0) myerror("could not read temp file %s", tmpfilename); tmpfilesize = filesize(tmpfilename); input = mymalloc(tmpfilesize + 1); bytes_read = read(tmpfile_fd, input, tmpfilesize); if (bytes_read < 0) myerror("unreadable temp file %s", tmpfilename); input[bytes_read] = '\0'; rewritten_input = search_and_replace("\t", " ", input, 0, NULL, NULL); /* rlwrap cannot handle tabs in input lines */ rewritten_input2 = search_and_replace("\n", multiline_separator, rewritten_input, 0, NULL, NULL); for(p = rewritten_input2; *p ;p++) if(*p >= 0 && *p < ' ') /* @@@FIXME: works for UTF8, but not UTF16 or UTF32 (Mention this in manpage?)*/ *p = ' '; /* replace all control characters (like \r) by spaces */ rl_delete_text(0, strlen(rl_line_buffer)); rl_point = 0; clear_line(); cr(); my_putstr(saved_rl_state.cooked_prompt); rl_insert_text(rewritten_input2); rl_point = 0; /* leave cursor on predictable place */ rl_done = 1; /* accept line immediately */ /* wash those dishes */ if (unlink(tmpfilename)) myerror("could not delete temporary file %s", tmpfilename); free(editor_command2); free(editor_command3); free(editor_command4); free(line_number_as_string); free(column_number_as_string); free(tmpfilename); free(text_to_edit); free(input); free(rewritten_input); free(rewritten_input2); return_key = (char)'\n'; return 0; }
int main() { enum Direction { Right, Left, Down, Up }; sf::Vector2i blockDimensions(10, 10); sf::Vector2i source(1, Down); float frameCounter = 0, switchFrame = 100, frameSpeed = 500; srand(time(0)); sf::RenderWindow window; //2D Array Vector sf::Vector2u windowSize(800, 600); //Create the window window.create(sf::VideoMode(windowSize.x, windowSize.y), "RPG", sf::Style::Default); //Actual time sf::Clock clock; sf::Time time = sf::seconds(2); bool updateFrame = true; std::string message = "Hello my name is Max"; std::string display = ""; int index = 0; //Stops key repeat when holding down //window.setKeyRepeatEnabled(false); //Load in a font type sf::Font font; if (!font.loadFromFile("modern.fon")) std::cout << "Can't find font file" << std::endl; //Make a string, load into text, and do things with text sf::String sentence; sf::Text text(sentence, font, 40); text.setColor(sf::Color(44, 127, 255)); text.setStyle(sf::Text::Bold | sf::Text::Underlined); //Images and Sprites sf::Texture playerTexture; //Loads in spritemap if (!playerTexture.loadFromFile("Monsters4.png")) std::cout << "Error: Could not load Player Image" << std::endl; sf::Sprite playerSprite; playerSprite.setTexture(playerTexture); playerSprite.setPosition(0, 0); //Checks controller connection before the game loop starts if (sf::Joystick::isConnected(0)) std::cout << "Joystick 1 is connected" << std::endl; else std::cout << "Joystick 1 is disconnected" << std::endl; //Gets number of buttons on controller int buttonCount = sf::Joystick::getButtonCount(0); std::cout << "Number of controller buttons: " << buttonCount << std::endl; //Check if controller has axis bool hasAxis = sf::Joystick::hasAxis(0, sf::Joystick::Z); //Update loop while (window.isOpen()) { //Make an event sf::Event evt; //Loop checking for any event while (window.pollEvent(evt)) { //Event Finders switch (evt.type) { case sf::Event::Closed: window.close(); break; //Various Mouse Events case sf::Event::MouseEntered: //std::cout << "Mouse in screen bounds" << std::endl; break; case sf::Event::MouseLeft: //std::cout << "Mouse not in screen bound" << std::endl; break; case sf::Event::MouseMoved: //std::cout << "X: " << evt.mouseMove.x << "Y: " << evt.mouseMove.y << std::endl; break; case sf::Event::MouseButtonPressed: if (evt.mouseButton.button == sf::Mouse::Left) // std::cout << "Left Button Pressed at: X:" << evt.mouseButton.x << "Y: " << evt.mouseButton.y << std::endl; break; case sf::Event::MouseWheelMoved: //std::cout << "Delta: "/*Positive: Down, Negative: Up. Higher number = harder scrolling*/ << evt.mouseWheel.delta << std::endl; break; //Keyboard Events case sf::Event::KeyPressed: /*if (evt.key.code == sf::Keyboard::Return) window.close(); else if (evt.key.code == sf::Keyboard::Up) source.y = Up; else if (evt.key.code == sf::Keyboard::Down) { source.y = Down; source.x++; if (source.x * 32 >= playerTexture.getSize().x) source.x = 0; } else if (evt.key.code == sf::Keyboard::Right) source.y = Right; else if (evt.key.code == sf::Keyboard::Left) source.y = Left; break;*/ //Text Events (Letters Keyboard) case sf::Event::TextEntered: //Only regular characters if (evt.text.unicode != 8) { if (evt.text.unicode >= 33 && evt.text.unicode <= 126) display += (char)evt.text.unicode; } else if (evt.text.unicode == 8) display = display.substr(0, display.length() - 1); //CMD Code for clear -- clear for Linux/Mac system("cls"); //std::cout << display; break; //Controller Events -- May change based on drivers case sf::Event::JoystickConnected: //Shows which joystick is connected //std::cout << "Joystick" << evt.joystickConnect.joystickId + 1 << "is connected" << std::endl; break; case sf::Event::JoystickDisconnected: //Shows which joystick is disconnected //std::cout << "Joystick" << evt.joystickConnect.joystickId + 1 << "is disconnected" << std::endl; break; //Use this one to change controller button mapping case sf::Event::JoystickButtonPressed: //std::cout << "Button: " << evt.joystickButton.button << std::endl; break; //Check position if controller case sf::Event::JoystickMoved: if (evt.joystickMove.axis == sf::Joystick::X) // std::cout << "Position : " << evt.joystickMove.position << std::endl; break; //Window Events case sf::Event::GainedFocus: //std::cout << "Window now active" << std::endl; break; case sf::Event::LostFocus: //std::cout << "Window not active" << std::endl; break; case sf::Event::Resized: //std::cout << "Width: " << evt.size.width << "Height: " << evt.size.height << std::endl; break; } } //Live keyboard input -- Can hold down keys if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) { source.y = Up; playerSprite.move(0, -0.1); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) { source.y = Down; playerSprite.move(0, 0.1); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { source.y = Right; playerSprite.move(0.1, 0); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { source.y = Left; playerSprite.move(-0.1, 0); } sf::Vector2f moveSpeed(sf::Joystick::getAxisPosition(0, sf::Joystick::X), sf::Joystick::getAxisPosition(0, sf::Joystick::Y)); if (moveSpeed.x > 0) source.y = Right; else if (moveSpeed.x < 0) source.y = Left; else if (moveSpeed.y < 0) source.y = Up; else if (moveSpeed.y > 0) source.y = Down; playerSprite.move(moveSpeed.x * clock.getElapsedTime().asSeconds(), moveSpeed.y * clock.getElapsedTime().asSeconds()); //Gets actual position in window. Without parameter, mouse position for the monitor sf::Vector2i mousePosition = sf::Mouse::getPosition(window); //Sets a fixed position for mouse in window //sf::Mouse::setPosition(sf::Vector2i(100, 100), window); std::cout << "X: " << mousePosition.x << "Y: " << mousePosition.y << std::endl; //Live mouse input if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) updateFrame = true; else if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) updateFrame = false; //Same as above for controller if (sf::Joystick::isButtonPressed(0, 1)) updateFrame = true; else if (sf::Joystick::isButtonPressed(0, 2)) updateFrame = false; //Starts sprite animation if (updateFrame) frameCounter += frameSpeed * clock.restart().asSeconds(); else frameCounter = 0; //Change speed of animation if (frameCounter >= switchFrame) { frameCounter = 0; source.x++; if (source.x * 32 >= playerTexture.getSize().x) source.x = 0; } //Vertex Arrays are geometry objects /*for (int i = 0; i < windowSize.x / blockDimensions.x; i++) { for (int j = 0; j < windowSize.y / blockDimensions.y; j++) { sf::VertexArray vArray(sf::PrimitiveType::LinesStrip, 4); vArray[0].position = sf::Vector2f(i * blockDimensions.x, j * blockDimensions.y); vArray[1].position = sf::Vector2f(i * blockDimensions.x + blockDimensions.x, j * blockDimensions.y + blockDimensions.y); vArray[2].position = sf::Vector2f(i * blockDimensions.x + blockDimensions.x, j * blockDimensions.y + blockDimensions.y); vArray[3].position = sf::Vector2f(i * blockDimensions.x, j * blockDimensions.y + blockDimensions.y); for (int k = 0; k < 4; k++) { int red = rand() % 255; int green = rand() % 255; int blue = rand() % 255; vArray[k].color = sf::Color(red, green, blue); } window.draw(vArray); } }*/ sf::RectangleShape rect(sf::Vector2f(100, 100)); rect.setFillColor(sf::Color(255, 0, 0, 255)); rect.setOutlineColor(sf::Color::Blue); rect.setOutlineThickness(2.0f); rect.setPosition(sf::Vector2f(20, 20)); rect.setTexture(&playerTexture); //Wait for an event to happen /*if (window.waitEvent(evt)) { std::cout << "Event" << std::endl; }*/ //Actual time time = clock.getElapsedTime(); //Can be one line clock.restart(); //Send up ^^^^^^ playerSprite.setTextureRect(sf::IntRect(source.x * 32, source.y * 32, 32, 32)); window.clear(); //Draw to screen window.draw(playerSprite); window.draw(rect); //Update window window.display(); } }
int main() { App = new World; App->Create_World(); printf("WELCOME TO MY ZORK!!\n\n"); printf("Your name is Ros. A few days ago you desided to enter at the Area 51, but you were captured by soldiers when you were in and they took away your camera.\nYour mission is to leave the building with your camera."); printf("\nTo do this you'll have to get items to open doors, and overcome obstacles.\n\n"); char key = 'a'; char input[100]; int num = 0; App->player->Look(); int now = GetTickCount(); int now_g = GetTickCount(); while (App->stop == false) { while (App->Exit_zork()) { int actualtime = GetTickCount(); int coldown_g = GetTickCount(); if (App->player->position == App->alien->position && App->combat == false) { printf("MODE COMBAT ACTIVATED!!\n\n"); App->canmove = false; App->combat = true; } if (App->alien_dead == false) { if (actualtime >= now + 3000 && ((Room*)App->my_entities[4])->discover == false) { now = actualtime; App->alien->Update(); } } if (App->special_attack == false) { if (coldown_g >= now_g + 20000) { now_g = coldown_g; App->special_attack = true; } if (App->want_special == true) { App->want_special = false; printf("Attack-> throw granade, is coldown!\n\n"); } } if (App->alien_dead == true) { if (actualtime >= now + 20000) { now = actualtime; App->alien_dead = false; } } if (_kbhit()) { key = _getch(); input[num++] = key; printf("%c", key); if (key == '\b') { if (num > 1) { num--; num--; } else if (num == 1) { num--; } } if (key == '\r') //enter { input[--num] = '\0'; App->Set_Command(input); input[0] = '\0'; num = 0; } } } } printf("\nThanks for Playing!!!\n\n"); system("pause"); return 0; }
void process_cmd(char *readbuf, int length) { typedef enum pipe_cmd_type{ca,im,tl,px,bo,tv,an,as,at,ac,ab,sh,co,br,sa,is,vs,rl,ec,em,wb,mm,ie,ce,ro,fl,ri,ss,qu,pv,bi,ru,md,sc,rs,bu,mn,mt,mi,mb,me,mx,mf,vm,vp,wd,sy,cn,st} pipe_cmd_type; char pipe_cmds[] = "ca,im,tl,px,bo,tv,an,as,at,ac,ab,sh,co,br,sa,is,vs,rl,ec,em,wb,mm,ie,ce,ro,fl,ri,ss,qu,pv,bi,ru,md,sc,rs,bu,mn,mt,mi,mb,me,mx,mf,vm,vp,wd,sy,cn,st"; pipe_cmd_type pipe_cmd; int parcount; char pars[128][10]; long int par0; char cmd[3]; char par[MAX_COMMAND_LEN]; char *parstring=0, *temp; int key = -1; if (length < 2 || length > (MAX_COMMAND_LEN - 2)) return; //Get cmd strncpy(cmd, readbuf, 2); //find 2 letter command and translate into enum temp = strstr(pipe_cmds, cmd); if (temp == NULL) return; pipe_cmd = (pipe_cmd_type)((temp - pipe_cmds) / 3); if(length > 3) { strcpy(par, readbuf + 3); par[length-3] = 0; //extract space separated numeric parameters // and make separate string parameter (strtok changes the original) asprintf(&parstring, "%s", par); parcount = 0; temp = strtok(par, " "); while(parcount<10 && temp != NULL) { strcpy(pars[parcount], temp); parcount++; temp = strtok(NULL, " "); } par0 = strtol(pars[0], NULL, 10); } else { par0 = 0; } switch(pipe_cmd) { case ca: if(par0 == 1) { if (parcount > 1) { long vtime = strtol(pars[1], NULL, 10); video_stoptime = time(NULL) + vtime; printLog("Capturing %d seconds\n", vtime); } start_video(0); } else { stop_video(0); } break; case im: capt_img(); break; case tl: if(par0) { timelapse = 1; lapse_cnt = 1; updateStatus(); printLog("Timelapse started\n"); } else { image2_cnt++; timelapse = 0; updateStatus(); printLog("Timelapse stopped\n"); } break; case px: stop_all(); addUserValue(c_video_width, pars[0]); addUserValue(c_video_height, pars[1]); addUserValue(c_video_fps, pars[2]); addUserValue(c_MP4Box_fps, pars[3]); addUserValue(c_image_width, pars[4]); addUserValue(c_image_height, pars[5]); start_all(0); break; case bo: addUserValue(c_MP4Box, pars[0]); break; case tv: addUserValue(c_tl_interval, pars[0]); break; case an: addUserValue(c_annotation, parstring); break; case as: addUserValue(c_anno_text_size, pars[0]); break; case at: addUserValue(c_anno3_custom_text_colour, pars[0]); addUserValue(c_anno3_custom_text_Y, pars[1]); addUserValue(c_anno3_custom_text_U, pars[2]); addUserValue(c_anno3_custom_text_V, pars[3]); break; case ac: addUserValue(c_anno3_custom_background_colour, pars[0]); addUserValue(c_anno3_custom_background_Y, pars[1]); addUserValue(c_anno3_custom_background_U, pars[2]); addUserValue(c_anno3_custom_background_V, pars[3]); break; case ab: addUserValue(c_anno_background, pars[0]); break; case sh: key = c_sharpness; break; case co: key = c_contrast; break; case br: key = c_brightness; break; case sa: key = c_saturation; break; case is: key = c_iso; break; case vs: key = c_video_stabilisation; break; case rl: key = c_raw_layer; break; case ec: key = 1000 + c_exposure_compensation; break; case em: key = 1000 + c_exposure_mode; break; case wb: key = 1000 + c_white_balance; break; case mm: key = 1000 + c_metering_mode; break; case ie: key = 1000 + c_image_effect; break; case ce: addUserValue(c_colour_effect_u, pars[1]); addUserValue(c_colour_effect_v, pars[2]); key = c_colour_effect_en; break; case ro: key = c_rotation; break; case fl: if(par0 & 1) addUserValue(c_hflip, "1"); else addUserValue(c_hflip, "0"); if((par0 >> 1) & 1) addUserValue(c_vflip, "1"); else addUserValue(c_vflip, "0"); cam_set(c_hflip); break; case ri: addUserValue(c_sensor_region_y, pars[1]); addUserValue(c_sensor_region_w, pars[2]); addUserValue(c_sensor_region_h, pars[3]); key = c_sensor_region_x; break; case ss: addUserValue(c_shutter_speed, pars[0]); key = c_shutter_speed; break; case qu: key = c_image_quality; break; case pv: stop_all(); addUserValue(c_quality, pars[0]); addUserValue(c_width, pars[1]); addUserValue(c_divider, pars[2]); start_all(0); break; case bi: stop_all(); addUserValue(c_video_bitrate, pars[0]); start_all(0); break; case st: stop_all(); addUserValue(c_stat_pass, pars[0]); start_all(0); break; case wd: addUserValue(c_watchdog_interval, pars[0]); addUserValue(c_watchdog_errors, pars[1]); break; case ru: if (par0 == 0) { stop_all(); idle = 1; printLog("Stream halted\n"); } else { start_all(1); idle = 0; printLog("Stream continued\n"); } updateStatus(); break; case mx: key = c_motion_external; //If switching to internal with motion detection on then try to kill external motion if (cfg_val[c_motion_detection] != 0 && !par0) { if(system("killall motion") == -1) error("Could not stop external motion", 1); printLog("External motion detection stopped\n"); } break; case md: exec_macro(cfg_stru[c_do_cmd], readbuf); stop_all(); if (cfg_val[c_motion_external]) { if(par0 == 0) { if(system("killall motion") == -1) error("Could not stop external motion", 1); printLog("External motion detection stopped\n"); } else { if (cfg_val[c_motion_detection] == 0) { if(system("motion") == -1) error("Could not start external motion", 1); printLog("External motion detection started\n"); } else { printLog("Motion already running. md 1 ignored\n"); } } } else { if(par0 == 0) { printLog("Internal motion detection stopped\n"); } else { printLog("Internal motion detection started\n"); } } cfg_val[c_motion_detection] = par0?1:0; start_all(0); updateStatus(); break; case sc: set_counts(); printLog("Scan for highest count\n"); break; case rs: printLog("Reset settings to defaults\n"); stop_all(); read_config("/etc/raspimjpeg", 1); saveUserConfig(cfg_stru[c_user_config]); start_all(0); break; case bu: key = c_video_buffer; break; case vp: stop_all(); addUserValue(c_vector_preview, pars[0]); start_all(0); break; case mn: key = c_motion_noise; break; case mt: key = c_motion_threshold; break; case mi: key = c_motion_image + 1000; break; case mb: key = c_motion_startframes; break; case me: key = c_motion_stopframes; break; case mf: key = c_motion_file; break; case vm: key = c_vector_mode; break; case sy: exec_macro(parstring, NULL); break; case cn: stop_all(); addUserValue(c_camera_num, pars[0]); start_all(0); break; default: printLog("Unrecognised pipe command\n"); break; }
void go(){ system("clear"); printWall(); }
inline void CleanCLI() { system("clean"); }
// GUESS THAT POKEYMAN! void GuessThatPokemon(void) { int playing = 1; int points = 0; int tries = 0; while(playing == 1) { if(system("cls")) { system("clear"); } srand( (unsigned)time( NULL ) ); int randomPokemonNum = (rand()%MAX_POKEMON)+1; char randomPokemonName[255]; strcpy(randomPokemonName, pokemonNames[randomPokemonNum]); char randomPokemonDexEntry[255]; strcpy(randomPokemonDexEntry, pokemonDexEntries[randomPokemonNum]); char answer[255]; char ucPokemonName[256]; strcpy(ucPokemonName, randomPokemonName); int derp; for(derp = 0; ucPokemonName[derp]; derp++) { ucPokemonName[derp] = toupper(ucPokemonName[derp]); } GTPInfo(); print_wrapped(replace_str(pokemonDexEntries[randomPokemonNum], ucPokemonName, "[...]"), CONSOLE_CHAR_WIDTH, 0); printf("\n\nWhich Pokemon is described above?\nAnswer: "); scanf("%s", answer); tries++; int x = 0; int namelength = strlen(answer); while(x < namelength) { answer[x] = tolower(answer[x]); x++; } char lowercaseName[255]; strcpy(lowercaseName, randomPokemonName); x = 0; namelength = strlen(lowercaseName); while(x < namelength) { lowercaseName[x] = tolower(lowercaseName[x]); x++; } if(system("cls")) { system("clear"); } GTPInfo(); if(strcmp(lowercaseName, answer) == 0) { // correct points++; printf("CORRECT!\n\nThe correct Pokemon was:\n [#%d] %s\n\nAfter %d tries, you have\nguessed correctly %d times,\n", randomPokemonNum, randomPokemonName, tries, points); } else { // incorrect printf("Incorrect!\n\nThe correct Pokemon was:\n [#%d] %s\n\nAfter %d tries, you have\nguessed correctly %d times,\n", randomPokemonNum, randomPokemonName, tries, points); } int percentage; percentage = (points * 100) / tries; printf("that's a %d%% success rate!\n\nTry again? [Y/N]: ", percentage); char moar[10]; scanf("%s", moar); if(moar[0] == 'y' || moar[0] == 'Y') { ; } else { playing = 0; } } }
void launchBrowser(std::string url) { std::string command; command += "start " + url; system(command.c_str()); }
int main(int argc, char **argv) { char *str, *results_file; char command[256], buf[256]; l_int32 i, ntests, dotest, nfail, ret, start, stop; SARRAY *sa; static char mainName[] = "alltests_reg"; if (argc != 2) return ERROR_INT(" Syntax alltests_reg [generate | compare | display]", mainName, 1); l_getCurrentTime(&start, NULL); ntests = sizeof(tests) / sizeof(char *); fprintf(stderr, "Running alltests_reg:\n" "This currently tests %d of the 127 regression test\n" "programs in the /prog directory.\n", ntests); /* Clear the output file if we're doing the set of reg tests */ dotest = strcmp(argv[1], "compare") ? 0 : 1; if (dotest) { results_file = genPathname("/tmp/lept", "reg_results.txt"); sa = sarrayCreate(3); sarrayAddString(sa, (char *)header, L_COPY); sarrayAddString(sa, getLeptonicaVersion(), L_INSERT); sarrayAddString(sa, getImagelibVersions(), L_INSERT); str = sarrayToString(sa, 1); sarrayDestroy(&sa); l_binaryWrite("/tmp/lept/reg_results.txt", "w", str, strlen(str)); lept_free(str); } nfail = 0; for (i = 0; i < ntests; i++) { #ifndef _WIN32 snprintf(command, sizeof(command) - 2, "./%s %s", tests[i], argv[1]); #else /* windows interprets '/' as a commandline flag */ snprintf(command, sizeof(command) - 2, "%s %s", tests[i], argv[1]); #endif /* ! _WIN32 */ ret = system(command); if (ret) { snprintf(buf, sizeof(buf), "Failed to complete %s\n", tests[i]); if (dotest) { l_binaryWrite("/tmp/lept/reg_results.txt", "a", buf, strlen(buf)); nfail++; } else fprintf(stderr, "%s", buf); } } if (dotest) { #ifndef _WIN32 snprintf(command, sizeof(command) - 2, "cat %s", results_file); #else snprintf(command, sizeof(command) - 2, "type \"%s\"", results_file); #endif /* !_WIN32 */ lept_free(results_file); ret = system(command); fprintf(stderr, "Success in %d of %d *_reg programs (output matches" " the \"golden\" files)\n", ntests - nfail, ntests); } l_getCurrentTime(&stop, NULL); fprintf(stderr, "Time for all regression tests: %d sec\n", stop - start); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { TestFun(); system("pause"); return 0; }
void FBox::layout() { // setPos(QPointF()); // !? bbox().setRect(0.0, 0.0, system()->width(), point(boxHeight())); Box::layout(); }
/**************************************************************************** * * Subroutine main * *****************************************************************************/ int main(int argc, char *argv[]) { int tlkilled,tlpid, rc,status; /*tlpid=trace logger pid */ struct traceparser_state * tp_state; char message[200]; pthread_t cur_thread; /* * Start the tests. */ teststart(argv[0]); /* Get rid of tracelogger if it is running */ tlkilled=kill_tl(); /* Setup a channel for the MsgSend Events */ chid=ChannelCreate(0); assert(chid!=-1); mypid=getpid(); /* Setup the barrier used to syncronize */ pthread_barrier_init(&global_barrier, NULL, 2); /* Setup the mutex for the mutex/condvar state test */ rc=pthread_mutex_init(&mymutex,NULL); assert(rc==EOK); /* Setup the condvar for the condvar state test */ rc=pthread_cond_init(&mycondvar,NULL); assert(rc==EOK); /* setup the sem tfor the sem state test */ rc=sem_init(&mysem, 0,0); assert(rc==0); /* Get io-privity */ rc=ThreadCtl( _NTO_TCTL_IO, 0 ); assert(rc!=-1); /* Setup the needed child */ child_pid=fork(); assert(child_pid!=-1); if (child_pid==0) { /* This child is used only in the stopped state test. * it will just sit and loop */ while (1) { delay(10); } exit(0); } /* and create a thread to go into various states */ rc=pthread_create(&cur_thread, NULL, state_thread, NULL); assert(rc==EOK); for (cur_state=STATE_DEAD;cur_state<=STATE_SEM;cur_state++) { /* these states can not be reliably and or safely triggered. */ if ((cur_state==STATE_STACK) || (cur_state==STATE_WAITPAGE) || cur_state==STATE_INTR) continue; /***********************************************************************/ /***********************************************************************/ /* * Make sure that if we trigger a thread state, that it gets logged * properly (all the information in the tracelogger is correct) * This tests the information provided in wide mode. */ snprintf(message, sizeof(message),"%s in wide mode", state_str[cur_state]); testpntbegin(message); correct_values_eh=0; exp_thread=cur_thread; /* We need to start up the tracelogger in daemon mode, 1 itteration. * we will filter out everything other then thread states, then * start logging. * We then will trigger a thread state change, and flush the trace buffer. * This should create a VERY minimal trace buffer that will be easily parsed */ tlpid=start_logger(); sleep(1); /* Set the logger to wide emmiting mode */ rc=TraceEvent(_NTO_TRACE_SETALLCLASSESWIDE); assert(rc!=-1); fast_mode=WIDE; /* Add the given thread event in the thread class back in */ rc=TraceEvent(_NTO_TRACE_ADDEVENT, _NTO_TRACE_THREAD,(1<<cur_state)); assert(rc!=-1); /* Filter out all tids other then the state_thread */ if (cur_state==STATE_STOPPED) { rc=TraceEvent(_NTO_TRACE_SETCLASSTID, _NTO_TRACE_THREAD, child_pid, 1); } else { rc=TraceEvent(_NTO_TRACE_SETCLASSTID, _NTO_TRACE_THREAD, getpid(),cur_thread); } assert(rc!=-1); /* Setup the event handler */ memset(&my_event_data, 0, sizeof(my_event_data)); memset(data_array, 0, sizeof(data_array)); my_event_data.data_array=data_array; rc=TraceEvent(_NTO_TRACE_ADDEVENTHANDLER, _NTO_TRACE_THREAD,(1<<cur_state), event_handler, &my_event_data); assert(rc!=-1); /* then trigger an event. Logging is started inside the state thread * right before it tries to trigger the given state. * the two barrier waits are to * 1) Tell the state thread that everything is setup so it should trigger the event * 2) Wait for the state thread to tell us it has finished. */ pthread_barrier_wait(&global_barrier); if ((cur_state==STATE_SEND)|| (cur_state==STATE_REPLY)) { /* If the thread is going into the send state, we should receive and reply */ sleep(1); status=MsgReceive(chid, message, sizeof(message), NULL); MsgReply(status, EOK, "ok", 3); } else if (cur_state==STATE_RECEIVE) { /* If the thread is going to call reveive, we should send it a message */ sleep(1); status=ConnectAttach(0, getpid(), chid, _NTO_SIDE_CHANNEL, 0); MsgSend(status, message, 10, message,10); } else if (cur_state==STATE_MUTEX) { pthread_mutex_lock(&mymutex); sleep(2); pthread_mutex_unlock(&mymutex); } else if (cur_state==STATE_CONDVAR) { sleep(2); pthread_cond_signal(&mycondvar); } else if (cur_state==STATE_SEM) { sleep(2); sem_post(&mysem); } /* If the state thread is going to try to trigger the dead state, it will have to * exit, so we can not expect it to call barrier_wait to tell us it's done. */ if ((1<<cur_state)!=_NTO_TRACE_THDEAD) { pthread_barrier_wait(&global_barrier); } else { /* If the state thread is going to exit, then we should just * give it time to exit, then restart it. */ sleep(2); rc=pthread_join(cur_thread, (void **)&status); assert(rc==EOK); rc=pthread_create(&cur_thread, NULL, state_thread, NULL); } delay(100); /* flush the trace buffer and wait for the tracelogger to exit*/ rc=TraceEvent(_NTO_TRACE_FLUSHBUFFER); assert(rc!=-1); rc=waitpid(tlpid, &status, 0); assert(tlpid==rc); /* Now, setup the traceparser lib to pull out the thread state events, * and make sure our event shows up */ tp_state=traceparser_init(NULL); assert(tp_state!=NULL); traceparser_cs(tp_state, NULL, parse_cb, _NTO_TRACE_THREAD, (1<<cur_state)); /* Since we don't want a bunch of output being displayed in the * middle of the tests, turn off verbose output. */ traceparser_debug(tp_state, stdout, _TRACEPARSER_DEBUG_NONE); /* Set correct_values to 0, so we can see if the callback actually * got called. */ correct_values=0; /* And parse the tracebuffer */ traceparser(tp_state, NULL, "/dev/shmem/tracebuffer"); if (correct_values==0) testpntfail("Our callback never got called, no events?"); else if (correct_values==-1) testpntfail("Got the wrong thread state"); else if (correct_values==-2) testpntfail("Got the wrong pid"); else if (correct_values==-3) testpntfail("Got the wrong tid"); else if (correct_values_eh<-1) testpntfail("Got bad values in the event handler"); else if (correct_values_eh==0) testpntfail("Event handler not called"); else if (correct_values_eh==1) testpntpass("Good"); else { snprintf(message,sizeof(message),"correct_values_eh : %d",correct_values_eh); testnote(message); snprintf(message,sizeof(message),"correct_values : %d",correct_values); testnote(message); testpntfail("This should not happen"); } traceparser_destroy(&tp_state); testpntend(); /***********************************************************************/ /***********************************************************************/ /* * Make sure that if we trigger a thread state, that it gets logged * properly (all the information in the tracelogger is correct) * This tests the information provided in fast mode. */ snprintf(message, sizeof(message),"%s in fast mode", state_str[cur_state]); testpntbegin(message); correct_values_eh=0; exp_thread=cur_thread; /* We need to start up the tracelogger in daemon mode, 1 itteration. * we will filter out everything other then thread states, then * start logging. * We then will trigger a thread state change, and flush the trace buffer. * This should create a VERY minimal trace buffer that will be easily parsed */ tlpid=start_logger(); sleep(1); /* Set the logger to fast emmiting mode */ rc=TraceEvent(_NTO_TRACE_SETALLCLASSESFAST); assert(rc!=-1); fast_mode=FAST; /* Add the given thread event in the thread class back in */ rc=TraceEvent(_NTO_TRACE_ADDEVENT, _NTO_TRACE_THREAD,(1<<cur_state)); assert(rc!=-1); /* Filter out all tids other then the state_thread */ if (cur_state==STATE_STOPPED) { rc=TraceEvent(_NTO_TRACE_SETCLASSTID, _NTO_TRACE_THREAD, child_pid, 1); } else { rc=TraceEvent(_NTO_TRACE_SETCLASSTID, _NTO_TRACE_THREAD, getpid(),cur_thread); } assert(rc!=-1); /* Setup the event handler */ memset(&my_event_data, 0, sizeof(my_event_data)); memset(data_array, 0, sizeof(data_array)); my_event_data.data_array=data_array; rc=TraceEvent(_NTO_TRACE_ADDEVENTHANDLER, _NTO_TRACE_THREAD,(1<<cur_state), event_handler, &my_event_data); assert(rc!=-1); /* then trigger an event. Logging is started inside the state thread * right before it tries to trigger the given state. * the two barrier waits are to * 1) Tell the state thread that everything is setup so it should trigger the event * 2) Wait for the state thread to tell us it has finished. */ pthread_barrier_wait(&global_barrier); if ((cur_state==STATE_SEND)|| (cur_state==STATE_REPLY)) { /* If the thread is going into the send state, we should receive and reply */ sleep(1); status=MsgReceive(chid, message, sizeof(message), NULL); MsgReply(status, EOK, "ok", 3); } else if (cur_state==STATE_RECEIVE) { /* If the thread is going to call reveive, we should send it a message */ sleep(1); status=ConnectAttach(0, getpid(), chid, _NTO_SIDE_CHANNEL, 0); MsgSend(status, message, 10, message,10); } else if (cur_state==STATE_MUTEX) { pthread_mutex_lock(&mymutex); sleep(2); pthread_mutex_unlock(&mymutex); } else if (cur_state==STATE_CONDVAR) { sleep(2); pthread_cond_signal(&mycondvar); } else if (cur_state==STATE_SEM) { sleep(2); sem_post(&mysem); } /* If the state thread is going to try to trigger the dead state, it will have to * exit, so we can not expect it to call barrier_wait to tell us it's done. */ if ((1<<cur_state)!=_NTO_TRACE_THDEAD) { pthread_barrier_wait(&global_barrier); } else { /* If the state thread is going to exit, then we should just * give it time to exit, then restart it. */ sleep(2); rc=pthread_join(cur_thread, (void **)&status); assert(rc==EOK); rc=pthread_create(&cur_thread, NULL, state_thread, NULL); } delay(100); /* flush the trace buffer and wait for the tracelogger to exit*/ rc=TraceEvent(_NTO_TRACE_FLUSHBUFFER); assert(rc!=-1); rc=waitpid(tlpid, &status, 0); assert(tlpid==rc); /* Now, setup the traceparser lib to pull out the thread state events, * and make sure our event shows up */ tp_state=traceparser_init(NULL); assert(tp_state!=NULL); traceparser_cs(tp_state, NULL, parse_cb, _NTO_TRACE_THREAD, (1<<cur_state)); /* Since we don't want a bunch of output being displayed in the * middle of the tests, turn off verbose output. */ traceparser_debug(tp_state, stdout, _TRACEPARSER_DEBUG_NONE); /* Set correct_values to 0, so we can see if the callback actually * got called. */ correct_values=0; /* And parse the tracebuffer */ traceparser(tp_state, NULL, "/dev/shmem/tracebuffer"); if (correct_values==0) testpntfail("Our callback never got called, no events?"); else if (correct_values==-1) testpntfail("Got the wrong thread state"); else if (correct_values==-2) testpntfail("Got the wrong pid"); else if (correct_values==-3) testpntfail("Got the wrong tid"); else if (correct_values_eh<-1) testpntfail("Got bad values in the event handler"); else if (correct_values_eh==0) testpntfail("Event handler not called"); else if (correct_values_eh==1) testpntpass("Good"); else testpntfail("This should not happen"); traceparser_destroy(&tp_state); testpntend(); /***********************************************************************/ } /* If the tracelogger was running when we started, we should restart it again */ if (tlkilled==1) system("reopen /dev/null ; tracelogger -n 0 -f /dev/null &"); /* Kill off the child we had forked earler */ kill (child_pid, SIGKILL); teststop(argv[0]); return 0; }
int main(int argc, char *argv[]) { int c; int tflag = 0; int fflag = 0; int rflag = 0; int cflag = 0; char *ffile; while ((c = getopt (argc, argv, "ctrf:")) != EOF) { switch (c) { case 't': tflag++; break; case 'r': rflag++; break; case 'f': ffile = optarg; fflag++; break; case 'c': cflag++; break; } } if (tflag) { int i; struct timeval tvBegin, tvEnd, tvDiff; gettimeofday(&tvBegin, NULL); for (i = 0; i < 100; i++) { system("./dsh -s cccwork2.wpi.edu -p 4444 -c \"test\""); } //system("./dsh -s cccwork2.wpi.edu -c \"close\""); gettimeofday(&tvEnd, NULL); timeval_subtract(&tvDiff, &tvEnd, &tvBegin); FILE * pFile; pFile = fopen ("setupData.txt","a"); if (pFile!=NULL) { fprintf(pFile, "%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec); fclose (pFile); } printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec); } else if (rflag) { int i; struct timeval tvBegin, tvEnd, tvDiff; FILE * pFile; pFile = fopen ("thruData.txt","a"); for (i = 0; i < 100; i++) { gettimeofday(&tvBegin, NULL); system("./dsh -s cccwork2.wpi.edu -p 4444 -c \"cat testdata.dat\""); gettimeofday(&tvEnd, NULL); timeval_subtract(&tvDiff, &tvEnd, &tvBegin); fprintf(pFile, "%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec); } //system("./dsh -s cccwork2.wpi.edu -c \"close\""); fclose (pFile); //printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec); } else if (fflag) { char *filename, *pfilename; int setup = 0; fstream inStream; printf("here is %s\n", ffile); if (strcmp(ffile, "setup") == 0) { filename = "setupData.txt"; pfilename = "fsetupData.txt"; setup++; } else { filename = "thruData.txt"; pfilename = "fthruData.txt"; } inStream.open(filename, ios :: in); if(inStream.fail()) { //return false; cout << "couldn't open\n"; return 0; } double inNum; FILE *pFile; pFile = fopen(pfilename, "a"); if ( pFile != NULL) { double number; char numtxt[80]; printf("here"); int i; for (i = 0; i < 100; i++) { inStream >> inNum; if (setup) inNum = inNum/100; else inNum = inNum*100; sprintf(numtxt,"%.8f",inNum); puts(numtxt); fputs ( numtxt, pFile ); /* write the line */ } fclose(pFile); } inStream.close(); }
gboolean cairo_dock_manage_themes (GtkWidget *pWidget, gboolean bSafeMode) { GString *sCommand = g_string_new (""); GHashTable *hThemeTable = NULL; gchar *cInitConfFile = cairo_dock_edit_themes (&hThemeTable, bSafeMode); if (cInitConfFile != NULL) { GError *erreur = NULL; gboolean bNeedSave = cairo_dock_theme_need_save (); //\___________________ On recupere les donnees de l'IHM apres modification par l'utilisateur. GKeyFile *pKeyFile = g_key_file_new (); g_key_file_load_from_file (pKeyFile, cInitConfFile, G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, &erreur); g_remove (cInitConfFile); g_free (cInitConfFile); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); return FALSE; } //\___________________ On charge le nouveau theme choisi. gchar *cNewThemeName = g_key_file_get_string (pKeyFile, "Themes", "chosen theme", &erreur); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); erreur = NULL; } if (cNewThemeName != NULL && *cNewThemeName == '\0') { g_free (cNewThemeName); cNewThemeName = NULL; } if (cNewThemeName != NULL) { if (bNeedSave) { int iAnswer = cairo_dock_ask_general_question_and_wait (_("You made some modifications in the current theme.\nYou will loose them if you don't save before choosing a new theme. Continue anyway ?")); if (iAnswer != GTK_RESPONSE_YES) { g_hash_table_destroy (hThemeTable); return TRUE; } else cairo_dock_mark_theme_as_modified (FALSE); } gchar *cNewThemePath = g_hash_table_lookup (hThemeTable, cNewThemeName); //\___________________ On charge les parametres de comportement. if (g_pMainDock == NULL || g_key_file_get_boolean (pKeyFile, "Themes", "use theme behaviour", NULL)) { g_string_printf (sCommand, "/bin/cp '%s'/%s '%s'", cNewThemePath, CAIRO_DOCK_CONF_FILE, g_cCurrentThemePath); cd_message ("%s", sCommand->str); system (sCommand->str); } else { gchar *cNewConfFilePath = g_strdup_printf ("%s/%s", cNewThemePath, CAIRO_DOCK_CONF_FILE); cairo_dock_replace_keys_by_identifier (g_cConfFile, cNewConfFilePath, '+'); g_free (cNewConfFilePath); } //\___________________ On charge les icones. g_string_printf (sCommand, "find '%s' -mindepth 1 ! -name '*.desktop' ! -name 'container-*' -delete", g_cCurrentLaunchersPath); cd_message ("%s", sCommand->str); system (sCommand->str); g_string_printf (sCommand, "find '%s/%s' -mindepth 1 ! -name '*.desktop' -exec /bin/cp -p '{}' '%s' \\;", cNewThemePath, CAIRO_DOCK_LAUNCHERS_DIR, g_cCurrentLaunchersPath); cd_message ("%s", sCommand->str); system (sCommand->str); //\___________________ On charge les lanceurs si necessaire, en effacant ceux existants. if (g_pMainDock == NULL || g_key_file_get_boolean (pKeyFile, "Themes", "use theme launchers", NULL)) { g_string_printf (sCommand, "rm -f '%s'/*.desktop", g_cCurrentLaunchersPath); cd_message ("%s", sCommand->str); system (sCommand->str); g_string_printf (sCommand, "cp '%s/%s'/*.desktop '%s'", cNewThemePath, CAIRO_DOCK_LAUNCHERS_DIR, g_cCurrentLaunchersPath); cd_message ("%s", sCommand->str); system (sCommand->str); } //\___________________ On remplace tous les autres fichiers par les nouveaux. g_string_printf (sCommand, "find '%s' -mindepth 1 -maxdepth 1 ! -name '*.conf' -type f -exec rm -rf '{}' \\;", g_cCurrentThemePath); // efface tous les fichiers du theme mais sans toucher aux lanceurs et aux plug-ins. cd_message ("%s", sCommand->str); system (sCommand->str); /// A FAIRE : fusionner les fichiers de conf des plug-ins si deja presents. g_string_printf (sCommand, "find '%s'/* -prune ! -name '*.conf' ! -name %s -exec /bin/cp -r '{}' '%s' \\;", cNewThemePath, CAIRO_DOCK_LAUNCHERS_DIR, g_cCurrentThemePath); // copie tous les fichiers du nouveau theme sauf les lanceurs et le .conf, dans le repertoire du theme courant. Ecrase les fichiers de memes noms. cd_message ("%s", sCommand->str); system (sCommand->str); //\___________________ On charge le theme courant. cairo_dock_load_theme (g_cCurrentThemePath); g_free (cNewThemeName); g_hash_table_destroy (hThemeTable); return FALSE; } g_free (cNewThemeName); //\___________________ On sauvegarde le theme actuel cNewThemeName = g_key_file_get_string (pKeyFile, "Save", "theme name", &erreur); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); erreur = NULL; } if (cNewThemeName != NULL && *cNewThemeName == '\0') { g_free (cNewThemeName); cNewThemeName = NULL; } cd_message ("cNewThemeName : %s", cNewThemeName); if (cNewThemeName != NULL) { cd_message ("on sauvegarde dans %s", cNewThemeName); gboolean bThemeSaved = FALSE; gchar *cNewThemePath = g_hash_table_lookup (hThemeTable, cNewThemeName); if (cNewThemePath != NULL) // on ecrase un theme existant. { cd_message (" theme existant"); if (strncmp (cNewThemePath, CAIRO_DOCK_SHARE_THEMES_DIR, strlen (CAIRO_DOCK_SHARE_THEMES_DIR)) == 0) // c'est un theme pre-installe. { cd_warning ("You can't overwrite a pre-installed theme"); } else { gchar *question = g_strdup_printf (_("Are you sure you want to overwrite theme %s ?"), cNewThemeName); GtkWidget *dialog = gtk_message_dialog_new (GTK_WINDOW (pWidget), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, question); g_free (question); int answer = gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); if (answer == GTK_RESPONSE_YES) { gchar *cNewConfFilePath = g_strdup_printf ("%s/%s", cNewThemePath, CAIRO_DOCK_CONF_FILE); if (g_key_file_get_boolean (pKeyFile, "Save", "save current behaviour", NULL)) { g_string_printf (sCommand, "/bin/cp '%s' '%s'", g_cConfFile, cNewConfFilePath); cd_message ("%s", sCommand->str); system (sCommand->str); } else { cairo_dock_replace_keys_by_identifier (cNewConfFilePath, g_cConfFile, '+'); } g_free (cNewConfFilePath); if (g_key_file_get_boolean (pKeyFile, "Save", "save current launchers", NULL)) { g_string_printf (sCommand, "rm -f '%s/%s'/*", cNewThemePath, CAIRO_DOCK_LAUNCHERS_DIR); cd_message ("%s", sCommand->str); system (sCommand->str); g_string_printf (sCommand, "cp '%s'/* '%s/%s'", g_cCurrentLaunchersPath, cNewThemePath, CAIRO_DOCK_LAUNCHERS_DIR); cd_message ("%s", sCommand->str); system (sCommand->str); } g_string_printf (sCommand, "find '%s' -mindepth 1 -maxdepth 1 ! -name '*.conf' ! -name '%s' -exec /bin/cp -r '{}' '%s' \\;", g_cCurrentThemePath, CAIRO_DOCK_LAUNCHERS_DIR, cNewThemePath); cd_message ("%s", sCommand->str); system (sCommand->str); bThemeSaved = TRUE; } } } else { cNewThemePath = g_strdup_printf ("%s/%s/%s", g_cCairoDockDataDir, CAIRO_DOCK_THEMES_DIR, cNewThemeName); cd_message (" nouveau theme (%s)", cNewThemePath); if (g_mkdir (cNewThemePath, 7*8*8+7*8+5) != 0) bThemeSaved = FALSE; else { g_string_printf (sCommand, "cp -r '%s'/* '%s'", g_cCurrentThemePath, cNewThemePath); cd_message ("%s", sCommand->str); system (sCommand->str); g_free (cNewThemePath); bThemeSaved = TRUE; } } if (bThemeSaved) cairo_dock_mark_theme_as_modified (FALSE); } //\___________________ On efface les themes qui ne sont plus desires. gsize length = 0; gchar ** cThemesList = g_key_file_get_string_list (pKeyFile, "Delete", "wanted themes", &length, &erreur); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); erreur = NULL; } else if (cThemesList != NULL) { gchar *cThemesDir = g_strdup_printf ("%s/%s", g_cCairoDockDataDir, CAIRO_DOCK_THEMES_DIR); GHashTable *hUserThemeTable = cairo_dock_list_themes (cThemesDir, NULL, &erreur); g_free (cThemesDir); if (erreur != NULL) { cd_warning ("Attention : %s", erreur->message); g_error_free (erreur); erreur = NULL; } else { if (cNewThemeName != NULL) g_hash_table_remove (hUserThemeTable, cNewThemeName); // pour ne pas effacer le theme qu'on vient d'enregistrer. gpointer data[2] = {cThemesList, pWidget}; g_hash_table_foreach (hUserThemeTable, (GHFunc) _cairo_dock_delete_one_theme, data); } g_hash_table_destroy (hUserThemeTable); } g_strfreev (cThemesList); g_free (cNewThemeName); g_key_file_free (pKeyFile); } g_string_free (sCommand, TRUE); g_hash_table_destroy (hThemeTable); return FALSE; }
int main(void) { RunAllTests(); system("PAUSE"); }
int makeflow_archive_copy_preserved_files(struct archive_instance *a, struct batch_task *t, char *task_path ) { struct batch_file *f; struct stat buf; struct list_cursor *cur = list_cursor_create(t->output_files); // Iterate through output files for(list_seek(cur, 0); list_get(cur, (void**)&f); list_next(cur)) { char *file_name = xxstrdup(f->outer_name); debug(D_MAKEFLOW_HOOK,"Trying to copy file to %s",file_name); char *file_to_check = xxstrdup(file_name); //Check to see if the directory was copied as an empty file/incorrectly stat(dirname(file_to_check),&buf); if(S_ISREG(buf.st_mode)){ debug(D_MAKEFLOW,"Removing empty file in the place of directory name %s",file_to_check); char *dirEmpty = string_format("rm -rf %s",file_to_check); system(dirEmpty); free(dirEmpty); } free(file_to_check); // Gets path of output file char *output_file_path = string_format("%s/output_files/%s",task_path,basename(file_name)); char *directory_name = xxstrdup(file_name); debug(D_MAKEFLOW_HOOK,"Creating directory %s",dirname(directory_name)); if(strcmp(directory_name,file_name) != 0){ //Create the upper level directory to copy the output files into if necessary if (!create_dir(directory_name, 0777) && errno != EEXIST){ debug(D_ERROR|D_MAKEFLOW_HOOK,"Failed to create directory %s",directory_name); free(directory_name); free(output_file_path); free(file_name); return 1; } } free(directory_name); // Copy output file or directory over to specified location if(path_is_dir(output_file_path) != 1){ int success = copy_file_to_file(output_file_path, file_name); free(output_file_path); free(file_name); if (!success) { list_cursor_destroy(cur); debug(D_ERROR|D_MAKEFLOW_HOOK,"Failed to copy output file %s to %s\n", output_file_path, file_name); return 1; } } else{ if(copy_dir(output_file_path, file_name) != 0){ list_cursor_destroy(cur); debug(D_ERROR|D_MAKEFLOW_HOOK,"Failed to copy output file %s to %s\n", output_file_path, file_name); free(output_file_path); free(file_name); return 1; } free(output_file_path); free(file_name); } } list_cursor_destroy(cur); return 0; }
/*! * pixHtmlViewer() * * Input: dirin: directory of input image files * dirout: directory for output files * rootname: root name for output files * thumbwidth: width of thumb images * (in pixels; use 0 for default) * viewwidth: maximum width of view images (no up-scaling) * (in pixels; use 0 for default) * copyorig: 1 to copy originals to dirout; 0 otherwise * Return: 0 if OK; 1 on error * * Notes: * (1) The thumb and view reduced images are generated, * along with two html files: * <rootname>.html and <rootname>-links.html * (2) The thumb and view files are named * <rootname>_thumb_xxx.jpg * <rootname>_view_xxx.jpg * With this naming scheme, any number of input directories * of images can be processed into views and thumbs * and placed in the same output directory. */ l_int32 pixHtmlViewer(const char *dirin, const char *dirout, const char *rootname, l_int32 thumbwidth, l_int32 viewwidth, l_int32 copyorig) { char *fname, *fullname, *outname; char *mainname, *linkname, *linknameshort; char *viewfile, *thumbfile; char *shtml, *slink; char charbuf[L_BUF_SIZE]; char htmlstring[] = "<html>"; char framestring[] = "</frameset></html>"; l_int32 i, nfiles, index, w, nimages, ignore; l_float32 factor; PIX *pix, *pixthumb, *pixview; SARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink; PROCNAME("pixHtmlViewer"); if (!dirin) return ERROR_INT("dirin not defined", procName, 1); if (!dirout) return ERROR_INT("dirout not defined", procName, 1); if (!rootname) return ERROR_INT("rootname not defined", procName, 1); if (thumbwidth == 0) thumbwidth = DEFAULT_THUMB_WIDTH; if (thumbwidth < MIN_THUMB_WIDTH) { L_WARNING("thumbwidth too small; using min value", procName); thumbwidth = MIN_THUMB_WIDTH; } if (viewwidth == 0) viewwidth = DEFAULT_VIEW_WIDTH; if (viewwidth < MIN_VIEW_WIDTH) { L_WARNING("viewwidth too small; using min value", procName); viewwidth = MIN_VIEW_WIDTH; } /* Make the output directory if it doesn't already exist */ sprintf(charbuf, "mkdir -p %s", dirout); ignore = system(charbuf); /* Capture the filenames in the input directory */ if ((safiles = getFilenamesInDirectory(dirin)) == NULL) return ERROR_INT("safiles not made", procName, 1); /* Generate output text file names */ sprintf(charbuf, "%s/%s.html", dirout, rootname); mainname = stringNew(charbuf); sprintf(charbuf, "%s/%s-links.html", dirout, rootname); linkname = stringNew(charbuf); linknameshort = stringJoin(rootname, "-links.html"); if ((sathumbs = sarrayCreate(0)) == NULL) return ERROR_INT("sathumbs not made", procName, 1); if ((saviews = sarrayCreate(0)) == NULL) return ERROR_INT("saviews not made", procName, 1); /* Generate the thumbs and views */ nfiles = sarrayGetCount(safiles); index = 0; for (i = 0; i < nfiles; i++) { fname = sarrayGetString(safiles, i, L_NOCOPY); fullname = genPathname(dirin, fname); fprintf(stderr, "name: %s\n", fullname); if ((pix = pixRead(fullname)) == NULL) { fprintf(stderr, "file %s not a readable image\n", fullname); FREE(fullname); continue; } FREE(fullname); if (copyorig) { outname = genPathname(dirout, fname); pixWrite(outname, pix, IFF_JFIF_JPEG); FREE(outname); } /* Make and store the thumb */ w = pixGetWidth(pix); factor = (l_float32)thumbwidth / (l_float32)w; if ((pixthumb = pixScale(pix, factor, factor)) == NULL) return ERROR_INT("pixthumb not made", procName, 1); sprintf(charbuf, "%s_thumb_%03d.jpg", rootname, index); sarrayAddString(sathumbs, charbuf, L_COPY); outname = genPathname(dirout, charbuf); pixWrite(outname, pixthumb, IFF_JFIF_JPEG); FREE(outname); pixDestroy(&pixthumb); /* Make and store the view */ factor = (l_float32)viewwidth / (l_float32)w; if (factor >= 1.0) pixview = pixClone(pix); /* no upscaling */ else { if ((pixview = pixScale(pix, factor, factor)) == NULL) return ERROR_INT("pixview not made", procName, 1); } sprintf(charbuf, "%s_view_%03d.jpg", rootname, index); sarrayAddString(saviews, charbuf, L_COPY); outname = genPathname(dirout, charbuf); pixWrite(outname, pixview, IFF_JFIF_JPEG); FREE(outname); pixDestroy(&pixview); pixDestroy(&pix); index++; } /* Generate the main html file */ if ((sahtml = sarrayCreate(0)) == NULL) return ERROR_INT("sahtml not made", procName, 1); sarrayAddString(sahtml, htmlstring, L_COPY); sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"views\" src=\"%s\">", sarrayGetString(saviews, 0, L_NOCOPY)); sarrayAddString(sahtml, charbuf, L_COPY); sarrayAddString(sahtml, framestring, L_COPY); shtml = sarrayToString(sahtml, 1); l_binaryWrite(mainname, "w", shtml, strlen(shtml)); FREE(shtml); FREE(mainname); /* Generate the link html file */ nimages = sarrayGetCount(saviews); fprintf(stderr, "num. images = %d\n", nimages); if ((salink = sarrayCreate(0)) == NULL) return ERROR_INT("salink not made", procName, 1); for (i = 0; i < nimages; i++) { viewfile = sarrayGetString(saviews, i, L_NOCOPY); thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY); sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>", viewfile, thumbfile); sarrayAddString(salink, charbuf, L_COPY); } slink = sarrayToString(salink, 1); l_binaryWrite(linkname, "w", slink, strlen(slink)); FREE(slink); FREE(linkname); FREE(linknameshort); sarrayDestroy(&safiles); sarrayDestroy(&sathumbs); sarrayDestroy(&saviews); sarrayDestroy(&sahtml); sarrayDestroy(&salink); return 0; }
Types::Transform PointOnPlaneCalibration::estimateTransform(const std::vector<PointPlanePair> & pair_vector) { const int size = pair_vector.size(); // Point-Plane Constraints // Initial system (Eq. 10) Eigen::MatrixXd system(size, 13); for (int i = 0; i < size; ++i) { const double d = pair_vector[i].plane_.offset(); const Eigen::Vector3d n = pair_vector[i].plane_.normal(); const Types::Point3 & x = pair_vector[i].point_; system.row(i) << d + n[0] * x[0] + n[1] * x[1] + n[2] * x[2], // q_0^2 2 * n[2] * x[1] - 2 * n[1] * x[2], // q_0 * q_1 2 * n[0] * x[2] - 2 * n[2] * x[0], // q_0 * q_2 2 * n[1] * x[0] - 2 * n[0] * x[1], // q_0 * q_3 d + n[0] * x[0] - n[1] * x[1] - n[2] * x[2], // q_1^2 2 * n[0] * x[1] + 2 * n[1] * x[0], // q_1 * q_2 2 * n[0] * x[2] + 2 * n[2] * x[0], // q_1 * q_3 d - n[0] * x[0] + n[1] * x[1] - n[2] * x[2], // q_2^2 2 * n[1] * x[2] + 2 * n[2] * x[1], // q_2 * q_3 d - n[0] * x[0] - n[1] * x[1] + n[2] * x[2], // q_3^2 n[0], n[1], n[2]; // q'*q*t } // Gaussian reduction for (int k = 0; k < 3; ++k) for (int i = k + 1; i < size; ++i) system.row(i) = system.row(i) - system.row(k) * system.row(i)[10 + k] / system.row(k)[10 + k]; // Quaternion q Eigen::Vector4d q; // Transform to inhomogeneous (Eq. 13) bool P_is_ok(false); while (not P_is_ok) { Eigen::Matrix4d P(Eigen::Matrix4d::Random()); while (P.determinant() < 1e-5) P = Eigen::Matrix4d::Random(); Eigen::MatrixXd reduced_system(size - 3, 10); for (int i = 3; i < size; ++i) { const Eigen::VectorXd & row = system.row(i); Eigen::Matrix4d Mi_tilde; Mi_tilde << row[0] , row[1] / 2, row[2] / 2, row[3] / 2, row[1] / 2, row[4] , row[5] / 2, row[6] / 2, row[2] / 2, row[5] / 2, row[7] , row[8] / 2, row[3] / 2, row[6] / 2, row[8] / 2, row[9] ; Eigen::Matrix4d Mi_bar(P.transpose() * Mi_tilde * P); reduced_system.row(i - 3) << Mi_bar(0, 0), Mi_bar(0, 1) + Mi_bar(1, 0), Mi_bar(0, 2) + Mi_bar(2, 0), Mi_bar(0, 3) + Mi_bar(3, 0), Mi_bar(1, 1), Mi_bar(1, 2) + Mi_bar(2, 1), Mi_bar(1, 3) + Mi_bar(3, 1), Mi_bar(2, 2), Mi_bar(2, 3) + Mi_bar(3, 2), Mi_bar(3, 3); } // Solve A m* = b Eigen::MatrixXd A = reduced_system.rightCols<9>(); Eigen::VectorXd b = - reduced_system.leftCols<1>(); Eigen::VectorXd m_star = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b); Eigen::Vector4d q_bar(1, m_star[0], m_star[1], m_star[2]); Eigen::VectorXd err(6); err << q_bar[1] * q_bar[1], q_bar[1] * q_bar[2], q_bar[1] * q_bar[3], q_bar[2] * q_bar[2], q_bar[2] * q_bar[3], q_bar[3] * q_bar[3]; err -= m_star.tail<6>(); //if (err.norm() < 0.1) // P is not ok? P_is_ok = true; //std::cout << m_star.transpose() << std::endl; //std::cout << q_bar[1] * q_bar[1] << " " << q_bar[1] * q_bar[2] << " " << q_bar[1] * q_bar[3] << " " //<< q_bar[2] * q_bar[2] << " " << q_bar[2] * q_bar[3] << " " << q_bar[3] * q_bar[3] << std::endl; q = P * q_bar; } // We want q.w > 0 (Why?) //if (q[0] < 0) // q = -q; Eigen::Vector4d tmp_q(q.normalized()); Eigen::Quaterniond rotation(tmp_q[0], tmp_q[1], tmp_q[2], tmp_q[3]); Eigen::VectorXd m(10); m << q[0] * q[0], q[0] * q[1], q[0] * q[2], q[0] * q[3], q[1] * q[1], q[1] * q[2], q[1] * q[3], q[2] * q[2], q[2] * q[3], q[3] * q[3]; // Solve A (q^T q t) = b Eigen::Matrix3d A = system.topRightCorner<3, 3>(); Eigen::Vector3d b = - system.topLeftCorner<3, 10>() * m; Eigen::Translation3d translation(A.colPivHouseholderQr().solve(b) / q.squaredNorm()); // Eigen::Quaterniond tmp(pose.linear()); // Eigen::Translation3d tmp2(pose.translation()); // std::cout << "Prev: " << tmp.normalized().coeffs().transpose() << " " << tmp2.vector().transpose() << std::endl; //std::cout << "PoP : " << rotation.coeffs().transpose() << " " << translation.vector().transpose() << std::endl; return translation * rotation; }
int main(int argc, char* argv[]) { try { char* testname_args[] = {"program.exe","width=640 height=480 window_name", " =GL WINDOW TEST 1 is_fullscreen=false"}; GLWindow::Settings setts(3, testname_args) ; GLWindow glWindow = GLWindow(setts); setts.width=1280; setts.height=720; setts.is_fullscreen=true; setts.is_antialiased = true; setts.antialias_amount = 8; //setts.match_resolution_exactly=true; PCInputBinding b; b.bindButtonDown('a', playBeep); std::function< void () > quit = std::bind(&GLWindow::close, &glWindow); b.bindButtonDown(PCInputBinding::ESCAPE, quit); glWindow.use_binding(b); std::cout<<"Supported resolutions "<<std::endl; std::set<std::pair<int,int>> resolutions = glWindow.getResolutions(); for(std::set<std::pair<int,int>>::const_iterator it = resolutions.begin(); it != resolutions.end(); it++){ std::cout<<it->first<<"::"<<it->second<<std::endl; } glWindow.recreate(setts); glClearColor(0,1,0,1); std::cout<<"Recreated window width is "<<glWindow.getWidth()<<":::"<<glWindow.getHeight()<<std::endl; while(glWindow.isValid()) { // glViewport(0,0,glWindow.getWidth(),glWindow.getHeight()); //glWindow.bind(); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_TRIANGLES); glClearColor(1.0,0.0,0.0,1.0); glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0,0.0,0.0); glVertex3f(-1.0,1.0,0.0); glColor3f(0.0,1.0,0.0); glVertex3f(-1.0,-1.0,0.0); glColor3f(0.0,0.0,1.0); glVertex3f(1.0,-1.0,0.0); glEnd(); glWindow.update(); glWindow.flush(); // } } catch(std::exception& e) { std::cerr << e.what() << std::endl; } system("pause"); return 0; }