void moveFilesProc(XtPointer fsel, int conf) { SelFileNamesRec *fnames = (SelFileNamesRec *) fsel; struct stat tostats, tolstats, frstats; char from[MAXPATHLEN], to[MAXPATHLEN]; String name, cwd; String op_name, from_err, to_err; size_t toend, fromend; int devto, devfrom, deverr = -1, i, perm, res; Boolean is_dir, is_link; if (conf != YES || !fnames->op) { freeSelFiles(fnames); return; } if (chdir(fnames->directory)) { sysError(fnames->shell, "System error:"); freeSelFiles(fnames); return; } chdir(user.home); switch (fnames->op) { case COPY: op_name = "Copy:"; from_err = "Error copying"; to_err = "Error copying to"; break; case MOVE: op_name = "Move:"; from_err = "Error moving"; to_err = "Error moving to"; break; default: /* i.e. LINK */ op_name = "Link:"; from_err = "Error creating symlink to"; to_err = "Error creating symlink in"; } if (fnames->target[0] != '/' && fnames->target[0] != '~' && fnames->target != 0) { strcpy(to, fnames->directory); if (to[strlen(to)-1] != '/') strcat(to, "/"); } else to[0] = 0; strcat(to, fnames->target); fnexpand(to); if (!(cwd = absolutePath(to))) { error(fnames->shell, no_target, to); freeSelFiles(fnames); return; } strcpy(to, cwd); XTFREE(cwd); fromend = strlen(strcpy(from, fnames->directory)); if (from[fromend-1] != '/') { from[fromend++] = '/'; from[fromend] = 0; } devfrom = findDev(from); if (mountDev(devto = findDev(to), False)) deverr = devto; else if (mountDev(devfrom, False)) deverr = devfrom; if (deverr != -1) { error(fnames->shell, "Cannot mount device on", mntable.devices[deverr].def_mpoint); umountDev(devto, False); freeSelFiles(fnames); return; } if (!(stat(to, &tostats)) && S_ISDIR(tostats.st_mode)) { if (chdir(to) || !(perm = permission(&tostats, P_WRITE))) { chdir(user.home); if (!perm) error(fnames->shell, "You have no write permission for ", to); else sysError(fnames->shell, "System error:"); umountDev(devto, False); umountDev(devfrom, False); freeSelFiles(fnames); return; } chdir(user.home); fnames->dirtarget = True; toend = strlen(to); if (to[toend-1] != '/') { to[toend++] = '/'; to[toend] = 0; } } else if (fnames->n_sel == 1) fnames->dirtarget = False; else { error(fnames->shell, op_name, "Target for multiple files must be a folder"); umountDev(devto, False); umountDev(devfrom, False); freeSelFiles(fnames); return; } if (!fnames->first) zzz(); XTFREE(fnames->target); fnames->target = XtNewString(to); for (i = fnames->first; i < fnames->n_sel; i++) { name = fnames->names[i]; if (fnames->op != LINK && (!strcmp(name, ".") || !strcmp(name, ".."))) { error(fnames->shell, "Cannot move or copy . or ..", NULL); continue; } strcpy(from+fromend, name); if (fnames->dirtarget) { if (fnames->op != LINK && prefix(from, to)) { String err_str, format = "Cannot move or copy %s to"; err_str = (String) XtMalloc((strlen(format) + strlen(from)) * sizeof(char)); sprintf(err_str, format, from); error(fnames->shell, err_str, to); XTFREE(err_str); umountDev(devto, False); umountDev(devfrom, False); freeSelFiles(fnames); wakeUp(); return; } strcpy(to+toend, name); } if (!(lstat(to, &tolstats))) { fnames->first = i; is_dir = False; if (!(stat(to, &tostats))) { if (S_ISDIR(tostats.st_mode)) is_dir = True; if (!stat(from, &frstats) && tostats.st_ino == frstats.st_ino) { error(fnames->shell, op_name, "Source and destination are identical"); umountDev(devto, False); umountDev(devfrom, False); freeSelFiles(fnames); wakeUp(); return; } } if (S_ISLNK(tolstats.st_mode)) is_link = True; else is_link = False; if (fnames->conf_ovwr || (is_dir && (!is_link || fnames->op == COPY) && resources.confirm_delete_folder)) overwriteDialog(fnames, to, (fnames->op == COPY && is_dir && (lstat(from, &frstats) || !S_ISDIR(frstats.st_mode)))? "File copy:" : op_name, is_dir && (!is_link || fnames->op == COPY)); else overwriteProc(fsel, YES); umountDev(devto, False); umountDev(devfrom, False); return; } switch (fnames->op) { case COPY: rcopy(from, to, False); res = 0; break; case MOVE: res = movefile(from, to); break; default: res = makeLink(from, to); } if (res) { if (opError(fnames->shell, from_err, name) != YES) break; } else fnames->update = True; } umountDev(devto, False); umountDev(devfrom, False); if (fnames->update) { if (fnames->op == COPY) intUpdate(CHECK_DIR); /* Check for new subdirectories */ if (fnames->op == MOVE) markForUpdate(fnames->directory, CHECK_FILES); markForUpdate(to, RESHOW); if (fnames->op != COPY) intUpdate(CHECK_DIR); } freeSelFiles(fnames); wakeUp(); }
void BlockDataManagerConfig::parseArgs(int argc, char* argv[]) { /*** --testnet: run db against testnet bitcoin network --regtest: run db against regression test network --rescan: delete all processed history data and rescan blockchain from the first block --rebuild: delete all DB data and build and scan from scratch --rescanSSH: delete balance and txcount data and rescan it. Much faster than rescan or rebuild. --datadir: path to the operation folder --dbdir: path to folder containing the database files. If empty, a new db will be created there --satoshi-datadir: path to blockchain data folder (blkXXXXX.dat files) --ram_usage: defines the ram use during scan operations. 1 level averages 128MB of ram (without accounting the base amount, ~400MB). Defaults at 4. Can't be lower than 1. Can be changed in between processes --thread-count: defines how many processing threads can be used during db builds and scans. Defaults to maximum available CPU threads. Can't be lower than 1. Can be changed in between processes --zcthread-count: defines the maximum number on threads the zc parser can create for processing incoming transcations from the network node --db-type: sets the db type: DB_BARE: tracks wallet history only. Smallest DB. DB_FULL: tracks wallet history and resolves all relevant tx hashes. ~750MB DB at the time of 0.95 release. Default DB type. DB_SUPER: tracks all blockchain history. XXL DB (100GB+). Not implemented yet db type cannot be changed in between processes. Once a db has been built with a certain type, it will always function according to that type. Specifying another type will do nothing. Build a new db to change type. --cookie: create a cookie file holding a random authentication key to allow local clients to make use of elevated commands, like shutdown. --fcgi-port: sets the DB listening port. --clear-mempool: delete all zero confirmation transactions from the DB. ***/ try { //parse cli args map<string, string> args; for (int i = 1; i < argc; i++) { //check prefix if (strlen(argv[i]) < 2) throw DbErrorMsg("invalid CLI arg"); string prefix(argv[i], 2); if (prefix != "--") throw DbErrorMsg("invalid CLI arg"); //string prefix and tokenize string line(argv[i] + 2); auto&& argkeyval = getKeyValFromLine(line, '='); args.insert(make_pair( argkeyval.first, stripQuotes(argkeyval.second))); } processArgs(args, true); //figure out datadir auto argIter = args.find("datadir"); if (argIter != args.end()) { dataDir_ = argIter->second; args.erase(argIter); } else { if (!testnet_ && !regtest_) dataDir_ = defaultDataDir_; else if (!regtest_) dataDir_ = defaultTestnetDataDir_; else dataDir_ = defaultRegtestDataDir_; } expandPath(dataDir_); //get datadir auto configPath = dataDir_; appendPath(configPath, "armorydb.conf"); if (DBUtils::fileExists(configPath, 2)) { ConfigFile cf(configPath); auto mapIter = cf.keyvalMap_.find("datadir"); if (mapIter != cf.keyvalMap_.end()) throw DbErrorMsg("datadir is illegal in .conf file"); processArgs(cf.keyvalMap_, false); } processArgs(args, false); //figure out defaults bool autoDbDir = false; if (dbDir_.size() == 0) { dbDir_ = dataDir_; appendPath(dbDir_, dbDirExtention_); autoDbDir = true; } if (blkFileLocation_.size() == 0) { if (!testnet_) blkFileLocation_ = defaultBlkFileLocation_; else blkFileLocation_ = defaultTestnetBlkFileLocation_; } //expand paths if necessary expandPath(dbDir_); expandPath(blkFileLocation_); if (blkFileLocation_.size() < 6 || blkFileLocation_.substr(blkFileLocation_.length() - 6, 6) != "blocks") { appendPath(blkFileLocation_, "blocks"); } logFilePath_ = dataDir_; appendPath(logFilePath_, "dbLog.txt"); //test all paths auto testPath = [](const string& path, int mode) { if (!DBUtils::fileExists(path, mode)) { stringstream ss; ss << path << " is not a valid path"; cout << ss.str() << endl; throw DbErrorMsg(ss.str()); } }; testPath(dataDir_, 6); //create dbdir if was set automatically if (autoDbDir) { try { testPath(dbDir_, 0); } catch (DbErrorMsg&) { #ifdef _WIN32 CreateDirectory(dbDir_.c_str(), NULL); #else mkdir(dbDir_.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif } } //now for the regular test, let it throw if it fails testPath(dbDir_, 6); testPath(blkFileLocation_, 2); //fcgi port if (useCookie_ && !customFcgiPort_) { //no custom fcgi port was provided and the db was spawned with a //cookie file, fcgi port will be randomized srand(time(0)); while (1) { auto port = rand() % 15000 + 49150; stringstream portss; portss << port; if (!testConnection("127.0.0.1", portss.str())) { fcgiPort_ = portss.str(); break; } } } } catch (...) { exceptionPtr_ = current_exception(); } }
QString IrcMessagePrivate::host() const { if (m_host.isNull()) parsePrefix(prefix(), &m_nick, &m_ident, &m_host); return m_host; }
PRBool nsDefaultURIFixup::MakeAlternateURI(nsIURI *aURI) { if (!mPrefBranch) { return PR_FALSE; } PRBool makeAlternate = PR_TRUE; mPrefBranch->GetBoolPref("browser.fixup.alternate.enabled", &makeAlternate); if (!makeAlternate) { return PR_FALSE; } // Code only works for http. Not for any other protocol including https! PRBool isHttp = PR_FALSE; aURI->SchemeIs("http", &isHttp); if (!isHttp) { return PR_FALSE; } // Security - URLs with user / password info should NOT be fixed up nsCAutoString userpass; aURI->GetUserPass(userpass); if (!userpass.IsEmpty()) { return PR_FALSE; } nsCAutoString oldHost; nsCAutoString newHost; aURI->GetHost(oldHost); // Count the dots PRInt32 numDots = 0; nsReadingIterator<char> iter; nsReadingIterator<char> iterEnd; oldHost.BeginReading(iter); oldHost.EndReading(iterEnd); while (iter != iterEnd) { if (*iter == '.') numDots++; ++iter; } nsresult rv; // Get the prefix and suffix to stick onto the new hostname. By default these // are www. & .com but they could be any other value, e.g. www. & .org nsCAutoString prefix("www."); nsXPIDLCString prefPrefix; rv = mPrefBranch->GetCharPref("browser.fixup.alternate.prefix", getter_Copies(prefPrefix)); if (NS_SUCCEEDED(rv)) { prefix.Assign(prefPrefix); } nsCAutoString suffix(".com"); nsXPIDLCString prefSuffix; rv = mPrefBranch->GetCharPref("browser.fixup.alternate.suffix", getter_Copies(prefSuffix)); if (NS_SUCCEEDED(rv)) { suffix.Assign(prefSuffix); } if (numDots == 0) { newHost.Assign(prefix); newHost.Append(oldHost); newHost.Append(suffix); } else if (numDots == 1) { if (!prefix.IsEmpty() && oldHost.EqualsIgnoreCase(prefix.get(), prefix.Length())) { newHost.Assign(oldHost); newHost.Append(suffix); } else if (!suffix.IsEmpty()) { newHost.Assign(prefix); newHost.Append(oldHost); } else { // Do nothing return PR_FALSE; } } else { // Do nothing return PR_FALSE; } if (newHost.IsEmpty()) { return PR_FALSE; } // Assign the new host string over the old one aURI->SetHost(newHost); return PR_TRUE; }
/* * ut_start -- initialize unit test framework, indicate test started */ void ut_start(const char *file, int line, const char *func, int argc, char * const argv[], const char *fmt, ...) { va_list ap; int saveerrno = errno; char logname[MAXLOGNAME]; char *logsuffix; va_start(ap, fmt); if (getenv("UNITTEST_NO_SIGHANDLERS") == NULL) ut_register_sighandlers(); if (getenv("UNITTEST_QUIET") != NULL) Quiet++; Testname = getenv("UNITTEST_NAME"); if ((logsuffix = getenv("UNITTEST_NUM")) == NULL) logsuffix = ""; snprintf(logname, MAXLOGNAME, "out%s.log", logsuffix); if ((Outfp = fopen(logname, "w")) == NULL) { perror(logname); exit(1); } snprintf(logname, MAXLOGNAME, "err%s.log", logsuffix); if ((Errfp = fopen(logname, "w")) == NULL) { perror(logname); exit(1); } snprintf(logname, MAXLOGNAME, "trace%s.log", logsuffix); if ((Tracefp = fopen(logname, "w")) == NULL) { perror(logname); exit(1); } setlinebuf(Outfp); setlinebuf(Errfp); setlinebuf(Tracefp); setlinebuf(stdout); prefix(file, line, func, 0); vout(OF_LOUD|OF_NAME, "START", fmt, ap); out(OF_NONL, 0, " args:"); for (int i = 0; i < argc; i++) out(OF_NONL, " %s", argv[i]); out(0, NULL); va_end(ap); record_open_files(); long long sc = sysconf(_SC_PAGESIZE); if (sc < 0) abort(); Ut_pagesize = (unsigned long)sc; errno = saveerrno; }
/* * Prepare "curses" for use by the file "z-term.c" * * Installs the "hook" functions defined above, and then activates * the main screen "term", which clears the screen and such things. * * Someone should really check the semantics of "initscr()" */ errr init_gcu(int argc, char **argv) { int i; int rows, cols, y, x; int next_win = 0; bool graphics = TRUE; /* Initialize info about terminal capabilities */ termtype = getenv("TERM"); loaded_terminfo = termtype && tgetent(0, termtype) == 1; /* Parse args */ for (i = 1; i < argc; i++) { if (prefix(argv[i], "-b")) use_big_screen = TRUE; else if (prefix(argv[i], "-B")) bold_extended = TRUE; else if (prefix(argv[i], "-a")) graphics = FALSE; else plog_fmt("Ignoring option: %s", argv[i]); } if (graphics) { ctrl_char[CTRL_WALL] = ' '; ctrl_attr[CTRL_ORE] = A_REVERSE; ctrl_attr[CTRL_WALL] = A_REVERSE; ctrl_attr[CTRL_ROCK] = A_REVERSE; } /* Extract the normal keymap */ keymap_norm_prepare(); /* We do it like this to prevent a link error with curseses that * lack ESCDELAY. */ if (!getenv("ESCDELAY")) putenv("ESCDELAY=20"); /* Initialize */ if (initscr() == NULL) return (-1); /* Activate hooks */ quit_aux = hook_quit; /* Require standard size screen */ if (LINES < 24 || COLS < 80) quit("Angband needs at least an 80x24 'curses' screen"); #ifdef A_COLOR /* Do we have color, and enough color, available? */ can_use_color = ((start_color() != ERR) && has_colors() && (COLORS >= 8) && (COLOR_PAIRS >= 8)); #ifdef HAVE_USE_DEFAULT_COLORS /* Should we use curses' "default color" */ /* * Turned off since it screws up the colors, * making background white and text black. -CJN */ /* if (use_default_colors() == OK) bg_color = -1; */ #endif /* Attempt to use colors */ if (can_use_color) { /* Prepare the color pairs */ /* PAIR_WHITE (pair 0) is *always* WHITE on BLACK */ init_pair(PAIR_RED, COLOR_RED, bg_color); init_pair(PAIR_GREEN, COLOR_GREEN, bg_color); init_pair(PAIR_YELLOW, COLOR_YELLOW, bg_color); init_pair(PAIR_BLUE, COLOR_BLUE, bg_color); init_pair(PAIR_MAGENTA, COLOR_MAGENTA, bg_color); init_pair(PAIR_CYAN, COLOR_CYAN, bg_color); init_pair(PAIR_BLACK, COLOR_BLACK, bg_color); /* Prepare the colors */ colortable[TERM_DARK] = (COLOR_PAIR(PAIR_BLACK)); colortable[TERM_WHITE] = (COLOR_PAIR(PAIR_WHITE) | A_BRIGHT); colortable[TERM_SLATE] = (COLOR_PAIR(PAIR_WHITE)); colortable[TERM_ORANGE] = (COLOR_PAIR(PAIR_YELLOW) | A_BRIGHT); colortable[TERM_RED] = (COLOR_PAIR(PAIR_RED)); colortable[TERM_GREEN] = (COLOR_PAIR(PAIR_GREEN)); colortable[TERM_BLUE] = (COLOR_PAIR(PAIR_BLUE)); colortable[TERM_UMBER] = (COLOR_PAIR(PAIR_YELLOW)); colortable[TERM_L_DARK] = (COLOR_PAIR(PAIR_BLACK) | A_BRIGHT); colortable[TERM_L_WHITE] = (COLOR_PAIR(PAIR_WHITE)); colortable[TERM_L_PURPLE] = (COLOR_PAIR(PAIR_MAGENTA)); colortable[TERM_YELLOW] = (COLOR_PAIR(PAIR_YELLOW) | A_BRIGHT); colortable[TERM_L_RED] = (COLOR_PAIR(PAIR_MAGENTA) | A_BRIGHT); colortable[TERM_L_GREEN] = (COLOR_PAIR(PAIR_GREEN) | A_BRIGHT); colortable[TERM_L_BLUE] = (COLOR_PAIR(PAIR_BLUE) | A_BRIGHT); colortable[TERM_L_UMBER] = (COLOR_PAIR(PAIR_YELLOW)); colortable[TERM_PURPLE] = (COLOR_PAIR(PAIR_MAGENTA)); colortable[TERM_VIOLET] = (COLOR_PAIR(PAIR_MAGENTA)); colortable[TERM_TEAL] = (COLOR_PAIR(PAIR_CYAN)); colortable[TERM_MUD] = (COLOR_PAIR(PAIR_YELLOW)); colortable[TERM_L_YELLOW] = (COLOR_PAIR(PAIR_YELLOW | A_BRIGHT)); colortable[TERM_MAGENTA] = (COLOR_PAIR(PAIR_MAGENTA | A_BRIGHT)); colortable[TERM_L_TEAL] = (COLOR_PAIR(PAIR_CYAN | A_BRIGHT)); colortable[TERM_L_VIOLET] = (COLOR_PAIR(PAIR_MAGENTA | A_BRIGHT)); colortable[TERM_L_PINK] = (COLOR_PAIR(PAIR_MAGENTA | A_BRIGHT)); colortable[TERM_MUSTARD] = (COLOR_PAIR(PAIR_YELLOW)); colortable[TERM_BLUE_SLATE] = (COLOR_PAIR(PAIR_BLUE)); colortable[TERM_DEEP_L_BLUE] = (COLOR_PAIR(PAIR_BLUE)); } #endif /* Paranoia -- Assume no waiting */ nodelay(stdscr, FALSE); /* Prepare */ cbreak(); noecho(); nonl(); /* Tell curses to rewrite escape sequences to KEY_UP and friends */ keypad(stdscr, TRUE); /* Extract the game keymap */ keymap_game_prepare(); /*** Now prepare the term(s) ***/ for (i = 0; i < MAX_TERM_DATA; i++) { if (use_big_screen && i > 0) break; /* Get the terminal dimensions; if the user asked for a big screen * then we'll put the whole screen in term 0; otherwise we'll divide * it amongst the available terms */ get_gcu_term_size(i, &rows, &cols, &y, &x); /* Skip non-existant windows */ if (rows <= 0 || cols <= 0) continue; /* Create a term */ term_data_init_gcu(&data[next_win], rows, cols, y, x); /* Remember the term */ angband_term[next_win] = &data[next_win].t; /* One more window */ next_win++; } /* Activate the "Angband" window screen */ Term_activate(&data[0].t); /* Remember the active screen */ term_screen = &data[0].t; /* Success */ return (0); }
int sys_setxattr (const char *path, const char *uname, const void *value, size_t size, int flags) { const char *name = prefix(uname); #if defined(HAVE_SETXATTR) #ifndef XATTR_ADD_OPT return setxattr(path, name, value, size, flags); #else int options = 0; return setxattr(path, name, value, size, 0, options); #endif #elif defined(HAVE_SETEA) return setea(path, name, value, size, flags); #elif defined(HAVE_EXTATTR_SET_FILE) int retval = 0; if (flags) { /* Check attribute existence */ retval = extattr_get_file(path, EXTATTR_NAMESPACE_USER, uname, NULL, 0); if (retval < 0) { /* REPLACE attribute, that doesn't exist */ if (flags & XATTR_REPLACE && errno == ENOATTR) { errno = ENOATTR; return -1; } /* Ignore other errors */ } else { /* CREATE attribute, that already exists */ if (flags & XATTR_CREATE) { errno = EEXIST; return -1; } } } retval = extattr_set_file(path, EXTATTR_NAMESPACE_USER, uname, value, size); return (retval < 0) ? -1 : 0; #elif defined(HAVE_ATTR_SET) int myflags = 0; char *attrname = strchr(name,'.') + 1; if (strncmp(name, "system", 6) == 0) myflags |= ATTR_ROOT; if (flags & XATTR_CREATE) myflags |= ATTR_CREATE; if (flags & XATTR_REPLACE) myflags |= ATTR_REPLACE; return attr_set(path, attrname, (const char *)value, size, myflags); #elif defined(HAVE_ATTROPEN) int ret = -1; int myflags = O_RDWR; int attrfd; if (flags & XATTR_CREATE) myflags |= O_EXCL; if (!(flags & XATTR_REPLACE)) myflags |= O_CREAT; attrfd = solaris_attropen(path, name, myflags, (mode_t) SOLARIS_ATTRMODE); if (attrfd >= 0) { ret = solaris_write_xattr(attrfd, value, size); close(attrfd); } return ret; #else errno = ENOSYS; return -1; #endif }
main() { int state 1000, i, book, volume, corp, report; int na; char *v[20], **vv, **rr; char ubuff[1000], *up; char line[100]; char *p, *s, *r, *q; while (gets(line)) { if (line[1]>'9' || line[1]<'0') continue; switch(line[0]) { case 'T': if (state > 'T') { book=0; report=0; printf("\n%%T "); } printf("%s\n", line+18); state='T'; na = getargs(line+18, v); for(i=0;i<na;i++) if (strcmp(v[i], "(Book)")==0) book=1; continue; case 'A': state = 'A'; na=getargs(line+18, vv=v); if (na<=0) continue; while (na>0) { printf("%%A "); corp=0; for(p=vv[1]; *p; p++) if (islower(*p)) corp=1; if (corp==0) { for(p=vv[1]; *p; p++) printf("%c. ", *p); if (na>2 &&strcmp(vv[2], "+")) { printf("%s", vv[0]); if (strcmp(vv[2], "Jr.")==0) printf(","); printf(" %s\n",vv[2]); vv++; na--; } else printf("%s\n", vv[0]); } else printf("%s %s\n",vv[0],vv[1]); vv+=2; na-=2; if (strcmp(vv[0], "+")==0) { vv++; na--; } } continue; case 'U': if (state!='U') ubuff[0]=0; else strcat(ubuff, " "); state = 'U'; strcat(ubuff, line+18); if (line[2]=='.') { /* end of item */ p=ubuff; /*start*/ volume=0; for(s=ubuff; *s; s++) if (s[-1]==' ' && prefix("Vol", s)) { for(q=s-1; q>ubuff; q--) { if (*q==' ' || *q==',') *q=0; else break; } volume=1; break; } if (*s==0) for(s=ubuff; *s && (*s!=',' || sprefix("Inc", s+1)); s++) ; else s++; if (*s==',')*s++=0; if (book) printf("%%I %s\n",ubuff); else if (volume) printf("%%J %s\n", ubuff); else if (substr(ubuff, "Report")!=0) { report=1; printf("%%R %s\n", ubuff); } else printf("%%J %s\n", ubuff); if (volume) { s += 3; /* Vol */ if (*s=='.') s++; while (*s==' ')s++; printf("%%V "); while (*s && *s != ' ' && *s!=',' && *s!=';' && *s!= ':') putchar(*s++); putchar('\n'); if (*s==':') { printf("%%N "); while (*s==' ')s++; while (isdigit(*s)) putchar(*s++); putchar('\n'); } *s++=0; while (*s==' ')*s++=0; if (s[0]=='N' && s[1]=='o' && (s[2]==' '||s[2]=='.')) { s+=2; while (*s==' '||*s=='.')s++; printf("%%N "); while (isdigit(*s)||*s=='-') putchar(*s++); putchar('\n'); } if (*s==',') *s++=0; } for(rr=months; *rr; rr++) { q= substr(s, *rr); if (q) { for(r=q; *r; r++); r--; if (*r=='.')*r=0; printf("%%D %s\n",q); *(q-1)=0; break; } } if (*rr==0) { for(q=s; *q; q++) { if (q[0]=='1' && q[1]=='9' && (q[4]==0 || (q[4]=='.' && q[5]==0))) { if (q[4]=='.') q[4]=0; printf("%%D %s\n",q); rr=months; q[-1]=0; if (q==s) q[0]=0; break; } } } if (*rr==0) /* no date */ printf("%%D 19xx\n"); /* if book bite off next field for city, if report for issuer */ if (book) { for(q=s; *q && *q != ','; q++) ; if (*q==',') { r=q; r++; while (*r==' ')r++; if (isupper(r[0]) && isupper(r[1])) { r+=2; *r++=0; while (*r==' ')r++; } else *q=0; printf("%%C %s\n", s); s=r; } } for(q=s; *q; q++) { if (q[0]==' ' && q[1]=='p' && (q[2]=='p'||q[2]==0)) { for(r=q; r>s; r--) { if (*r==' ' || *r==',') *r=0; } *q=0; q+=2; if (q[0]=='p')q++; while (*q==' '||*q=='.')q++; r=q; while (isdigit(*q)||*q=='.'||*q=='-'||isalpha(*q))q++; *q++=0; while (*q==' ')q++; printf("%%P %s\n",r); break; } } s=ispp(s); while (*s==' ')s++; while (*q==' ')q++; if (*s||*q) printf("%%O %s %s\n", *s?s:"", *q?q:""); } continue; } } }
input () { int infile; int n; long dist; int nfd; int stat, slen; char otherbuf[S_BSIZE]; char tempbuf[24]; char *fromptr, *toptr, *ccptr, *subjptr, *bccptr, *otherptr; sigtype (*old1) (), (*old2) (), (*old3) (); register int i; printf ("SND (%s)\n", verdate); bccflag = 0; dropen(DRBEGIN); /* Set up headers to be written into the draft file */ fromptr = from; toptr = to; ccptr = cc; subjptr = subject; bccptr = bcc; otherptr = otherbuf; strcpy(from, signature); strcpy(otherptr, fromname); strcat(otherptr, fromptr); strcpy(fromptr, otherptr); strcpy(otherptr, toname); strcat(otherptr, toptr); strcpy(toptr, otherptr); strcpy(otherptr, ccname); strcat(otherptr, ccptr); strcpy(ccptr, otherptr); slen = strlen( subjname ); strcpy(otherptr, subjname); strcat(otherptr, subjptr); strcpy(subjptr, otherptr); /* Write the header info to the draft file */ if(write(drffd, fromptr, strlen(fromptr)) < 0) { printf("Cannot write draft %s\n", drffile); s_exit(-1); } write(drffd, "\n", 1); write(drffd, toptr, strlen(toptr)); write(drffd, "\n", 1); write(drffd, ccptr, strlen(ccptr)); write(drffd, "\n", 1); /* If there are blind carbon copies write the necessary header b.s. */ if(bcc[0] != '\0') { strcpy(otherptr, bccname); strcat(otherptr, bccptr); strcpy(bccptr, otherptr); write(drffd, bccptr, strlen(subjptr)); write(drffd, "\n", 1); bccflag = 1; } if( strlen( subject ) > slen ) { char newsubj[S_BSIZE], *p, *pnt; char *index(); int plc; newsubj[0] = '\0'; pnt = subjptr; while( (p = index(pnt,'\n')) != 0 ) { *p++ = '\0'; plc = strlen(newsubj); sprintf( &newsubj[plc],"%s\n%s",pnt," "); pnt = p; } strcat( newsubj, pnt ); strcpy( subjptr, newsubj ); } write(drffd, subjptr, strlen(subjptr)); write(drffd, "\n\n", 2); /* If there is a forwarded message */ if (inclfile[0] != '\0') { /* tack file to end of message */ body = TRUE; strcpy (bigbuf, inclfile); infile = open (bigbuf, 0); if (inclfile[0] != '\0') inclfile[0] = '\0'; if (infile < 0) printf ("can't open: '%s'\n", bigbuf); dropen (DREND); body = TRUE; while ((i = read (infile, bigbuf, BBSIZE - 1)) > 0) write (drffd, bigbuf, i); (void) close (infile); } edit: fflush (stdout); drclose (); old1 = signal (SIGHUP, SIG_IGN); /* ignore signals intended for edit */ old2 = signal (SIGINT, SIG_IGN); old3 = signal (SIGQUIT, SIG_IGN); /* Crank up the editor now that the draft file is set-up */ if (fork () == 0) { signal (SIGHUP, old1); signal (SIGINT, orig); signal (SIGQUIT, old3); execlp (editor, editor, drffile, (char *)0); fprintf (stderr,"can't execute\n"); s_exit (-1); } wait (&stat); body = TRUE; /* Don't know but assume he created a draft */ lastsend = 0; signal (SIGHUP, old1); /* restore signals */ signal (SIGINT, old2); signal (SIGQUIT, old3); fflush (stdout); signal (SIGINT, SIG_IGN); signal (SIGQUIT, SIG_IGN); dropen(DRBEGIN); /* Rip the header information from the draft file and ** take care of any aliases ** Algorithm: ** Read each header line (function grabaddr), keeping track of the ** number of characters read. Handle the aliases (function doalias). ** Open a new file descriptor which points to the beginning of the ** draft file. Read the draft file from the point where the header ** information leaves off while writing to the draft from the beginning. ** This effectively reads the header info, then shifts the body of the ** message up to the top of the draft, overwriting the header. */ dist = gethdr( fromptr, toptr, ccptr, bccptr, subjptr ); doalias( toptr ); doalias( ccptr ); doalias( bccptr ); if(chmod(drffile, 0600) < 0) { fprintf(stderr,"Unable to make draft writable %s.\n", drffile); s_exit(-1); } if((nfd = open(drffile, 2, 600)) < 0) { fprintf(stderr,"Could not open draft %s\n", drffile); s_exit(-1); } if(lseek(nfd, 0L, 0) < 0) { fprintf(stderr,"Lseek failed on draft %s\n", drffile); s_exit(-1); } if(lseek(drffd, dist-1, 0) < 0) { fprintf(stderr,"Lseek failed on draft %s\n", drffile); s_exit(-1); } dist = 0L; while((i = read(drffd, bigbuf, BBSIZE -1)) > 0) dist += write(nfd, bigbuf, i); if(truncate(drffile, dist) < 0) { fprintf(stderr,"Truncate failed on draft %s\n", drffile); s_exit(-1); } if(chmod(drffile, 0400) < 0) fprintf(stderr,"Unable to make draft %s writable.\n",drffile); (void) close( nfd ); setjmp (savej); nsent = 0; /* ** MAIN COMMAND INTERPRETER LOOP */ for (;;) { char *cp; signal (SIGINT, onint3); printf ("Command or ?: "); fflush (stdout); aborted = FALSE; if (fgets (bigbuf, BBSIZE, stdin) == NULL) goto byebye; if (cp = index(bigbuf, '\n')) *cp = '\0'; /* "Set" option */ if( strncmp( "set", bigbuf, 3) == 0){ char *av[NARGS]; i = sstr2arg(bigbuf, 20, av, " \t"); if( i == 1 ) { /* tell him what the current options are */ printf(" Copyfile - '%s'\n", copyfile); printf(" Signature - '%s'\n", signature); printf(" Aliases - '%s'\n", aliasfilename); printf(" Editor - '%s'\n", editor); printf(" Checker - '%s'\n", checker); printf(" Subargs - '%s'\n", subargs); if(qflag == 0 && cflag == 1) printf(" File copy option is on\n"); if(qflag == 1 && cflag == 0) printf(" File copy on confirmation only\n"); continue; } if( (i = picko( av[1] ) ) < 0) { fprintf(stderr,"Option '%s' is invalid.\n", av[1]); continue; } select_o( i, &av[1] ); continue; } compress (bigbuf, bigbuf); /* so prefix works on multi-words */ if (bigbuf[0] == '\0') continue; /* just hit newline */ signal (SIGINT, onint); for (i = 0; !isnull (bigbuf[i]); i++) bigbuf[i] = uptolow (bigbuf[i]); if (prefix ("bcc", bigbuf)) { getaddr (bccname, bcc, YES, locname); bccflag = 1; continue; } /* "Edit" option (grandfathered to also accept "v" for visual edit) */ if (prefix ("edit body", bigbuf) || prefix("visual edit body", bigbuf)) { dropen( DRBEGIN ); if((tmpfd = open(tmpdrffile, 2, 0600)) < 0) { fprintf(stderr,"Cannot open temporary draft file %s\n", tmpdrffile); s_exit(-1); } if(lseek(tmpfd, 0L, 0) < 0) { fprintf(stderr,"Lseek failed on temporary draft file %s\n", tmpdrffile); s_exit(-1); } if(chmod(drffile, 0600) < 0) fprintf(stderr,"Could not make draft %s writable\n", drffile); /* Write the header info to the temporary draft */ dist = 0L; dist += write(tmpfd, fromname, strlen( fromname )); dist += write(tmpfd, from, strlen( from )); dist += write(tmpfd, "\n", 1); dist += write(tmpfd, toname, strlen( toname )); dist += write(tmpfd, to, strlen( to )); dist += write(tmpfd, "\n", 1); dist += write(tmpfd, ccname, strlen( ccname )); dist += write(tmpfd, cc, strlen( cc )); dist += write(tmpfd, "\n", 1); if(bccflag) { dist += write(tmpfd, bccname, strlen( bccname )); dist += write(tmpfd, bcc, strlen( bcc )); dist += write(tmpfd, "\n", 1); } dist += write(tmpfd, subjname, strlen( subjname )); dist += write(tmpfd, subject, strlen( subject )); dist += write(tmpfd, "\n", 1); if(lseek(drffd, 0L, 0) < 0) { fprintf(stderr,"Lseek failed on draft %s\n", drffile); s_exit(-1); } if(lseek(tmpfd, 0L, 2) < 0) { fprintf(stderr,"Lseek failed on temporary draft\n"); s_exit(-1); } /* Write the body into the temp. draft */ while((i = read(drffd, bigbuf, BBSIZE-1)) > 0) dist += write(tmpfd, bigbuf, i); if(truncate( tmpdrffile, dist) < 0) { fprintf(stderr,"Could not truncate temporary draft\n"); s_exit(-1); } if(lseek(tmpfd, 0L, 0) < 0) fprintf(stderr,"Lseek failed on temporary draft\n"); if(lseek(drffd, 0L, 0) < 0) fprintf(stderr,"Lseek failed on draft %s\n", drffile); dist = 0L; /* Copy temp. draft which contains headers and ** body back into draft file */ while((i = read(tmpfd, bigbuf, BBSIZE-1)) > 0) dist += write(drffd, bigbuf, i); if(truncate( drffile, dist ) < 0) fprintf(stderr,"Could not truncate draft %s\n", drffile); if(truncate( tmpdrffile, 0 ) < 0) fprintf(stderr,"Could not truncate temporary draft\n"); if(close( tmpfd ) < 0) fprintf(stderr,"Could not close temporary draft\n"); if(lseek(drffd, 0L, 0) < 0) fprintf(stderr,"Lseek failed on draft %s\n", drffile); if(chmod(drffile, 0400) < 0) fprintf(stderr,"Could not protect draft %s\n", drffile); /* Fire-up the editor */ goto edit; } /* "File include" option */ if (prefix ("file include", bigbuf)) { printf ("File: "); gather (bigbuf, BBSIZE - 1); if (bigbuf[0] == '\0') continue; infile = open (bigbuf, 0); if (inclfile[0] != '\0') { /* and include file */ inclfile[0] = '\0'; } if (infile < 0) { fprintf(stderr,"can't open: '%s'\n", bigbuf); continue; } dropen (DREND); body = TRUE; while ((i = read (infile, bigbuf, BBSIZE - 1)) > 0) write (drffd, bigbuf, i); (void) close (infile); printf (" ...included\n"); continue; } /* "Program run" option */ if (prefix ("program run", bigbuf)) { printf ("Program: "); fflush (stdout); if (gets (tempbuf) == NULL) continue; drclose (); /* ignore signals intended for subprocess */ old1 = signal (SIGHUP, SIG_IGN); old2 = signal (SIGINT, SIG_IGN); old3 = signal (SIGQUIT, SIG_IGN); if (fork () == 0) { signal (SIGHUP, old1); signal (SIGINT, orig); signal (SIGQUIT, old3); execlp ("sh", "send-shell", "-c", tempbuf, (char *)0); fprintf(stderr,"can't execute\n"); s_exit (-1); } wait (&stat); signal (SIGHUP, old1); /* restore signals */ signal (SIGINT, old2); signal (SIGQUIT, old3); dropen (DREND); continue; } /* "quit" option */ if (prefix ("quit", bigbuf) || prefix ("bye", bigbuf)) { byebye: if ( body && !nsent) { printf ("Without sending draft"); if (confirm ()) return; else continue; } drclose (); return; } /* "review message" option */ if (prefix ("review message", bigbuf)) { dropen( DRBEGIN ); /* Put header info into temp. draft */ if((nfd = open(tmpdrffile, 2, 0600)) < 0) { fprintf(stderr,"Can't open temporary file\n"); s_exit(-1); } if(lseek(nfd, 0L, 0) < 0) { fprintf(stderr,"Lseek failed on temporary file\n"); s_exit(-1); } if(write(nfd, fromname, strlen( fromname )) < 0) { fprintf(stderr,"Cannot write temporary file\n"); s_exit(-1); } write(nfd, from, strlen( from )); write(nfd, "\n", 1); if(to[0] != '\0') { write(nfd, toname, strlen( toname )); write(nfd, to, strlen( to )); write(nfd, "\n", 1); } else if(bccflag) { write(nfd, toname, strlen( toname )); write(nfd, "list: ;", 7); write(nfd, "\n", 1); } if(cc[0] != '\0') { write(nfd, ccname, strlen( ccname )); write(nfd, cc, strlen( cc )); write(nfd, "\n", 1); } if(bccflag) { write(nfd, bccname, strlen( bccname )); write(nfd, bcc, strlen( bcc )); write(nfd, "\n", 1); } if(subject[0] != '\0') { write(nfd, subjname, strlen( subjname )); write(nfd, subject, strlen( subject )); write(nfd, "\n", 1); } if(lseek(drffd, 0L, 0) < 0) fprintf(stderr,"Lseek failed on draft %s\n", drffile); /* Write the body into the temp. file */ while((i = read(drffd, bigbuf, BBSIZE - 1)) > 0) write(nfd, bigbuf, i); drclose(); if(pflag) { (void) close( nfd ); /* ignore signals intended for subprocess */ old1 = signal (SIGHUP, SIG_IGN); old2 = signal (SIGINT, SIG_IGN); old3 = signal (SIGQUIT, SIG_IGN); /* Start-up "more" program on the temp. draft */ if (fork () == 0) { signal (SIGHUP, old1); signal (SIGINT, orig); signal (SIGQUIT, old3); execlp ("more", "-c", tmpdrffile, 0); fprintf(stderr,"can't execute\n"); s_exit (-1); } wait (&stat); signal (SIGHUP, old1); /* restore signals */ signal (SIGINT, old2); signal (SIGQUIT, old3); } else /* If the paging option is off, just show it */ { if( lseek(nfd, 0L, 0) < 0 ) fprintf(stderr, "Lseek failed on temporary draft.\n"); while((i = read(nfd, bigbuf, BBSIZE - 1)) > 0) write( 1, bigbuf, i); (void) close( nfd ); } if(truncate(tmpdrffile, 0) < 0) fprintf(stderr,"truncate failed on temp. draft\n"); fflush( stdout ); continue; } /* "Check spelling" option */ if (prefix ("check spelling", bigbuf)) { drclose (); old1 = signal (SIGHUP, SIG_IGN); /* ignore signals intended for cheker */ old2 = signal (SIGINT, SIG_IGN); old3 = signal (SIGQUIT, SIG_IGN); if (fork () == 0) { signal (SIGHUP, old1); signal (SIGINT, orig); signal (SIGQUIT, old3); execlp (checker, checker, drffile, (char *)0); fprintf(stderr,"can't execute\n"); s_exit (-1); } wait (&stat); signal (SIGHUP, old1); /* restore signals */ signal (SIGINT, old2); signal (SIGQUIT, old3); dropen (DREND); continue; } /* "Post message" option */ if (prefix ("post message", bigbuf) || prefix ("send message", bigbuf)) { if (lastsend && lastsend == body) { printf ("Without changing anything"); if (!confirm ()) break; } signal (SIGINT, onint2); if( qflag == 1 ){ printf(" Do you want a file copy of this message ? "); fflush(stdout); fgets(tempbuf, sizeof(tempbuf), stdin ); if( tempbuf[0] == 'y' || tempbuf[0] == 'Y' || tempbuf[0] == '\n') cflag = 1; else cflag = 0; } post (); if ( qflag == 1 ) cflag = 0; /* *** auto-exit, upon successfull send, since draft is saved *** */ goto byebye; } /* help */ if (prefix ("?", bigbuf)) { printf ("bcc\n"); printf ("bye\n"); printf ("check spelling\n"); printf ("edit body\n"); printf ("file include\n"); printf ("program run\n"); printf ("quit\n"); printf ("review message\n"); printf ("send message\n"); printf ("set [option] [option value]\n"); continue; } printf (" unknown command (type ? for help)\n"); } /* end of loop */ }
sequence_analyzer default_pos_analyzer() { sequence_analyzer analyzer; auto word_feats = [](const std::string& word, uint64_t t, sequence_analyzer::collector& coll) { auto norm = utf::foldcase(word); for (uint64_t i = 1; i <= 4; i++) { auto len = std::to_string(i); coll.add("w[t]_suffix_" + len + "=" + suffix(norm, i), 1); coll.add("w[t]_prefix_" + len + "=" + prefix(norm, i), 1); } coll.add("w[t]=" + norm, 1); // additional binary word features if (std::any_of(word.begin(), word.end(), [](char c) { return std::isdigit(c); })) { coll.add("w[t]_has_digit=1", 1); } if (std::find(word.begin(), word.end(), '-') != word.end()) coll.add("w[t]_has_hyphen=1", 1); if (std::any_of(word.begin(), word.end(), [](char c) { return std::isupper(c); })) { coll.add("w[t]_has_upper=1", 1); if (t != 0) { coll.add("w[t]_has_upper_and_not_sentence_start=1", 1); } } if (std::all_of(word.begin(), word.end(), [](char c) { return std::isupper(c); })) { coll.add("w[t]_all_upper=1", 1); } }; // current word features analyzer.add_observation_function( [=](const sequence& seq, uint64_t t, sequence_analyzer::collector& coll) { std::string word = seq[t].symbol(); word_feats(word, t, coll); }); // previous word features analyzer.add_observation_function( [](const sequence& seq, uint64_t t, sequence_analyzer::collector& coll) { std::string word = seq[t].symbol(); if (t > 0) { auto prevword = seq[t - 1].symbol(); coll.add("w[t-1]=" + utf::foldcase(prevword), 1); if (t > 1) { auto prev2word = seq[t - 2].symbol(); coll.add("w[t-2]=" + utf::foldcase(prev2word), 1); } else { coll.add("w[t-2]=<s>", 1); } } else { coll.add("w[t-1]=<s>", 1); coll.add("w[t-2]=<s1>", 1); } }); // next word features analyzer.add_observation_function( [](const sequence& seq, uint64_t t, sequence_analyzer::collector& coll) { if (t + 1 < seq.size()) { auto nextword = seq[t + 1].symbol(); coll.add("w[t+1]=" + utf::foldcase(nextword), 1); if (t + 2 < seq.size()) { auto next2word = seq[t + 2].symbol(); coll.add("w[t+2]=" + utf::foldcase(next2word), 1); } else { coll.add("w[t+2]=</s>", 1); } } else { coll.add("w[t+1]=</s>", 1); coll.add("w[t+2]=</s1>", 1); } }); // bias term analyzer.add_observation_function( [](const sequence&, uint64_t, sequence_analyzer::collector& coll) { coll.add("bias", 1); }); return analyzer; }
/* * Initialization function for an "X11" module to Angband */ errr init_x11(int argc, char **argv) { int i; cptr dpy_name = ""; int num_term = 1; #ifdef USE_GRAPHICS cptr bitmap_file = ""; char filename[1024]; int pict_wid = 0; int pict_hgt = 0; char *TmpData; #endif /* USE_GRAPHICS */ /* Parse args */ for (i = 1; i < argc; i++) { if (prefix(argv[i], "-d")) { dpy_name = &argv[i][2]; continue; } #ifdef USE_GRAPHICS if (prefix(argv[i], "-s")) { smoothRescaling = FALSE; continue; } if (prefix(argv[i], "-o")) { arg_graphics = GRAPHICS_ORIGINAL; continue; } if (prefix(argv[i], "-a")) { arg_graphics = GRAPHICS_ADAM_BOLT; continue; } if (prefix(argv[i], "-g")) { smoothRescaling = FALSE; arg_graphics = GRAPHICS_DAVID_GERVAIS; continue; } if (prefix(argv[i], "-b")) { use_bigtile = TRUE; continue; } #endif /* USE_GRAPHICS */ if (prefix(argv[i], "-n")) { num_term = atoi(&argv[i][2]); if (num_term > MAX_TERM_DATA) num_term = MAX_TERM_DATA; else if (num_term < 1) num_term = 1; continue; } plog_fmt("Ignoring option: %s", argv[i]); } /* Init the Metadpy if possible */ if (Metadpy_init_name(dpy_name)) return (-1); /* Prepare cursor color */ MAKE(xor, infoclr); Infoclr_set(xor); Infoclr_init_ppn(Metadpy->fg, Metadpy->bg, "xor", 0); /* Prepare normal colors */ for (i = 0; i < 256; ++i) { Pixell pixel; MAKE(clr[i], infoclr); Infoclr_set(clr[i]); /* Acquire Angband colors */ color_table[i][0] = angband_color_table[i][0]; color_table[i][1] = angband_color_table[i][1]; color_table[i][2] = angband_color_table[i][2]; color_table[i][3] = angband_color_table[i][3]; /* Default to monochrome */ pixel = ((i == 0) ? Metadpy->bg : Metadpy->fg); /* Handle color */ if (Metadpy->color) { /* Create pixel */ pixel = create_pixel(Metadpy->dpy, color_table[i][1], color_table[i][2], color_table[i][3]); } /* Initialize the color */ Infoclr_init_ppn(pixel, Metadpy->bg, "cpy", 0); } /* Initialize the windows */ for (i = 0; i < num_term; i++) { term_data *td = &data[i]; /* Initialize the term_data */ term_data_init(td, i); /* Save global entry */ angband_term[i] = Term; } /* Raise the "Angband" window */ Infowin_set(data[0].win); Infowin_raise(); /* Activate the "Angband" window screen */ Term_activate(&data[0].t); #ifdef USE_GRAPHICS /* Try graphics */ switch (arg_graphics) { case GRAPHICS_ADAM_BOLT: /* Use tile graphics of Adam Bolt */ bitmap_file = "16x16.bmp"; /* Try the "16x16.bmp" file */ path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, format("graf/%s", bitmap_file)); /* Use the "16x16.bmp" file if it exists */ if (0 == fd_close(fd_open(filename, O_RDONLY))) { /* Use graphics */ use_graphics = TRUE; use_transparency = TRUE; pict_wid = pict_hgt = 16; ANGBAND_GRAF = "new"; break; } /* Fall through */ case GRAPHICS_ORIGINAL: /* Use original tile graphics */ bitmap_file = "8x8.bmp"; /* Try the "8x8.bmp" file */ path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, format("graf/%s", bitmap_file)); /* Use the "8x8.bmp" file if it exists */ if (0 == fd_close(fd_open(filename, O_RDONLY))) { /* Use graphics */ use_graphics = TRUE; pict_wid = pict_hgt = 8; ANGBAND_GRAF = "old"; break; } break; case GRAPHICS_DAVID_GERVAIS: /* Use tile graphics of David Gervais */ bitmap_file = "32x32.bmp"; /* Use graphics */ use_graphics = TRUE; use_transparency = TRUE; pict_wid = pict_hgt = 32; ANGBAND_GRAF = "david"; break; } /* Load graphics */ if (use_graphics) { Display *dpy = Metadpy->dpy; XImage *tiles_raw; /* Initialize */ for (i = 0; i < num_term; i++) { term_data *td = &data[i]; td->tiles = NULL; } path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, format("graf/%s", bitmap_file)); /* Load the graphical tiles */ tiles_raw = ReadBMP(dpy, filename); if (tiles_raw) { /* Initialize the windows */ for (i = 0; i < num_term; i++) { int j; bool same = FALSE; term_data *td = &data[i]; term_data *o_td = NULL; term *t = &td->t; /* Graphics hook */ t->pict_hook = Term_pict_x11; /* Use graphics sometimes */ t->higher_pict = TRUE; /* Look for another term with same font size */ for (j = 0; j < i; j++) { o_td = &data[j]; if ((td->fnt->twid == o_td->fnt->twid) && (td->fnt->hgt == o_td->fnt->hgt)) { same = TRUE; break; } } if (!same) { /* Resize tiles */ td->tiles = ResizeImage(dpy, tiles_raw, pict_wid, pict_hgt, td->fnt->twid, td->fnt->hgt); } else { /* Use same graphics */ td->tiles = o_td->tiles; } } /* Free tiles_raw */ FREE(tiles_raw); } /* Initialize the transparency masks */ for (i = 0; i < num_term; i++) { term_data *td = &data[i]; int ii, jj; int depth = DefaultDepth(dpy, DefaultScreen(dpy)); Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy)); int total; /* Determine total bytes needed for image */ ii = 1; jj = (depth - 1) >> 2; while (jj >>= 1) ii <<= 1; total = td->fnt->twid * td->fnt->hgt * ii; TmpData = (char *)malloc(total); td->TmpImage = XCreateImage(dpy,visual,depth, ZPixmap, 0, TmpData, td->fnt->twid, td->fnt->hgt, 32, 0); } } #endif /* USE_GRAPHICS */ /* Success */ return (0); }
/* * Initialization function for an X Athena Widget module to Angband * * We should accept "-d<dpy>" requests in the "argv" array. XXX XXX XXX */ errr init_xaw(int argc, char **argv) { int i; Widget topLevel; Display *dpy; cptr dpy_name = ""; #ifdef USE_GRAPHICS cptr bitmap_file = ""; char filename[1024]; int pict_wid = 0; int pict_hgt = 0; char *TmpData; #endif /* USE_GRAPHICS */ /* Parse args */ for (i = 1; i < argc; i++) { if (prefix(argv[i], "-d")) { dpy_name = &argv[i][2]; continue; } #ifdef USE_GRAPHICS if (prefix(argv[i], "-s")) { smoothRescaling = FALSE; continue; } if (prefix(argv[i], "-o")) { arg_graphics = GRAPHICS_ORIGINAL; continue; } if (prefix(argv[i], "-a")) { arg_graphics = GRAPHICS_ADAM_BOLT; continue; } if (prefix(argv[i], "-g")) { smoothRescaling = FALSE; arg_graphics = GRAPHICS_DAVID_GERVAIS; continue; } if (prefix(argv[i], "-b")) { use_bigtile = TRUE; continue; } #endif /* USE_GRAPHICS */ if (prefix(argv[i], "-n")) { num_term = atoi(&argv[i][2]); if (num_term > MAX_TERM_DATA) num_term = MAX_TERM_DATA; else if (num_term < 1) num_term = 1; continue; } plog_fmt("Ignoring option: %s", argv[i]); } /* Attempt to open the local display */ dpy = XOpenDisplay(dpy_name); /* Failure -- assume no X11 available */ if (!dpy) return (-1); /* Close the local display */ XCloseDisplay(dpy); #ifdef USE_XAW_LANG /* Support locale processing */ XtSetLanguageProc(NULL, NULL, NULL); #endif /* USE_XAW_LANG */ /* Initialize the toolkit */ topLevel = XtAppInitialize(&appcon, "Angband", NULL, 0, &argc, argv, fallback, NULL, 0); /* Initialize the windows */ for (i = 0; i < num_term; i++) { term_data *td = &data[i]; term_data_init(td, topLevel, 1024, termNames[i], (i == 0) ? specialArgs : defaultArgs, TERM_FALLBACKS, i); angband_term[i] = Term; } /* Activate the "Angband" window screen */ Term_activate(&data[0].t); /* Raise the "Angband" window */ term_raise(&data[0]); #ifdef USE_GRAPHICS /* Try graphics */ switch (arg_graphics) { case GRAPHICS_ADAM_BOLT: /* Use tile graphics of Adam Bolt */ bitmap_file = "16x16.bmp"; /* Try the "16x16.bmp" file */ path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, format("graf/%s", bitmap_file)); /* Use the "16x16.bmp" file if it exists */ if (0 == fd_close(fd_open(filename, O_RDONLY))) { /* Use graphics */ use_graphics = GRAPHICS_ADAM_BOLT; use_transparency = TRUE; pict_wid = pict_hgt = 16; ANGBAND_GRAF = "new"; break; } /* Fall through */ case GRAPHICS_ORIGINAL: /* Use original tile graphics */ bitmap_file = "8x8.bmp"; /* Try the "8x8.bmp" file */ path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, format("graf/%s", bitmap_file)); /* Use the "8x8.bmp" file if it exists */ if (0 == fd_close(fd_open(filename, O_RDONLY))) { /* Use graphics */ use_graphics = GRAPHICS_ORIGINAL; pict_wid = pict_hgt = 8; ANGBAND_GRAF = "old"; break; } break; case GRAPHICS_DAVID_GERVAIS: /* Use tile graphics of David Gervais */ bitmap_file = "32x32.bmp"; /* Use graphics */ use_graphics = GRAPHICS_DAVID_GERVAIS; use_transparency = TRUE; pict_wid = pict_hgt = 32; ANGBAND_GRAF = "david"; break; } /* Load graphics */ if (use_graphics) { /* Hack -- Get the Display */ term_data *td = &data[0]; Widget widget = (Widget)(td->widget); Display *dpy = XtDisplay(widget); XImage *tiles_raw; for (i = 0; i < num_term; i++) { term_data *td = &data[i]; td->widget->angband.tiles = NULL; } path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, format("graf/%s", bitmap_file)); /* Load the graphical tiles */ tiles_raw = ReadBMP(dpy, filename); if (tiles_raw) { /* Initialize the windows */ for (i = 0; i < num_term; i++) { int j; bool same = FALSE; term_data *td = &data[i]; term_data *o_td = NULL; term *t = &td->t; t->pict_hook = Term_pict_xaw; t->higher_pict = TRUE; /* Look for another term with same font size */ for (j = 0; j < i; j++) { o_td = &data[j]; if ((td->widget->angband.tilewidth == o_td->widget->angband.tilewidth) && (td->widget->angband.fontheight == o_td->widget->angband.fontheight)) { same = TRUE; break; } } if (!same) { /* Resize tiles */ td->widget->angband.tiles = ResizeImage(dpy, tiles_raw, pict_wid, pict_hgt, td->widget->angband.tilewidth, td->widget->angband.fontheight); } else { /* Use same graphics */ td->widget->angband.tiles = o_td->widget->angband.tiles; } } /* Free tiles_raw */ FREE(tiles_raw); } /* Initialize the transparency temp storage */ for (i = 0; i < num_term; i++) { term_data *td = &data[i]; int ii, jj; int depth = DefaultDepth(dpy, DefaultScreen(dpy)); Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy)); int total; /* Determine total bytes needed for image */ ii = 1; jj = (depth - 1) >> 2; while (jj >>= 1) ii <<= 1; total = td->widget->angband.tilewidth * td->widget->angband.fontheight * ii; TmpData = (char *)malloc(total); td->widget->angband.TmpImage = XCreateImage(dpy, visual,depth, ZPixmap, 0, TmpData, td->widget->angband.tilewidth, td->widget->angband.fontheight, 8, 0); } } #endif /* USE_GRAPHICS */ /* Success */ return (0); }
void M2kGearAnimation::registerChannels(Bus* bus) { GearSequenceAnimation::registerChannels(bus); b_Absorber02Angle = bus->registerLocalDataChannel<double>(prefix() + ".Absorber02", 0.0); b_Absorber03Angle = bus->registerLocalDataChannel<double>(prefix() + ".Absorber03", 0.0); b_Compression = bus->registerLocalDataChannel<double>(prefix() + ".Compression", 0.0); }
void GearSequenceAnimation::registerChannels(Bus* bus) { if (m_RetractSequence.valid()) m_RetractSequence->registerChannels(bus); if (m_CompressionSequence.valid()) m_CompressionSequence->registerChannels(bus); b_TireRotation = bus->registerLocalDataChannel<double>(prefix() + ".TireRotation", 0.0); b_SteeringAngle = bus->registerLocalDataChannel<double>(prefix() + ".SteeringAngle", 0.0); }
void EOTHeader::updateEOTSize(size_t fontDataSize) { prefix()->eotSize = m_buffer.size() + fontDataSize; }
ProgramRunner::ProgramRunner( const BSONObj &args ) { verify( !args.isEmpty() ); string program( args.firstElement().valuestrsafe() ); verify( !program.empty() ); boost::filesystem::path programPath = findProgram(program); string prefix( "mongod-" ); bool isMongodProgram = string("mongod") == program || program.compare( 0, prefix.size(), prefix ) == 0; prefix = "mongos-"; bool isMongosProgram = string("mongos") == program || program.compare( 0, prefix.size(), prefix ) == 0; #if 0 if (isMongosProgram == "mongos") { _argv.push_back("valgrind"); _argv.push_back("--log-file=/tmp/mongos-%p.valgrind"); _argv.push_back("--leak-check=yes"); _argv.push_back("--suppressions=valgrind.suppressions"); //_argv.push_back("--error-exitcode=1"); _argv.push_back("--"); } #endif _argv.push_back( programPath.string() ); _port = -1; BSONObjIterator j( args ); j.next(); // skip program name (handled above) while(j.more()) { BSONElement e = j.next(); string str; if ( e.isNumber() ) { stringstream ss; ss << e.number(); str = ss.str(); } else { verify( e.type() == mongo::String ); str = e.valuestr(); } if ( str == "--port" ) _port = -2; else if ( _port == -2 ) _port = strtol( str.c_str(), 0, 10 ); _argv.push_back(str); } if ( ! isMongodProgram && ! isMongosProgram && program != "mongobridge" ) _port = 0; else { if ( _port <= 0 ) log() << "error: a port number is expected when running " << program << " from the shell" << endl; verify( _port > 0 ); } if ( _port > 0 ) { bool haveDbForPort = registry.isPortRegistered( _port ); if ( haveDbForPort ) { log() << "already have db for port: " << _port << endl; verify( !haveDbForPort ); } } }
int main(int argc, char** argv) { if (argc != 3) { fprintf(stderr, "exef2paz v1.22 by asmodean\n\n"); fprintf(stderr, "usage: %s <input.paz> <game index>\n\n", argv[0]); fprintf(stderr, "\t 0 = ef - the latter tale\n", argv[0]); fprintf(stderr, "\t 1 = eden*\n", argv[0]); return -1; } string in_filename(argv[1]); unsigned long game_index = atol(argv[2]); if (game_index >= GAME_COUNT) { fprintf(stderr, "Unknown game index: %d\n", game_index); return -1; } string prefix(as::stringtol(as::get_file_prefix(in_filename, true))); game_info_t game_info = GAME_INFO[game_index]; key_info_t keys; for (unsigned long i = 0; !game_info.keys[i].prefix.empty(); i++) { if (prefix == game_info.keys[i].prefix) { keys = game_info.keys[i]; } } if (keys.prefix.empty()) { fprintf(stderr, "%s: don't know encryption key.\n", in_filename.c_str()); return -1; } // Hard to recognize individual sound files because they lack extension bool is_audio = prefix == "bgm" || prefix == "se" || prefix == "voice" || prefix == "PMvoice"; bool is_mov = prefix == "mov"; int fd = as::open_or_die(in_filename, O_RDONLY | O_BINARY); PAZHDR hdr; read(fd, &hdr, sizeof(hdr)); char simple_key = hdr.toc_len >> 24; lseek(fd, 0, SEEK_SET); read_unobfuscate(fd, simple_key, &hdr, sizeof(hdr)); Blowfish bf; unsigned char* toc_buff = new unsigned char[hdr.toc_len]; read_unobfuscate(fd, simple_key, toc_buff, hdr.toc_len); bf.Set_Key(keys.toc_key, sizeof(keys.toc_key)); bf.Decrypt(toc_buff, hdr.toc_len); PAZHDR2* hdr2 = (PAZHDR2*) toc_buff; unsigned char* p = (unsigned char*) (hdr2 + 1); unsigned char* mov_seed = NULL; if (is_mov) { mov_seed = p; p += 256; } for (unsigned long i = 0; i < hdr2->entry_count; i++) { string filename = (char*) p; p += filename.length() + 1; PAZENTRY* entry = (PAZENTRY*) p; p += sizeof(*entry); unsigned long len = entry->padded_length; unsigned char* buff = new unsigned char[len]; lseek(fd, entry->offset, SEEK_SET); read_unobfuscate(fd, simple_key, buff, len); string crud; if (filename.find(".png") != string::npos) { crud = game_info.crud.png; } else if (filename.find(".ogg") != string::npos || is_audio) { crud = game_info.crud.ogg; } else if (filename.find(".sc") != string::npos) { crud = game_info.crud.sc; } else if (filename.find(".avi") != string::npos) { crud = game_info.crud.avi; } string seed = as::stringtol(filename) + as::stringf(" %08X ", entry->length) + crud; if (is_mov) { decrypt_mov(mov_seed, seed, buff, len); } else { bf.Set_Key(keys.dat_key, sizeof(keys.dat_key)); bf.Decrypt(buff, len); if (!crud.empty()) { unobfuscate3(seed, buff, len); } } as::make_path(filename); as::write_file(filename, buff, entry->length); delete [] buff; } delete [] toc_buff; close(fd); return 0; }
RocksEngine::RocksEngine(const std::string& path, bool durable) : _path(path), _durable(durable), _maxPrefix(0) { { // create block cache uint64_t cacheSizeGB = rocksGlobalOptions.cacheSizeGB; if (cacheSizeGB == 0) { ProcessInfo pi; unsigned long long memSizeMB = pi.getMemSizeMB(); if (memSizeMB > 0) { double cacheMB = memSizeMB / 2; cacheSizeGB = static_cast<uint64_t>(cacheMB / 1024); } if (cacheSizeGB < 1) { cacheSizeGB = 1; } } _block_cache = rocksdb::NewLRUCache(cacheSizeGB * 1024 * 1024 * 1024LL, 6); } _maxWriteMBPerSec = rocksGlobalOptions.maxWriteMBPerSec; _rateLimiter.reset( rocksdb::NewGenericRateLimiter(static_cast<int64_t>(_maxWriteMBPerSec) * 1024 * 1024)); // open DB rocksdb::DB* db; auto s = rocksdb::DB::Open(_options(), path, &db); invariantRocksOK(s); _db.reset(db); _counterManager.reset( new RocksCounterManager(_db.get(), rocksGlobalOptions.crashSafeCounters)); _compactionScheduler.reset(new RocksCompactionScheduler(_db.get())); // open iterator boost::scoped_ptr<rocksdb::Iterator> iter(_db->NewIterator(rocksdb::ReadOptions())); // find maxPrefix iter->SeekToLast(); if (iter->Valid()) { // otherwise the DB is empty, so we just keep it at 0 bool ok = extractPrefix(iter->key(), &_maxPrefix); // this is DB corruption here invariant(ok); } // load ident to prefix map. also update _maxPrefix if there's any prefix bigger than // current _maxPrefix { boost::lock_guard<boost::mutex> lk(_identPrefixMapMutex); for (iter->Seek(kMetadataPrefix); iter->Valid() && iter->key().starts_with(kMetadataPrefix); iter->Next()) { invariantRocksOK(iter->status()); rocksdb::Slice ident(iter->key()); ident.remove_prefix(kMetadataPrefix.size()); // this could throw DBException, which then means DB corruption. We just let it fly // to the caller BSONObj identConfig(iter->value().data()); BSONElement element = identConfig.getField("prefix"); if (element.eoo() || !element.isNumber()) { log() << "Mongo metadata in RocksDB database is corrupted."; invariant(false); } uint32_t identPrefix = static_cast<uint32_t>(element.numberInt()); _identPrefixMap[StringData(ident.data(), ident.size())] = identPrefix; _maxPrefix = std::max(_maxPrefix, identPrefix); } } // just to be extra sure. we need this if last collection is oplog -- in that case we // reserve prefix+1 for oplog key tracker ++_maxPrefix; // load dropped prefixes { rocksdb::WriteBatch wb; // we will use this iter to check if prefixes are still alive boost::scoped_ptr<rocksdb::Iterator> prefixIter( _db->NewIterator(rocksdb::ReadOptions())); for (iter->Seek(kDroppedPrefix); iter->Valid() && iter->key().starts_with(kDroppedPrefix); iter->Next()) { invariantRocksOK(iter->status()); rocksdb::Slice prefix(iter->key()); prefix.remove_prefix(kDroppedPrefix.size()); prefixIter->Seek(prefix); invariantRocksOK(iter->status()); if (prefixIter->Valid() && prefixIter->key().starts_with(prefix)) { // prefix is still alive, let's instruct the compaction filter to clear it up uint32_t int_prefix; bool ok = extractPrefix(prefix, &int_prefix); invariant(ok); { boost::lock_guard<boost::mutex> lk(_droppedPrefixesMutex); _droppedPrefixes.insert(int_prefix); } } else { // prefix is no longer alive. let's remove the prefix from our dropped prefixes // list wb.Delete(iter->key()); } } if (wb.Count() > 0) { auto s = _db->Write(rocksdb::WriteOptions(), &wb); invariantRocksOK(s); } } }
void prefix(node* a){ cout << a->value->Char; if (a->left != NULL)prefix(a->left); if (a->right != NULL)prefix(a->right); }
gettbl() { int icol, ch; cstore=cspace= chspace(); textflg=0; for (nlin=nslin=0; gets1(cstore); nlin++) { stynum[nlin]=nslin; if (prefix(".TE", cstore)) { leftover=0; break; } if (prefix(".TC", cstore) || prefix(".T&", cstore)) { readspec(); nslin++; } if (nlin>=MAXLIN) { leftover=cstore; break; } fullbot[nlin]=0; if (cstore[0] == '.' && !isdigit(cstore[1])) { instead[nlin] = cstore; while (*cstore++); continue; } else instead[nlin] = 0; if (nodata(nlin)) { if (ch = oneh(nlin)) fullbot[nlin]= ch; nlin++; nslin++; instead[nlin]=fullbot[nlin]=0; } table[nlin] = alocv((ncol+2)*sizeof(table[0][0])); if (cstore[1]==0) switch(cstore[0]) { case '_': fullbot[nlin]= '-'; continue; case '=': fullbot[nlin]= '='; continue; } stynum[nlin] = nslin; nslin = min(nslin+1, nclin-1); for (icol = 0; icol <ncol; icol++) { table[nlin][icol].col = cstore; table[nlin][icol].rcol=0; ch=1; if (match(cstore, "T{")) /* text follows */ table[nlin][icol].col = gettext(cstore, nlin, icol, font[stynum[nlin]][icol], csize[stynum[nlin]][icol]); else { for(; (ch= *cstore) != '\0' && ch != tab; cstore++) ; *cstore++ = '\0'; switch(ctype(nlin,icol)) /* numerical or alpha, subcol */ { case 'n': table[nlin][icol].rcol = maknew(table[nlin][icol].col); break; case 'a': table[nlin][icol].rcol = table[nlin][icol].col; table[nlin][icol].col = ""; break; } } while (ctype(nlin,icol+1)== 's') /* spanning */ table[nlin][++icol].col = ""; if (ch == '\0') break; } while (++icol <ncol+2) { table[nlin][icol].col = ""; table [nlin][icol].rcol=0; } while (*cstore != '\0') cstore++; if (cstore-cspace > MAXCHS) cstore = cspace = chspace(); } last = cstore; permute(); if (textflg) untext(); return; }
int sys_fsetxattr (int filedes, const char *uname, const void *value, size_t size, int flags) { const char *name = prefix(uname); #if defined(HAVE_FSETXATTR) #ifndef XATTR_ADD_OPT return fsetxattr(filedes, name, value, size, flags); #else int options = 0; return fsetxattr(filedes, name, value, size, 0, options); #endif #elif defined(HAVE_FSETEA) return fsetea(filedes, name, value, size, flags); #elif defined(HAVE_EXTATTR_SET_FD) char *s; int retval = 0; int attrnamespace = (strncmp(name, "system", 6) == 0) ? EXTATTR_NAMESPACE_SYSTEM : EXTATTR_NAMESPACE_USER; const char *attrname = ((s=strchr(name, '.')) == NULL) ? name : s + 1; if (flags) { /* Check attribute existence */ retval = extattr_get_fd(filedes, attrnamespace, attrname, NULL, 0); if (retval < 0) { /* REPLACE attribute, that doesn't exist */ if (flags & XATTR_REPLACE && errno == ENOATTR) { errno = ENOATTR; return -1; } /* Ignore other errors */ } else { if (flags & XATTR_CREATE) { errno = EEXIST; return -1; } } } retval = extattr_set_fd(filedes, attrnamespace, attrname, value, size); return (retval < 0) ? -1 : 0; #elif defined(HAVE_ATTR_SETF) int myflags = 0; char *attrname = strchr(name,'.') + 1; if (strncmp(name, "system", 6) == 0) myflags |= ATTR_ROOT; if (flags & XATTR_CREATE) myflags |= ATTR_CREATE; if (flags & XATTR_REPLACE) myflags |= ATTR_REPLACE; return attr_setf(filedes, attrname, (const char *)value, size, myflags); #elif defined(HAVE_ATTROPEN) int ret = -1; int myflags = O_RDWR | O_XATTR; int attrfd; if (flags & XATTR_CREATE) myflags |= O_EXCL; if (!(flags & XATTR_REPLACE)) myflags |= O_CREAT; attrfd = solaris_openat(filedes, name, myflags, (mode_t) SOLARIS_ATTRMODE); if (attrfd >= 0) { ret = solaris_write_xattr(attrfd, value, size); close(attrfd); } return ret; #else errno = ENOSYS; return -1; #endif }
void IrcEvent::toVariantMap(QVariantMap& map) const { NetworkEvent::toVariantMap(map); map["prefix"] = prefix(); map["params"] = params(); }
int main(int argc, char ** argv) { setbuf(stdout, NULL); time_t start = time(NULL); printf("MiniMac - Imputation into phased haplotypes\n" "(c) 2011 Goncalo Abecasis\n"); #ifdef __VERSION__ printf("VERSION 5.0\n"); #else printf("UNDOCUMENTED RELEASE\n"); #endif int rounds = 5, states = 200, cpus = 0; bool em = false, gzip = false, phased = false; String referenceHaplotypes, referenceSnps; String haplotypes, snps; String prefix("minimac"); String firstMarker, lastMarker; String recombinationRates, errorRates; BEGIN_LONG_PARAMETERS(longParameters) LONG_PARAMETER_GROUP("Reference Haplotypes") LONG_STRINGPARAMETER("refHaps", &referenceHaplotypes) LONG_STRINGPARAMETER("refSnps", &referenceSnps) LONG_PARAMETER_GROUP("Target Haplotypes") LONG_STRINGPARAMETER("haps", &haplotypes) LONG_STRINGPARAMETER("snps", &snps) LONG_PARAMETER_GROUP("Starting Parameters") LONG_STRINGPARAMETER("rec", &recombinationRates) LONG_STRINGPARAMETER("erate", &errorRates) LONG_PARAMETER_GROUP("Parameter Fitting") LONG_INTPARAMETER("rounds", &rounds) LONG_INTPARAMETER("states", &states) LONG_PARAMETER("em", &em) LONG_PARAMETER_GROUP("Output Files") LONG_STRINGPARAMETER("prefix", &prefix) LONG_PARAMETER("phased", &phased) LONG_PARAMETER("gzip", &gzip) // LONG_PARAMETER_GROUP("Clipping Window") // LONG_STRINGPARAMETER("start", &firstMarker) // LONG_STRINGPARAMETER("stop", &lastMarker) #ifdef _OPENMP LONG_PARAMETER_GROUP("Multi-Threading") LONG_INTPARAMETER("cpus", &cpus) #endif END_LONG_PARAMETERS(); ParameterList pl; pl.Add(new LongParameters("Command Line Options", longParameters)); pl.Read(argc, argv); pl.Status(); #ifdef _OPENMP if (cpus > 0) omp_set_num_threads(cpus); #endif // Read marker list printf("Reading Reference Marker List ...\n"); StringArray refMarkerList; refMarkerList.Read(referenceSnps); // Index markers StringIntHash referenceHash; for (int i = 0; i < refMarkerList.Length(); i++) referenceHash.Add(refMarkerList[i].Trim(), i); printf(" %d Markers in Reference Haplotypes...\n\n", refMarkerList.Length()); // Load reference haplotypes printf("Loading reference haplotypes ...\n"); HaplotypeSet reference; reference.markerCount = refMarkerList.Length(); reference.LoadHaplotypes(referenceHaplotypes); printf(" %d Reference Haplotypes Loaded ...\n\n", reference.count); // Read framework marker list printf("Reading Framework Marker List ...\n"); StringArray markerList; markerList.Read(snps); ClipReference(reference, refMarkerList, referenceHash, markerList, firstMarker, lastMarker); // Crossref Marker Names to Reference Panel Positions IntArray markerIndex; markerIndex.Dimension(markerList.Length()); int matches = 0; for (int i = 0; i < markerList.Length(); i++) { markerIndex[i] = referenceHash.Integer(markerList[i].Trim()); if (markerIndex[i] >= 0) matches++; } printf(" %d Markers in Framework Haplotypes Overlap Reference ...\n", matches); if (matches == 0) error("No markers overlap between target and reference\n" "Please check correct reference is being used and markers are named consistently"); printf(" %d Other Markers in Framework Haplotypes Discarded ...\n\n", markerList.Length() - matches); // Check for flips in reference vs. target haplotypes int flips = 0; int previous = -1; for (int i = 0; i < markerIndex.Length(); i++) if (markerIndex[i] >= 0) if (markerIndex[i] < previous) { if (flips++ < 10) printf(" -> Marker %s precedes %s in reference, but follows it in target\n", (const char *) refMarkerList[previous], (const char *) markerList[i]); previous = markerIndex[i]; } if (flips > 10) printf(" -> %d Additional Marker Order Changes Not Listed\n", flips - 10); if (flips) printf(" %d Marker Pairs Change Order in Target vs Framework Haplotypes\n", flips); // Load target haplotypes printf("Loading target haplotypes ...\n"); HaplotypeSet target; target.markerCount = markerList.Length(); target.LoadHaplotypes(haplotypes, true); reference.CalculateFrequencies(); target.CalculateFrequencies(); target.CompareFrequencies(reference, markerIndex, markerList); printf(" %d Target Haplotypes Loaded ...\n\n", target.count); int startIndex = firstMarker.IsEmpty() ? 0 : referenceHash.Integer(firstMarker); int stopIndex = lastMarker.IsEmpty() ? reference.markerCount - 1 : referenceHash.Integer(lastMarker); if (startIndex < 0 || stopIndex < 0) error("Clipping requested, but no position available for one of the endpoints"); printf("Setting up Markov Model...\n\n"); // Setup Markov Model MarkovParameters mp; mp.Allocate(reference.markerCount); if (rounds > 0) printf("Initializing Model Parameters (using %s and up to %d haplotypes)\n", em ? "E-M" : "MCMC", states); // Simple initial estimates of error and recombination rate for (int i = 0; i < reference.markerCount; i++) mp.E[i] = 0.01; for (int i = 0; i < reference.markerCount - 1; i++) mp.R[i] = 0.001; if (mp.ReadErrorRates(errorRates)) printf(" Updated error rates using data in %s ...\n", (const char *) errorRates); if (mp.ReadCrossoverRates(recombinationRates)) printf(" Updated recombination rates using %s ...\n", (const char *) recombinationRates); // Parameter estimation loop for (int round = 0; round < rounds; round++) { printf(" Round %d of Parameter Refinement ...\n", round + 1); int iterations = states < reference.count ? states : reference.count; MarkovModel original; original.CopyParameters(mp); #pragma omp parallel for for (int i = 0; i < iterations; i++) { MarkovModel mm; mm.Allocate(reference.markerCount, reference.count - 1); mm.CopyParameters(original); // Reference leave one out (loo) panel char ** reference_loo = new char * [reference.count - 1]; for (int in = 0, out = 0; in < reference.count; in++) if (in != i) reference_loo[out++] = reference.haplotypes[in]; mm.WalkLeft(reference.haplotypes[i], reference_loo, reference.freq); if (em) mm.CountExpected(reference.haplotypes[i], reference_loo, reference.freq); else { #pragma omp critical { mm.ProfileModel(reference.haplotypes[i], reference_loo, reference.freq); } } delete [] reference_loo; #pragma omp critical mp += mm; } if (round >= rounds / 2) { int iterations = states < target.count ? states : target.count; #pragma omp parallel for for (int i = 0; i < iterations; i++) { MarkovModel mm; mm.Allocate(reference.markerCount, reference.count); mm.CopyParameters(original); // Padded version of target haplotype, including missing sites char * padded = new char [reference.markerCount]; for (int k = 0; k < reference.markerCount; k++) padded[k] = 0; // Copy current haplotype into padded vector for (int j = 0; j < target.markerCount; j++) if (markerIndex[j] >= 0) padded[markerIndex[j]] = target.haplotypes[i][j]; mm.WalkLeft(padded, reference.haplotypes, reference.freq); if (em) mm.CountExpected(padded, reference.haplotypes, reference.freq); else { #pragma omp critical { mm.ProfileModel(padded, reference.haplotypes, reference.freq); } } delete [] padded; #pragma omp critical mp += mm; } } mp.UpdateModel(); double crossovers = 0; for (int i = 0; i < reference.markerCount - 1; i++) crossovers += mp.R[i]; double errors = 0; for (int i = 0; i < reference.markerCount; i++) { double heterozygosity = 1.0 - square(reference.freq[1][i]) - square(reference.freq[2][i]) - square(reference.freq[3][i]) - square(reference.freq[4][i]); errors += mp.E[i] * heterozygosity; } errors /= reference.markerCount + 1e-30; printf(" %.0f mosaic crossovers expected per haplotype\n", crossovers); printf(" %.1f%% of crossovers are due to reference flips\n", mp.empiricalFlipRate * 100.); printf(" %.3g errors in mosaic expected per marker\n", errors); } if (rounds > 0) { printf(" Saving estimated parameters for future use ...\n"); mp.WriteParameters(refMarkerList, prefix, gzip); } printf("\n"); // List the major allele at each location reference.ListMajorAlleles(); printf("Generating Draft .info File ...\n\n"); // Output some basic information IFILE info = ifopen(prefix + ".info.draft", "wt"); ifprintf(info, "SNP\tAl1\tAl2\tFreq1\tGenotyped\n"); for (int i = 0, j = 0; i <= stopIndex; i++) if (i >= startIndex) ifprintf(info, "%s\t%s\t%s\t%.4f\t%s\n", (const char *) refMarkerList[i], reference.MajorAlleleLabel(i), reference.MinorAlleleLabel(i), reference.freq[reference.major[i]][i], j < markerIndex.Length() && i == markerIndex[j] ? (j++, "Genotyped") : "-"); else if (j < markerIndex.Length() && i == markerIndex[j]) j++; ifclose(info); printf("Imputing Genotypes ...\n"); IFILE dosages = ifopen(prefix + ".dose" + (gzip ? ".gz" : ""), "wt"); IFILE hapdose, haps; if (phased) { hapdose = ifopen(prefix + ".hapDose" + (gzip ? ".gz" : ""), "wt"); haps = ifopen(prefix + ".haps" + (gzip ? ".gz" : ""), "wt"); } ImputationStatistics stats(reference.markerCount); // Impute each haplotype #pragma omp parallel for for (int i = 0; i < target.count; i++) { if (i != 0 && target.labels[i] == target.labels[i-1]) continue; MarkovModel mm; mm.Allocate(reference.markerCount, reference.count); mm.ClearImputedDose(); mm.CopyParameters(mp); // Padded version of target haplotype, including missing sites char * padded = new char [reference.markerCount]; for (int j = 0; j < reference.markerCount; j++) padded[j] = 0; int k = i; do { printf(" Processing Haplotype %d of %d ...\n", k + 1, target.count); // Copy current haplotype into padded vector for (int j = 0; j < target.markerCount; j++) if (markerIndex[j] >= 0) padded[markerIndex[j]] = target.haplotypes[k][j]; mm.WalkLeft(padded, reference.haplotypes, reference.freq); mm.Impute(reference.major, padded, reference.haplotypes, reference.freq); #pragma omp critical { stats.Update(mm.imputedHap, mm.leaveOneOut, padded, reference.major); } #pragma omp critical if (phased) { ifprintf(hapdose, "%s\tHAPLO%d", (const char *) target.labels[i], k - i + 1); ifprintf(haps, "%s\tHAPLO%d", (const char *) target.labels[i], k - i + 1); for (int j = startIndex; j <= stopIndex; j++) { ifprintf(hapdose, "\t%.3f", mm.imputedHap[j]); ifprintf(haps, "%s%c", j % 8 == 0 ? " " : "", mm.imputedAlleles[j]); } ifprintf(hapdose, "\n"); ifprintf(haps, "\n"); } k++; } while (k < target.count && target.labels[k] == target.labels[i]); printf(" Outputting Individual %s ...\n", (const char *) target.labels[i]); #pragma omp critical { ifprintf(dosages, "%s\tDOSE", (const char *) target.labels[i]); for (int j = startIndex; j <= stopIndex; j++) ifprintf(dosages, "\t%.3f", mm.imputedDose[j]); ifprintf(dosages, "\n"); } delete [] padded; } ifclose(dosages); if (phased) { ifclose(hapdose); ifclose(haps); } // Output some basic information info = ifopen(prefix + ".info" + (gzip ? ".gz" : ""), "wt"); ifprintf(info, "SNP\tAl1\tAl2\tFreq1\tMAF\tAvgCall\tRsq\tGenotyped\tLooRsq\tEmpR\tEmpRsq\tDose1\tDose2\n"); // Padded version of target haplotype, including missing sites char * padded = new char [reference.markerCount]; for (int k = 0; k < reference.markerCount; k++) padded[k] = 0; // Mark genotyped SNPs in padded vector for (int j = 0; j < target.markerCount; j++) if (markerIndex[j] >= 0) padded[markerIndex[j]] = 1; for (int i = startIndex; i <= stopIndex; i++) { ifprintf(info, "%s\t%s\t%s\t%.5f\t%.5f\t%.5f\t%.5f\t", (const char *) refMarkerList[i], reference.MajorAlleleLabel(i), reference.MinorAlleleLabel(i), stats.AlleleFrequency(i), stats.AlleleFrequency(i) > 0.5 ? 1.0 - stats.AlleleFrequency(i) : stats.AlleleFrequency(i), stats.AverageCallScore(i), stats.Rsq(i)); if (padded[i]) ifprintf(info, "Genotyped\t%.5f\t%.5f\t%.5f\t%.5f\t%.5f\n", stats.LooRsq(i), stats.EmpiricalR(i), stats.EmpiricalRsq(i), stats.LooMajorDose(i), stats.LooMinorDose(i)); else ifprintf(info, "-\t-\t-\t-\t-\t-\n"); } ifclose(info); delete [] padded; time_t stop = time(NULL); int seconds = stop - start; printf("\nRun completed in %d hours, %d mins, %d seconds on %s\n\n", seconds / 3600, (seconds % 3600) / 60, seconds % 60, ctime(&stop)); }
STATIC struct job * getjob(char *name) { int jobno; struct job *found, *jp; pid_t pid; int i; if (name == NULL) { #if JOBS currentjob: if ((jp = getcurjob(NULL)) == NULL) error("No current job"); return (jp); #else error("No current job"); #endif } else if (name[0] == '%') { if (is_digit(name[1])) { jobno = number(name + 1); if (jobno > 0 && jobno <= njobs && jobtab[jobno - 1].used != 0) return &jobtab[jobno - 1]; #if JOBS } else if (name[1] == '%' && name[2] == '\0') { goto currentjob; } else if (name[1] == '+' && name[2] == '\0') { goto currentjob; } else if (name[1] == '-' && name[2] == '\0') { if ((jp = getcurjob(NULL)) == NULL || (jp = getcurjob(jp)) == NULL) error("No previous job"); return (jp); #endif } else if (name[1] == '?') { found = NULL; for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) { if (jp->used && jp->nprocs > 0 && strstr(jp->ps[0].cmd, name + 2) != NULL) { if (found) error("%s: ambiguous", name); found = jp; } } if (found != NULL) return (found); } else { found = NULL; for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) { if (jp->used && jp->nprocs > 0 && prefix(name + 1, jp->ps[0].cmd)) { if (found) error("%s: ambiguous", name); found = jp; } } if (found) return found; } } else if (is_number(name)) { pid = (pid_t)number(name); for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) { if (jp->used && jp->nprocs > 0 && jp->ps[jp->nprocs - 1].pid == pid) return jp; } } error("No such job: %s", name); /*NOTREACHED*/ return NULL; }
STATIC struct job * getjob(const char *name, int noerror) { int jobno = -1; struct job *jp; int pid; int i; const char *err_msg = "No such job: %s"; if (name == NULL) { #if JOBS jobno = curjob; #endif err_msg = "No current job"; } else if (name[0] == '%') { if (is_number(name + 1)) { jobno = number(name + 1) - 1; } else if (!name[2]) { switch (name[1]) { #if JOBS case 0: case '+': case '%': jobno = curjob; err_msg = "No current job"; break; case '-': jobno = curjob; if (jobno != -1) jobno = jobtab[jobno].prev_job; err_msg = "No previous job"; break; #endif default: goto check_pattern; } } else { struct job *found; check_pattern: found = NULL; for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) { if (!jp->used || jp->nprocs <= 0) continue; if ((name[1] == '?' && strstr(jp->ps[0].cmd, name + 2)) || prefix(name + 1, jp->ps[0].cmd)) { if (found) { err_msg = "%s: ambiguous"; found = 0; break; } found = jp; } } if (found) return found; } } else if (is_number(name)) { pid = number(name); for (jp = jobtab, i = njobs ; --i >= 0 ; jp++) { if (jp->used && jp->nprocs > 0 && jp->ps[jp->nprocs - 1].pid == pid) return jp; } } if (!jobs_invalid && jobno >= 0 && jobno < njobs) { jp = jobtab + jobno; if (jp->used) return jp; } if (!noerror) error(err_msg, name); return 0; }
int main() { int counter; int casecounter; int i; int j; char *tmp; for(i = 0; i < MAXNUM; i++) { codes[i] = (char *)malloc(MAXLEN * sizeof(char)); } casecounter = 0; while(1) { casecounter++; counter = 0; while(1) { if(gets(codes[counter]) == NULL) { return 0; } if(strcmp(codes[counter], "9") == 0) { break; } else { counter++; } } if(counter <= 1) { printf("Set %d is immediately decodable\n", casecounter); } else { for(i = 0; i < counter - 1; i++) { for(j = i + 1; j < counter; j++) { if(strcmp(codes[i], codes[j]) > 0) { tmp = codes[i]; codes[i] = codes[j]; codes[j] = tmp; } } } for(i = 0; i < counter - 1; i++) { if(prefix(codes[i], codes[i + 1])) { break; } } if(i == counter - 1) { printf("Set %d is immediately decodable\n", casecounter); } else { printf("Set %d is not immediately decodable\n", casecounter); } } } for(i = 0; i < MAXNUM; i++) { free(codes[i]); } return 0; }
wxString ProjectListBox::GetAttributeString(int i, Project* project) { wxString str; switch(i) { case 0: return wxString::Format(_T("%ld"),project->id); case 1: return project->path; case 2: if(project->target==Project::STITCHING) { //make prefix relative to project path wxFileName prefix(project->prefix); wxFileName projectFile(project->path); prefix.MakeRelativeTo(projectFile.GetPath()); return prefix.GetFullPath(); } else { return _("Assistant"); }; case 7: return project->GetStatusText(); //all following cases default to an empty string if file is missing case 3: if(project->status!=Project::MISSING) { if (project->modDate.IsValid()) { return project->modDate.Format(); }; }; return wxEmptyString; case 4: if(project->status!=Project::MISSING) { str = GetLongerFormatName(project->options.outputImageType); str = str+wxT(" (.")+wxString::FromAscii(project->options.outputImageType.c_str())+wxT(")"); return str; }; return wxEmptyString; case 5: if(project->status!=Project::MISSING) { pano_projection_features proj; if (panoProjectionFeaturesQuery(project->options.getProjection(), &proj)) { wxString str2(proj.name, wxConvLocal); return wxGetTranslation(str2); } else { return _T(""); } }; return wxEmptyString; case 6: if(project->status!=Project::MISSING) { str = wxString() << project->options.getWidth(); str = str+_T("x"); str = str << project->options.getHeight(); return str; } return wxEmptyString; default: return _T(""); } }
/* * Recursive file perusal. * * Return FALSE on "?", otherwise TRUE. * * This function could be made much more efficient with the use of "seek" * functionality, especially when moving backwards through a file, or * forwards through a file by less than a page at a time. XXX XXX XXX */ bool show_file(const char *name, const char *what, int line, int mode) { int i, k, n; struct keypress ch; /* Number of "real" lines passed by */ int next = 0; /* Number of "real" lines in the file */ int size; /* Backup value for "line" */ int back = 0; /* This screen has sub-screens */ bool menu = FALSE; /* Case sensitive search */ bool case_sensitive = FALSE; /* Current help file */ ang_file *fff = NULL; /* Find this string (if any) */ char *find = NULL; /* Jump to this tag */ const char *tag = NULL; /* Hold a string to find */ char finder[80] = ""; /* Hold a string to show */ char shower[80] = ""; /* Filename */ char filename[1024]; /* Describe this thing */ char caption[128] = ""; /* Path buffer */ char path[1024]; /* General buffer */ char buf[1024]; /* Lower case version of the buffer, for searching */ char lc_buf[1024]; /* Sub-menu information */ char hook[26][32]; int wid, hgt; /* TRUE if we are inside a RST block that should be skipped */ bool skip_lines = FALSE; /* Wipe the hooks */ for (i = 0; i < 26; i++) hook[i][0] = '\0'; /* Get size */ Term_get_size(&wid, &hgt); /* Copy the filename */ my_strcpy(filename, name, sizeof(filename)); n = strlen(filename); /* Extract the tag from the filename */ for (i = 0; i < n; i++) { if (filename[i] == '#') { filename[i] = '\0'; tag = filename + i + 1; break; } } /* Redirect the name */ name = filename; /* Hack XXX XXX XXX */ if (what) { my_strcpy(caption, what, sizeof(caption)); my_strcpy(path, name, sizeof(path)); fff = file_open(path, MODE_READ, FTYPE_TEXT); } /* Look in "help" */ if (!fff) { strnfmt(caption, sizeof(caption), "Help file '%s'", name); path_build(path, sizeof(path), ANGBAND_DIR_HELP, name); fff = file_open(path, MODE_READ, FTYPE_TEXT); } /* Look in "info" */ if (!fff) { strnfmt(caption, sizeof(caption), "Info file '%s'", name); path_build(path, sizeof(path), ANGBAND_DIR_INFO, name); fff = file_open(path, MODE_READ, FTYPE_TEXT); } /* Oops */ if (!fff) { /* Message */ msg("Cannot open '%s'.", name); event_signal(EVENT_MESSAGE_FLUSH); /* Oops */ return (TRUE); } /* Pre-Parse the file */ while (TRUE) { /* Read a line or stop */ if (!file_getl(fff, buf, sizeof(buf))) break; /* Skip lines if we are inside a RST directive*/ if(skip_lines){ if(contains_only_spaces(buf)) skip_lines=FALSE; continue; } /* Parse a very small subset of RST */ /* TODO: should be more flexible */ if (prefix(buf, ".. ")) { /* parse ".. menu:: [x] filename.txt" (with exact spacing)*/ if(prefix(buf+strlen(".. "), "menu:: [") && buf[strlen(".. menu:: [x")]==']') { /* This is a menu file */ menu = TRUE; /* Extract the menu item */ k = A2I(buf[strlen(".. menu:: [")]); /* Store the menu item (if valid) */ if ((k >= 0) && (k < 26)) my_strcpy(hook[k], buf + strlen(".. menu:: [x] "), sizeof(hook[0])); } /* parse ".. _some_hyperlink_target:" */ else if (buf[strlen(".. ")] == '_') { if (tag) { /* Remove the closing '>' of the tag */ buf[strlen(buf) - 1] = '\0'; /* Compare with the requested tag */ if (streq(buf + strlen(".. _"), tag)) { /* Remember the tagged line */ line = next; } } } /* Skip this and enter skip mode*/ skip_lines = TRUE; continue; } /* Count the "real" lines */ next++; } /* Save the number of "real" lines */ size = next; /* Display the file */ while (TRUE) { /* Clear screen */ Term_clear(); /* Restrict the visible range */ if (line > (size - (hgt - 4))) line = size - (hgt - 4); if (line < 0) line = 0; skip_lines = FALSE; /* Re-open the file if needed */ if (next > line) { /* Close it */ file_close(fff); /* Hack -- Re-Open the file */ fff = file_open(path, MODE_READ, FTYPE_TEXT); if (!fff) return (TRUE); /* File has been restarted */ next = 0; } /* Goto the selected line */ while (next < line) { /* Get a line */ if (!file_getl(fff, buf, sizeof(buf))) break; /* Skip lines if we are inside a RST directive*/ if(skip_lines){ if(contains_only_spaces(buf)) skip_lines=FALSE; continue; } /* Skip RST directives */ if (prefix(buf, ".. ")) { skip_lines=TRUE; continue; } /* Count the lines */ next++; } /* Dump the next lines of the file */ for (i = 0; i < hgt - 4; ) { /* Hack -- track the "first" line */ if (!i) line = next; /* Get a line of the file or stop */ if (!file_getl(fff, buf, sizeof(buf))) break; /* Skip lines if we are inside a RST directive*/ if(skip_lines){ if(contains_only_spaces(buf)) skip_lines=FALSE; continue; } /* Skip RST directives */ if (prefix(buf, ".. ")) { skip_lines=TRUE; continue; } /* skip | characters */ strskip(buf,'|'); /* escape backslashes */ strescape(buf,'\\'); /* Count the "real" lines */ next++; /* Make a copy of the current line for searching */ my_strcpy(lc_buf, buf, sizeof(lc_buf)); /* Make the line lower case */ if (!case_sensitive) string_lower(lc_buf); /* Hack -- keep searching */ if (find && !i && !strstr(lc_buf, find)) continue; /* Hack -- stop searching */ find = NULL; /* Dump the line */ Term_putstr(0, i+2, -1, COLOUR_WHITE, buf); /* Highlight "shower" */ if (shower[0]) { const char *str = lc_buf; /* Display matches */ while ((str = strstr(str, shower)) != NULL) { int len = strlen(shower); /* Display the match */ Term_putstr(str-lc_buf, i+2, len, COLOUR_YELLOW, &buf[str-lc_buf]); /* Advance */ str += len; } } /* Count the printed lines */ i++; } /* Hack -- failed search */ if (find) { bell("Search string not found!"); line = back; find = NULL; continue; } /* Show a general "title" */ prt(format("[%s, %s, Line %d-%d/%d]", buildid, caption, line, line + hgt - 4, size), 0, 0); /* Prompt -- menu screen */ if (menu) { /* Wait for it */ prt("[Press a Letter, or ESC to exit.]", hgt - 1, 0); } /* Prompt -- small files */ else if (size <= hgt - 4) { /* Wait for it */ prt("[Press ESC to exit.]", hgt - 1, 0); } /* Prompt -- large files */ else { /* Wait for it */ prt("[Press Space to advance, or ESC to exit.]", hgt - 1, 0); } /* Get a keypress */ ch = inkey(); /* Exit the help */ if (ch.code == '?') break; /* Toggle case sensitive on/off */ if (ch.code == '!') { case_sensitive = !case_sensitive; } /* Try showing */ if (ch.code == '&') { /* Get "shower" */ prt("Show: ", hgt - 1, 0); (void)askfor_aux(shower, sizeof(shower), NULL); /* Make the "shower" lowercase */ if (!case_sensitive) string_lower(shower); } /* Try finding */ if (ch.code == '/') { /* Get "finder" */ prt("Find: ", hgt - 1, 0); if (askfor_aux(finder, sizeof(finder), NULL)) { /* Find it */ find = finder; back = line; line = line + 1; /* Make the "finder" lowercase */ if (!case_sensitive) string_lower(finder); /* Show it */ my_strcpy(shower, finder, sizeof(shower)); } } /* Go to a specific line */ if (ch.code == '#') { char tmp[80] = "0"; prt("Goto Line: ", hgt - 1, 0); if (askfor_aux(tmp, sizeof(tmp), NULL)) line = atoi(tmp); } /* Go to a specific file */ if (ch.code == '%') { char ftmp[80] = "help.hlp"; prt("Goto File: ", hgt - 1, 0); if (askfor_aux(ftmp, sizeof(ftmp), NULL)) { if (!show_file(ftmp, NULL, 0, mode)) ch.code = ESCAPE; } } switch (ch.code) { /* up a line */ case ARROW_UP: case '8': line--; break; /* up a page */ case KC_PGUP: case '9': case '-': line -= (hgt - 4); break; /* home */ case KC_HOME: case '7': line = 0; break; /* down a line */ case ARROW_DOWN: case '2': case KC_ENTER: line++; break; /* down a page */ case KC_PGDOWN: case '3': case ' ': line += hgt - 4; break; /* end */ case KC_END: case '1': line = size; break; } /* Recurse on letters */ if (menu && isalpha((unsigned char)ch.code)) { /* Extract the requested menu item */ k = A2I(ch.code); /* Verify the menu item */ if ((k >= 0) && (k <= 25) && hook[k][0]) { /* Recurse on that file */ if (!show_file(hook[k], NULL, 0, mode)) ch.code = ESCAPE; } } /* Exit on escape */ if (ch.code == ESCAPE) break; } /* Close the file */ file_close(fff); /* Done */ return (ch.code != '?'); }
pfs::error_code ubjson_ostream<OStreamType, JsonType>::write_object (json_type const & j) { _os << UBJSON_CHAR_OBJECT_BEGIN; bool use_count_optimization = ((_flags & count_optimized) && !j.empty()); bool is_special_case = false; // If a type is specified, a count must also be specified. // A type cannot be specified by itself. bool use_type_optimization = ((_flags & type_optimized) && use_count_optimization); // Additional checks for type optimization if (use_type_optimization) { // This call is safe. Array is not empty as checked before int8_t first_prefix = prefix(*j.cbegin()); use_type_optimization = pfs::all_of(j.cbegin(), j.cend(), compare_prefix(first_prefix)); if (use_type_optimization) { _os << UBJSON_CHAR_TYPE; _os << first_prefix; // Check special cases if (first_prefix == UBJSON_CHAR_NOOP || first_prefix == UBJSON_CHAR_NULL || first_prefix == UBJSON_CHAR_TRUE || first_prefix == UBJSON_CHAR_FALSE) { is_special_case = true; } } } if (use_count_optimization) { _os << UBJSON_CHAR_SIZE; write_integer(static_cast<typename json_type::integer_type>(j.size()), true); } typename json_type::const_iterator first = j.cbegin(); typename json_type::const_iterator last = j.cend(); if (is_special_case) { for (; first != last; ++first) { // The [S] (string) marker is omitted from each of the names in the // name/value pairings inside the object. The JSON specification does // not allow non-string name values, therefore the [S] marker // is redundant and must not be used. write_string(first.key(), false); } } else { for (; first != last; ++first) { write_string(first.key(), false); write_json(*first, !use_type_optimization); } } // If a count is specified the container must not specify an end-marker. if (!use_count_optimization) _os << UBJSON_CHAR_OBJECT_END; return pfs::error_code(); }
newfunc () { char n[NAMESIZE], *ptr; fexitlab = getlabel(); if (!symname (n) ) { error ("illegal function or declaration"); kill (); return; } if (ptr = findglb (n)) { if (ptr[IDENT] != FUNCTION) multidef (n); else if (ptr[OFFSET] == FUNCTION) multidef (n); else ptr[OFFSET] = FUNCTION; } else addglb (n, FUNCTION, CINT, FUNCTION, PUBLIC); prologue (); if (!match ("(")) error ("missing open paren"); prefix (); outstr (n); col (); nl (); locptr = STARTLOC; argstk = 0; while (!match (")")) { if (symname (n)) { if (findloc (n)) multidef (n); else { addloc (n, 0, 0, argstk, AUTO); argstk = argstk + intsize(); } } else { error ("illegal argument name"); junk (); } blanks (); if (!streq (line + lptr, ")")) { if (!match (",")) error ("expected comma"); } if (endst ()) break; } stkp = 0; argtop = argstk; while (argstk) { if (amatch ("register", 8)) { if (amatch("char", 4)) getarg(CCHAR); else if (amatch ("int", 3)) getarg(CINT); else getarg(CINT); ns(); } else if (amatch ("char", 4)) { getarg (CCHAR); ns (); } else if (amatch ("int", 3)) { getarg (CINT); ns (); } else { error ("wrong number args"); break; } } statement(YES); printlabel(fexitlab); col(); nl(); modstk (0); gret (); stkp = 0; locptr = STARTLOC; }