bool MOL2Format::ReadMolecule(OBBase* pOb, OBConversion* pConv) { OBMol* pmol = pOb->CastAndClear<OBMol>(); if(pmol==NULL) return false; //Define some references so we can use the old parameter names istream &ifs = *pConv->GetInStream(); OBMol &mol = *pmol; //Old code follows... bool foundAtomLine = false; char buffer[BUFF_SIZE]; char *comment = NULL; string str,str1; vector<string> vstr; int len; mol.BeginModify(); for (;;) { if (!ifs.getline(buffer,BUFF_SIZE)) return(false); if (EQn(buffer,"@<TRIPOS>MOLECULE",17)) break; } // OK, just read MOLECULE line int lcount; int natoms,nbonds; bool hasPartialCharges = true; for (lcount=0;;lcount++) { if (!ifs.getline(buffer,BUFF_SIZE)) return(false); if (EQn(buffer,"@<TRIPOS>ATOM",13)) { foundAtomLine = true; break; } if (lcount == 0) { tokenize(vstr,buffer); if (!vstr.empty()) mol.SetTitle(buffer); } else if (lcount == 1) sscanf(buffer,"%d%d",&natoms,&nbonds); else if (lcount == 3) // charge descriptions { // Annotate origin of partial charges OBPairData *dp = new OBPairData; dp->SetAttribute("PartialCharges"); dp->SetValue(buffer); dp->SetOrigin(fileformatInput); mol.SetData(dp); if (strncasecmp(buffer, "NO_CHARGES", 10) == 0) hasPartialCharges = false; } else if (lcount == 4) //energy (?) { tokenize(vstr,buffer); if (!vstr.empty() && vstr.size() == 3) if (vstr[0] == "Energy") mol.SetEnergy(atof(vstr[2].c_str())); } else if (lcount == 5) //comment { if ( buffer[0] ) { len = (int) strlen(buffer)+1; //! @todo allow better multi-line comments // which don't allow ill-formed data to consume memory // Thanks to Andrew Dalke for the pointer if (comment != NULL) delete [] comment; comment = new char [len]; memcpy(comment,buffer,len); } } } if (!foundAtomLine) { mol.EndModify(); mol.Clear(); obErrorLog.ThrowError(__FUNCTION__, "Unable to read Mol2 format file. No atoms found.", obWarning); return(false); } mol.ReserveAtoms(natoms); int i; vector3 v; OBAtom atom; double x,y,z,pcharge; char temp_type[BUFF_SIZE], resname[BUFF_SIZE], atmid[BUFF_SIZE]; int elemno, resnum = -1; ttab.SetFromType("SYB"); for (i = 0;i < natoms;i++) { if (!ifs.getline(buffer,BUFF_SIZE)) return(false); sscanf(buffer," %*s %1024s %lf %lf %lf %1024s %d %1024s %lf", atmid, &x,&y,&z, temp_type, &resnum, resname, &pcharge); atom.SetVector(x, y, z); // Handle "CL" and "BR" and other mis-typed atoms str = temp_type; if (strncmp(temp_type, "CL", 2) == 0) { str = "Cl"; } else if (strncmp(temp_type,"BR",2) == 0) { str = "Br"; } else if (strncmp(temp_type,"S.o2", 4) == 02) { str = "S.O2"; } else if (strncmp(temp_type,"S.o", 3) == 0) { str = "S.O"; } else if (strncmp(temp_type,"SI", 2) == 0) { str = "Si"; // The following cases are entries which are not in openbabel/data/types.txt // and should probably be added there } else if (strncmp(temp_type,"S.1", 3) == 0) { str = "S.2"; // no idea what the best type might be here } else if (strncmp(temp_type,"P.", 2) == 0) { str = "P.3"; } else if (strncasecmp(temp_type,"Ti.", 3) == 0) { // e.g. Ti.th str = "Ti"; } else if (strncasecmp(temp_type,"Ru.", 3) == 0) { // e.g. Ru.oh str = "Ru"; } ttab.SetToType("ATN"); ttab.Translate(str1,str); elemno = atoi(str1.c_str()); ttab.SetToType("IDX"); // We might have missed some SI or FE type things above, so here's // another check if( !elemno && isupper(temp_type[1]) ) { temp_type[1] = (char)tolower(temp_type[1]); str = temp_type; ttab.Translate(str1,str); elemno = atoi(str1.c_str()); } // One last check if there isn't a period in the type, // it's a malformed atom type, but it may be the element symbol // GaussView does this (PR#1739905) if ( !elemno ) { obErrorLog.ThrowError(__FUNCTION__, "This Mol2 file is non-standard. Cannot interpret atom types correctly, instead attempting to interpret as elements instead.", obWarning); string::size_type dotPos = str.find('.'); if (dotPos == string::npos) { elemno = etab.GetAtomicNum(str.c_str()); } } atom.SetAtomicNum(elemno); ttab.SetToType("INT"); ttab.Translate(str1,str); atom.SetType(str1); atom.SetPartialCharge(pcharge); if (!mol.AddAtom(atom)) return(false); if (!IsNearZero(pcharge)) hasPartialCharges = true; // Add residue information if it exists if (resnum != -1 && resnum != 0 && strlen(resname) != 0 && strncmp(resname,"<1>", 3) != 0) { OBResidue *res = (mol.NumResidues() > 0) ? mol.GetResidue(mol.NumResidues()-1) : NULL; if (res == NULL || res->GetName() != resname || static_cast<int>(res->GetNum()) != resnum) { vector<OBResidue*>::iterator ri; for (res = mol.BeginResidue(ri) ; res ; res = mol.NextResidue(ri)) if (res->GetName() == resname && static_cast<int>(res->GetNum()) == resnum) break; if (res == NULL) { res = mol.NewResidue(); res->SetName(resname); res->SetNum(resnum); } } OBAtom *atomPtr = mol.GetAtom(mol.NumAtoms()); res->AddAtom(atomPtr); res->SetAtomID(atomPtr, atmid); } // end adding residue info } for (;;) { if (!ifs.getline(buffer,BUFF_SIZE)) return(false); str = buffer; if (!strncmp(buffer,"@<TRIPOS>BOND",13)) break; } int start,end,order; for (i = 0; i < nbonds; i++) { if (!ifs.getline(buffer,BUFF_SIZE)) return(false); sscanf(buffer,"%*d %d %d %1024s",&start,&end,temp_type); str = temp_type; order = 1; if (str == "ar" || str == "AR" || str == "Ar") order = 5; else if (str == "AM" || str == "am" || str == "Am") order = 1; else order = atoi(str.c_str()); mol.AddBond(start,end,order); } // Suggestion by Liu Zhiguo 2008-01-26 // Mol2 files define atom types -- there is no need to re-perceive mol.SetAtomTypesPerceived(); mol.EndModify(); //must add generic data after end modify - otherwise it will be blown away if (comment) { OBCommentData *cd = new OBCommentData; cd->SetData(comment); cd->SetOrigin(fileformatInput); mol.SetData(cd); delete [] comment; comment = NULL; } if (hasPartialCharges) mol.SetPartialChargesPerceived(); /* Disabled due to PR#3048758 -- seekg is very slow with gzipped mol2 // continue untill EOF or untill next molecule record streampos pos; for(;;) { pos = ifs.tellg(); if (!ifs.getline(buffer,BUFF_SIZE)) break; if (EQn(buffer,"@<TRIPOS>MOLECULE",17)) break; } ifs.seekg(pos); // go back to the end of the molecule */ return(true); }
int main(int argv, char** argc) { if (argv == 1) { std::cerr << "Must provide a command and arguments! Try parse, rewrite, compile, assemble\n"; return 0; } if (argv == 2 && std::string(argc[1]) == "--help" || std::string(argc[1]) == "-h" ) { std::cout << argc[1] << "\n"; std::cout << "serpent command input\n"; std::cout << "where input -s for from stdin, a file, or interpreted as serpent code if does not exist as file."; std::cout << "where command: \n"; std::cout << " parse: Just parses and returns s-expression code.\n"; std::cout << " rewrite: Parse, use rewrite rules print s-expressions of result.\n"; std::cout << " compile: Return resulting compiled EVM code in hex.\n"; std::cout << " assemble: Return result from step before compilation.\n"; return 0; } std::string flag = ""; std::string command = argc[1]; std::string input; std::string secondInput; if (std::string(argc[1]) == "-s") { flag = command.substr(1); command = argc[2]; input = ""; std::string line; while (std::getline(std::cin, line)) { input += line + "\n"; } secondInput = argv == 3 ? "" : argc[3]; } else { if (argv == 2) { std::cerr << "Not enough arguments for serpent cmdline\n"; throw(0); } input = argc[2]; secondInput = argv == 3 ? "" : argc[3]; } bool haveSec = secondInput.length() > 0; if (command == "parse" || command == "parse_serpent") { std::cout << printAST(parseSerpent(input), haveSec) << "\n"; } else if (command == "rewrite") { std::cout << printAST(rewrite(parseLLL(input, true)), haveSec) << "\n"; } else if (command == "compile_to_lll") { std::cout << printAST(compileToLLL(input), haveSec) << "\n"; } else if (command == "rewrite_chunk") { std::cout << printAST(rewriteChunk(parseLLL(input, true)), haveSec) << "\n"; } else if (command == "compile_chunk_to_lll") { std::cout << printAST(compileChunkToLLL(input), haveSec) << "\n"; } else if (command == "build_fragtree") { std::cout << printAST(buildFragmentTree(parseLLL(input, true))) << "\n"; } else if (command == "compile_lll") { std::cout << binToHex(compileLLL(parseLLL(input, true))) << "\n"; } else if (command == "dereference") { std::cout << printAST(dereference(parseLLL(input, true)), haveSec) <<"\n"; } else if (command == "pretty_assemble") { std::cout << printTokens(prettyAssemble(parseLLL(input, true))) <<"\n"; } else if (command == "pretty_compile_lll") { std::cout << printTokens(prettyCompileLLL(parseLLL(input, true))) << "\n"; } else if (command == "pretty_compile") { std::cout << printTokens(prettyCompile(input)) << "\n"; } else if (command == "pretty_compile_chunk") { std::cout << printTokens(prettyCompileChunk(input)) << "\n"; } else if (command == "assemble") { std::cout << assemble(parseLLL(input, true)) << "\n"; } else if (command == "serialize") { std::cout << binToHex(serialize(tokenize(input, Metadata(), false))) << "\n"; } else if (command == "flatten") { std::cout << printTokens(flatten(parseLLL(input, true))) << "\n"; } else if (command == "deserialize") { std::cout << printTokens(deserialize(hexToBin(input))) << "\n"; } else if (command == "compile") { std::cout << binToHex(compile(input)) << "\n"; } else if (command == "compile_chunk") { std::cout << binToHex(compileChunk(input)) << "\n"; } else if (command == "encode_datalist") { std::vector<Node> tokens = tokenize(input); std::vector<std::string> o; for (int i = 0; i < (int)tokens.size(); i++) { o.push_back(tokens[i].val); } std::cout << binToHex(encodeDatalist(o)) << "\n"; } else if (command == "decode_datalist") { std::vector<std::string> o = decodeDatalist(hexToBin(input)); std::vector<Node> tokens; for (int i = 0; i < (int)o.size(); i++) tokens.push_back(token(o[i])); std::cout << printTokens(tokens) << "\n"; } else if (command == "tokenize") { std::cout << printTokens(tokenize(input)); } else if (command == "biject") { if (argv == 3) std::cerr << "Not enough arguments for biject\n"; int pos = decimalToUnsigned(secondInput); std::vector<Node> n = prettyCompile(input); if (pos >= (int)n.size()) std::cerr << "Code position too high\n"; Metadata m = n[pos].metadata; std::cout << "Opcode: " << n[pos].val << ", file: " << m.file << ", line: " << m.ln << ", char: " << m.ch << "\n"; } }
bool PWscfFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv) { OBMol* pmol = pOb->CastAndClear<OBMol>(); if(pmol==NULL) return false; //Define some references so we can use the old parameter names istream &ifs = *pConv->GetInStream(); char buffer[BUFF_SIZE], tag[BUFF_SIZE]; double x,y,z; double alat = 1.0; vector<string> vs; matrix3x3 ortho; int atomicNum; OBUnitCell *cell = new OBUnitCell(); bool hasEnthalpy=false; double enthalpy, pv; pmol->BeginModify(); while (ifs.getline(buffer,BUFF_SIZE)) { // Older version of pwscf may use this for alat if (strstr(buffer, "lattice parameter (a_0)")) { tokenize(vs, buffer); alat = atof(vs.at(4).c_str()); } // Newer versions will use this for alat instead if (strstr(buffer, "lattice parameter (alat)")) { tokenize(vs, buffer); alat = atof(vs.at(4).c_str()); } // Unit cell info // Newer versions will also say "CELL_PARAMETERS" to complain that no // units were specified if (strstr(buffer, "CELL_PARAMETERS") && !strstr(buffer, "no units specified in CELL_PARAMETERS card")) { // Discover units double conv = 1.0; tokenize(vs, buffer); if (strstr(vs[1].c_str(), "alat")) { conv = alat * BOHR_TO_ANGSTROM; } else if (strstr(vs[1].c_str(), "bohr")) { conv = BOHR_TO_ANGSTROM; } // Add others if needed double v11, v12, v13, v21, v22, v23, v31, v32, v33; ifs.getline(buffer,BUFF_SIZE); // v1 tokenize(vs, buffer); v11 = atof(vs.at(0).c_str()) * conv; v12 = atof(vs.at(1).c_str()) * conv; v13 = atof(vs.at(2).c_str()) * conv; ifs.getline(buffer,BUFF_SIZE); // v2 tokenize(vs, buffer); v21 = atof(vs.at(0).c_str()) * conv; v22 = atof(vs.at(1).c_str()) * conv; v23 = atof(vs.at(2).c_str()) * conv; ifs.getline(buffer,BUFF_SIZE); // v3 tokenize(vs, buffer); v31 = atof(vs.at(0).c_str()) * conv; v32 = atof(vs.at(1).c_str()) * conv; v33 = atof(vs.at(2).c_str()) * conv; // Build unit cell cell->SetData(vector3(v11,v12,v13), vector3(v21,v22,v23), vector3(v31,v32,v33)); } // Unit cell info (for non-variable cell calcs) if (strstr(buffer, "crystal axes: (cart. coord. in units of a_0)") || strstr(buffer, "crystal axes: (cart. coord. in units of alat)")) { double conv = alat * BOHR_TO_ANGSTROM; double v11, v12, v13, v21, v22, v23, v31, v32, v33; ifs.getline(buffer,BUFF_SIZE); // v1 tokenize(vs, buffer); v11 = atof(vs.at(3).c_str()) * conv; v12 = atof(vs.at(4).c_str()) * conv; v13 = atof(vs.at(5).c_str()) * conv; ifs.getline(buffer,BUFF_SIZE); // v2 tokenize(vs, buffer); v21 = atof(vs.at(3).c_str()) * conv; v22 = atof(vs.at(4).c_str()) * conv; v23 = atof(vs.at(5).c_str()) * conv; ifs.getline(buffer,BUFF_SIZE); // v3 tokenize(vs, buffer); v31 = atof(vs.at(3).c_str()) * conv; v32 = atof(vs.at(4).c_str()) * conv; v33 = atof(vs.at(5).c_str()) * conv; // Build unit cell cell->SetData(vector3(v11,v12,v13), vector3(v21,v22,v23), vector3(v31,v32,v33)); } // Atoms info if (strstr(buffer, "ATOMIC_POSITIONS")) { // Clear old atoms from pmol vector<OBAtom*> toDelete; FOR_ATOMS_OF_MOL(a, *pmol) toDelete.push_back(&*a); for (size_t i = 0; i < toDelete.size(); i++) pmol->DeleteAtom(toDelete.at(i)); // Discover units matrix3x3 conv (1); tokenize(vs, buffer); if (strstr(vs[1].c_str(), "alat")) { conv *= (alat * BOHR_TO_ANGSTROM); } else if (strstr(vs[1].c_str(), "crystal")) { // Set to the zero matrix and test below. conv = matrix3x3 (0.0); } // Add others if needed // Load new atoms from molecule ifs.getline(buffer,BUFF_SIZE); // First entry tokenize(vs, buffer); int size = vs.size(); while (size == 4) { atomicNum = OBElements::GetAtomicNum(vs[0].c_str()); x = atof((char*)vs[1].c_str()); y = atof((char*)vs[2].c_str()); z = atof((char*)vs[3].c_str()); // Add atom OBAtom *atom = pmol->NewAtom(); atom->SetAtomicNum(atomicNum); vector3 coords (x,y,z); if (conv.determinant() == 0.0) { // Fractional coords atom->SetVector(cell->FractionalToCartesian(coords)); } else { atom->SetVector(conv * coords); } // Reset vars ifs.getline(buffer,BUFF_SIZE); // First entry tokenize(vs, buffer); size = vs.size(); } } // Free energy if (strstr(buffer, "Final energy =")) { tokenize(vs, buffer); pmol->SetEnergy(atof(vs[3].c_str()) * RYDBERG_TO_KCAL_PER_MOL); } // H - PV = U energy if (strstr(buffer, "! total energy =")) { tokenize(vs, buffer); pmol->SetEnergy(atof(vs[4].c_str()) * RYDBERG_TO_KCAL_PER_MOL); } // Enthalphy if (strstr(buffer, "Final enthalpy =")) { tokenize(vs, buffer); hasEnthalpy = true; enthalpy = atof(vs.at(3).c_str()) * RYDBERG_TO_KCAL_PER_MOL; pv = enthalpy - pmol->GetEnergy(); } } // set final unit cell pmol->SetData(cell); // Set enthalpy if (hasEnthalpy) { OBPairData *enthalpyPD = new OBPairData(); OBPairData *enthalpyPD_pv = new OBPairData(); OBPairData *enthalpyPD_eV = new OBPairData(); OBPairData *enthalpyPD_pv_eV = new OBPairData(); enthalpyPD->SetAttribute("Enthalpy (kcal/mol)"); enthalpyPD_pv->SetAttribute("Enthalpy PV term (kcal/mol)"); enthalpyPD_eV->SetAttribute("Enthalpy (eV)"); enthalpyPD_pv_eV->SetAttribute("Enthalpy PV term (eV)"); double en_kcal_per_mole = enthalpy; double pv_kcal_per_mole = pv; double en_eV = enthalpy / EV_TO_KCAL_PER_MOL; double pv_eV = pv / EV_TO_KCAL_PER_MOL; snprintf(tag, BUFF_SIZE, "%f", en_kcal_per_mole); enthalpyPD->SetValue(tag); snprintf(tag, BUFF_SIZE, "%f", pv_kcal_per_mole); enthalpyPD_pv->SetValue(tag); snprintf(tag, BUFF_SIZE, "%f", en_eV); enthalpyPD_eV->SetValue(tag); snprintf(tag, BUFF_SIZE, "%f", pv_eV); enthalpyPD_pv_eV->SetValue(tag); pmol->SetData(enthalpyPD); pmol->SetData(enthalpyPD_pv); pmol->SetData(enthalpyPD_eV); pmol->SetData(enthalpyPD_pv_eV); } pmol->EndModify(); return true; }
gint nwchem_input_import(gpointer import) { gint *symbols, num_symbols, num_tokens, value; gchar *line, **buff; gpointer scan, config; GString *unparsed; struct model_pak *model=NULL; // CURRENT - will break if more than one in a file struct nwchem_pak *nwchem; scan = scan_new(import_fullpath(import)); if (!scan) return(1); /* populate symbol table */ nwchem_scan_symbols_init(scan); config = config_new(NWCHEM, NULL); nwchem = config_data(config); unparsed = g_string_new(NULL); while (!scan_complete(scan)) { symbols = scan_get_symbols(scan, &num_symbols); if (num_symbols) { /* process first recognized symbol */ value = symbols[0]; switch (value) { case NWCHEM_START: /* TODO - could this serve as title? */ nwchem->start = parse_strip(scan_cur_line(scan)); break; case NWCHEM_BASIS: // TODO - don't want to use this for predefined basis sets read_nwchem_basis_library(scan, config); break; case NWCHEM_CHARGE: line = scan_cur_line(scan); buff = tokenize(line, &num_tokens); if (num_tokens > 1) nwchem->charge = g_strdup(buff[1]); g_strfreev(buff); break; case NWCHEM_GEOMETRY: if (!model) { model = model_new(); import_object_add(IMPORT_MODEL, model, import); } read_nwchem_geometry(scan, model); break; case NWCHEM_SYSTEM: if (!model) { model = model_new(); import_object_add(IMPORT_MODEL, model, import); } read_nwchem_system(scan, model); break; case NWCHEM_TASK: read_nwchem_task(scan, config, symbols, num_symbols); break; default: /* add lines that have recognized symbols (but no special trigger) to unparsed */ /* this'll happen for symbols that occur in multiple locations (eg dft) */ line = scan_cur_line(scan); if (line) g_string_append(unparsed, line); } g_free(symbols); } else { /* add non-NULL lines to unparsed list */ line = scan_cur_line(scan); if (line) g_string_append(unparsed, line); } } config_unparsed_set(g_string_free(unparsed, FALSE), config); import_object_add(IMPORT_CONFIG, config, import); scan_free(scan); import_init(import); return(0); }
Event * create_riemann_event (const char *grid, const char *cluster, const char *host, const char *ip, const char *metric, const char *value, const char *type, const char *units, const char *state, unsigned int localtime, const char *tags_str, const char *location, unsigned int ttl) { /* debug_msg("[riemann] grid=%s, cluster=%s, host=%s, ip=%s, metric=%s, value=%s %s, type=%s, state=%s, " "localtime=%u, tags=%s, location=%s, ttl=%u\n", grid, cluster, host, ip, metric, value, units, type, state, localtime, tags_str, location, ttl); */ Event *event = malloc (sizeof (Event)); event__init (event); event->host = strdup (host); event->service = strdup (metric); if (value) { if (!strcmp (type, "int")) { event->has_metric_sint64 = 1; event->metric_sint64 = strtol (value, (char **) NULL, 10); } else if (!strcmp (type, "float")) { event->has_metric_d = 1; event->metric_d = (double) strtod (value, (char **) NULL); } else { event->state = strdup (value); } } event->description = strdup (units); if (state) event->state = strdup (state); if (localtime) event->time = localtime; char *tags[64] = { NULL }; event->n_tags = tokenize (tags_str, ",", tags); event->tags = malloc (sizeof (char *) * (event->n_tags)); int j; for (j = 0; j< event->n_tags; j++) { event->tags[j] = strdup (tags[j]); free(tags[j]); } char attr_str[512]; sprintf(attr_str, "grid=%s,cluster=%s,ip=%s,location=%s%s%s", grid, cluster, ip, location, gmetad_config.riemann_attributes ? "," : "", gmetad_config.riemann_attributes ? gmetad_config.riemann_attributes : ""); char *kv[64] = { NULL }; event->n_attributes = tokenize (attr_str, ",", kv); Attribute **attrs; attrs = malloc (sizeof (Attribute *) * (event->n_attributes)); int i; for (i = 0; i < event->n_attributes; i++) { char *pair[2] = { NULL }; tokenize (kv[i], "=", pair); free(kv[i]); attrs[i] = malloc (sizeof (Attribute)); attribute__init (attrs[i]); attrs[i]->key = strdup(pair[0]); attrs[i]->value = strdup(pair[1]); free(pair[0]); free(pair[1]); } event->attributes = attrs; event->has_ttl = 1; event->ttl = ttl; /* debug_msg("[riemann] %zu host=%s, service=%s, state=%s, metric_f=%f, metric_d=%lf, metric_sint64=%" PRId64 ", description=%s, ttl=%f, tags(%zu), attributes(%zu)", event->time, event->host, event->service, event->state, event->metric_f, event->metric_d, event->metric_sint64, event->description, event->ttl, event->n_tags, event->n_attributes); */ return event; }
static void complete(t_tokenline *tl) { t_token *tokens, *partial; unsigned int i; int words[TL_MAX_WORDS], num_words, arg_needed, multiple; int reprompt, t; char *word; reprompt = FALSE; if (!tl->pos) { /* Tab on an empty line: show all commmands. */ tl->print(tl->user, NL); tokens = tl->token_levels[tl->token_level]; for (i = 0; tokens[i].token; i++) { print_token_and_help(tl, &tokens[i]); tl->print(tl->user, NL); } reprompt = TRUE; } else if (tl->buf[tl->pos - 1] != ' ') { /* Try to complete the current word. */ if (!split_line(tl, words, &num_words, TRUE) || !num_words) return; if (tokenize(tl, words, num_words - 1, &tokens, NULL)) { if (tokens) { word = tl->buf + words[num_words - 1]; partial = NULL; multiple = FALSE; for (t = 0; tokens[t].token; t++) { if (tokens[t].token >= T_ARG_UINT) continue; if (!strncmp(word, tl->token_dict[tokens[t].token].tokenstr, strlen(word))) { if (partial) { /* Not the first match, print previous one. */ multiple = TRUE; tl->print(tl->user, NL); print_token_and_help(tl, partial); } partial = &tokens[t]; } } if (partial) { if (multiple) { /* Last partial match. */ tl->print(tl->user, NL); print_token_and_help(tl, partial); tl->print(tl->user, NL); reprompt = TRUE; } else { for (i = strlen(word); i < strlen(tl->token_dict[partial->token].tokenstr); i++) add_char(tl, tl->token_dict[partial->token].tokenstr[i]); add_char(tl, ' '); } } } } } else { /* List all possible tokens from this point. */ if (!split_line(tl, words, &num_words, TRUE) || !num_words) return; if (tokenize(tl, words, num_words, &tokens, &arg_needed)) { if (arg_needed && arg_needed != T_ARG_TOKEN) { tl->print(tl->user, INDENT NL); tl->print(tl->user, arg_type_to_string(arg_needed)); tl->print(tl->user, NL); reprompt = TRUE; } else if (tokens) { tl->print(tl->user, NL); for (t = 0; tokens[t].token; t++) { print_token_and_help(tl, &tokens[t]); tl->print(tl->user, NL); reprompt = TRUE; } } } } unsplit_line(tl); if (reprompt) { tl->print(tl->user, tl->prompt); tl->print(tl->user, tl->buf); } }
int main ( int argc, char ** argv ) { cmd_set_arguments ( argc, argv ); if ( setlocale ( LC_ALL, "" ) == NULL ) { fprintf ( stderr, "Failed to set locale.\n" ); return EXIT_FAILURE; } /** * Collating. */ char *res = token_collate_key ( "€ Sign", FALSE ); TASSERT ( strcmp ( res, "€ sign" ) == 0 ); g_free ( res ); res = token_collate_key ( "éÉêèë Sign", FALSE ); TASSERT ( strcmp ( res, "ééêèë sign" ) == 0 ); g_free ( res ); res = token_collate_key ( "éÉêèë³ Sign", TRUE ); TASSERT ( strcmp ( res, "éÉêèë3 Sign" ) == 0 ); g_free ( res ); /** * Char function */ TASSERT ( helper_parse_char ( "\\n" ) == '\n' ); TASSERT ( helper_parse_char ( "\\a" ) == '\a' ); TASSERT ( helper_parse_char ( "\\b" ) == '\b' ); TASSERT ( helper_parse_char ( "\\t" ) == '\t' ); TASSERT ( helper_parse_char ( "\\v" ) == '\v' ); TASSERT ( helper_parse_char ( "\\f" ) == '\f' ); TASSERT ( helper_parse_char ( "\\r" ) == '\r' ); TASSERT ( helper_parse_char ( "\\\\" ) == '\\' ); TASSERT ( helper_parse_char ( "\\0" ) == 0 ); TASSERT ( helper_parse_char ( "\\x77" ) == 'w' ); TASSERT ( helper_parse_char ( "\\x0A" ) == '\n' ); /** * tokenize */ config.regex = FALSE; config.glob = FALSE; char ** retv = tokenize ( "aAp nOoT MieS 12", FALSE ); TASSERT ( retv[0] && strcmp ( retv[0], "aap" ) == 0 ); TASSERT ( retv[1] && strcmp ( retv[1], "noot" ) == 0 ); TASSERT ( retv[2] && strcmp ( retv[2], "mies" ) == 0 ); TASSERT ( retv[3] && strcmp ( retv[3], "12" ) == 0 ); tokenize_free ( retv ); retv = tokenize ( "blub³ bOb bEp bEE", TRUE ); TASSERT ( retv[0] && strcmp ( retv[0], "blub3" ) == 0 ); TASSERT ( retv[1] && strcmp ( retv[1], "bOb" ) == 0 ); TASSERT ( retv[2] && strcmp ( retv[2], "bEp" ) == 0 ); TASSERT ( retv[3] && strcmp ( retv[3], "bEE" ) == 0 ); tokenize_free ( retv ); TASSERT ( levenshtein ( "aap", "aap" ) == 0 ); TASSERT ( levenshtein ( "aap", "aap " ) == 1 ); TASSERT ( levenshtein ( "aap ", "aap" ) == 1 ); TASSERTE ( levenshtein ( "aap", "aap noot" ), 5 ); TASSERTE ( levenshtein ( "aap", "noot aap" ), 5 ); TASSERTE ( levenshtein ( "aap", "noot aap mies" ), 10 ); TASSERTE ( levenshtein ( "noot aap mies", "aap" ), 10 ); TASSERTE ( levenshtein ( "otp", "noot aap" ), 5 ); }
LexAnalyzer(std::string line): myLine(line) { tokenize(myLine, tokens); }
bool MSIFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv) { OBMol* pmol = pOb->CastAndClear<OBMol>(); if(pmol==NULL) return false; //Define some references so we can use the old parameter names istream &ifs = *pConv->GetInStream(); OBMol &mol = *pmol; const char* title = pConv->GetTitle(); char buffer[BUFF_SIZE]; stringstream errorMsg; if (!ifs) return false; // we're attempting to read past the end of the file if (!ifs.getline(buffer,BUFF_SIZE)) { obErrorLog.ThrowError(__FUNCTION__, "Problems reading an MSI file: Cannot read the first line.", obWarning); return(false); } if (!EQn(buffer, "# MSI CERIUS2 DataModel File", 28)) { obErrorLog.ThrowError(__FUNCTION__, "Problems reading an MSI file: The first line must contain the MSI header.", obWarning); return(false); } // "records" start with // (1 Model // .... // and end with // .... // ) unsigned int openParens = 0; // the count of "open parentheses" tags unsigned int startBondAtom, endBondAtom, bondOrder; bool atomRecord = false; bool bondRecord = false; OBAtom *atom; // OBBond *bond; vector<string> vs; const SpaceGroup *sg; bool setSpaceGroup = false; double x,y,z; vector3 translationVectors[3]; int numTranslationVectors = 0; mol.BeginModify(); while (ifs.getline(buffer,BUFF_SIZE)) { // model record if (strstr(buffer, "Model") != NULL) { openParens++; continue; } // atom record if (!bondRecord && strstr(buffer, "Atom") != NULL) { atomRecord = true; openParens++; continue; } if (strstr(buffer, "Bond") != NULL) { bondRecord = true; startBondAtom = endBondAtom = 0; bondOrder = 1; openParens++; continue; } /* (A I PeriodicType 100) (A D A3 (6.2380000000000004 0 0)) (A D B3 (0 6.9909999999999997 0)) (A D C3 (0 0 6.9960000000000004)) (A C SpaceGroup "63 5") */ if (strstr(buffer, "PeriodicType") != NULL) { ifs.getline(buffer,BUFF_SIZE); // next line should be translation vector tokenize(vs,buffer); while (vs.size() == 6) { x = atof((char*)vs[3].erase(0,1).c_str()); y = atof((char*)vs[4].c_str()); z = atof((char*)vs[5].c_str()); translationVectors[numTranslationVectors++].Set(x, y, z); if (!ifs.getline(buffer,BUFF_SIZE)) break; tokenize(vs,buffer); } } if (strstr(buffer, "SpaceGroup") != NULL) { tokenize(vs, buffer); if (vs.size() != 5) continue; // invalid space group setSpaceGroup = true; sg = SpaceGroup::GetSpaceGroup(vs[4]); // remove the initial " character } // atom information if (atomRecord) { if (strstr(buffer, "ACL") != NULL) { tokenize(vs, buffer); // size should be 5 -- need a test here if (vs.size() != 5) return false; // timvdm 18/06/2008 vs[3].erase(0,1); // "6 => remove the first " character unsigned int atomicNum = atoi(vs[3].c_str()); if (atomicNum == 0) atomicNum = 1; // hydrogen ? // valid element, so create the atom atom = mol.NewAtom(); atom->SetAtomicNum(atomicNum); continue; } else if (strstr(buffer, "XYZ") != NULL) { tokenize(vs, buffer); // size should be 6 -- need a test here if (vs.size() != 6) return false; // timvdm 18/06/2008 vs[3].erase(0,1); // remove ( character vs[5].erase(vs[5].length()-2, 2); // remove trailing )) characters atom->SetVector(atof(vs[3].c_str()), atof(vs[4].c_str()), atof(vs[5].c_str())); continue; } } // end of atom records // bond information if (bondRecord) { if (strstr(buffer, "Atom1") != NULL) { tokenize(vs, buffer); if (vs.size() < 4) return false; // timvdm 18/06/2008 vs[3].erase(vs[3].length()-1,1); startBondAtom = atoi(vs[3].c_str()); continue; } else if (strstr(buffer, "Atom2") != NULL) { tokenize(vs, buffer); if (vs.size() < 4) return false; // timvdm 18/06/2008 vs[3].erase(vs[3].length()-1,1); endBondAtom = atoi(vs[3].c_str()); continue; } else if (strstr(buffer, "Type") != NULL) { tokenize(vs, buffer); if (vs.size() < 4) return false; // timvdm 18/06/2008 vs[3].erase(vs[3].length()-1,1); bondOrder = atoi(vs[3].c_str()); if (bondOrder == 4) // triple bond? bondOrder = 3; else if (bondOrder == 8) // aromatic? bondOrder = 5; else if (bondOrder != 2) // 1 OK, 2 OK, others unknown bondOrder = 1; continue; } } // ending a "tag" -- a lone ")" on a line if (strstr(buffer,")") != NULL && strstr(buffer, "(") == NULL) { openParens--; if (atomRecord) { atomRecord = false; } if (bondRecord) { // Bond records appear to be questionable mol.AddBond(startBondAtom - 1, endBondAtom - 1, bondOrder); bondRecord = false; } if (openParens == 0) { ifs.getline(buffer, BUFF_SIZE); break; // closed this molecule } } } mol.EndModify(); // clean out any remaining blank lines while(ifs.peek() != EOF && ifs.good() && (ifs.peek() == '\n' || ifs.peek() == '\r')) ifs.getline(buffer,BUFF_SIZE); /* if (!pConv->IsOption("b",OBConversion::INOPTIONS)) mol.ConnectTheDots(); if (!pConv->IsOption("s",OBConversion::INOPTIONS) && !pConv->IsOption("b",OBConversion::INOPTIONS)) mol.PerceiveBondOrders(); */ if (numTranslationVectors > 0) { OBUnitCell* uc = new OBUnitCell; uc->SetData(translationVectors[0], translationVectors[1], translationVectors[2]); uc->SetOrigin(fileformatInput); if (setSpaceGroup) { uc->SetSpaceGroup(sg); } mol.SetData(uc); } return(true); }
TrafficPattern * TrafficPattern::New(string const & pattern, int nodes) { string pattern_name; string param_str; size_t left = pattern.find_first_of('('); if(left == string::npos) { pattern_name = pattern; } else { pattern_name = pattern.substr(0, left); size_t right = pattern.find_last_of(')'); if(right == string::npos) { param_str = pattern.substr(left+1); } else { param_str = pattern.substr(left+1, right-left-1); } } vector<string> params = tokenize(param_str); TrafficPattern * result = NULL; if(pattern_name == "bitcomp") { result = new BitCompTrafficPattern(nodes); } else if(pattern_name == "transpose") { result = new TransposeTrafficPattern(nodes); } else if(pattern_name == "bitrev") { result = new BitRevTrafficPattern(nodes); } else if(pattern_name == "shuffle") { result = new ShuffleTrafficPattern(nodes); } else if(pattern_name == "randperm") { int perm_seed = params.empty() ? 0 : atoi(params[0].c_str()); result = new RandomPermutationTrafficPattern(nodes, perm_seed); } else if(pattern_name == "uniform") { result = new UniformRandomTrafficPattern(nodes); } else if(pattern_name == "background") { vector<string> excludes_str = tokenize(params[0]); vector<int> excludes(excludes_str.size()); for(size_t i = 0; i < excludes.size(); ++i) { excludes[i] = atoi(excludes_str[i].c_str()); } result = new UniformBackgroundTrafficPattern(nodes, excludes); } else if(pattern_name == "diagonal") { result = new DiagonalTrafficPattern(nodes); } else if(pattern_name == "asymmetric") { result = new AsymmetricTrafficPattern(nodes); } else if(pattern_name == "taper64") { result = new Taper64TrafficPattern(nodes); } else if(pattern_name == "bad_dragon") { if(params.size() < 2) { cout << "Error: Missing parameters for dragonfly bad permutation traffic pattern: " << pattern << endl; exit(-1); } int k = atoi(params[0].c_str()); int n = atoi(params[1].c_str()); result = new BadPermDFlyTrafficPattern(nodes, k, n); } else if((pattern_name == "tornado") || (pattern_name == "neighbor") || (pattern_name == "badperm_yarc")) { if(params.size() < 3) { cout << "Error: Missing parameters for digit permutation traffic pattern: " << pattern << endl; exit(-1); } int k = atoi(params[0].c_str()); int n = atoi(params[1].c_str()); int xr = atoi(params[2].c_str()); if(pattern_name == "tornado") { result = new TornadoTrafficPattern(nodes, k, n, xr); } else if(pattern_name == "neighbor") { result = new NeighborTrafficPattern(nodes, k, n, xr); } else if(pattern_name == "badperm_yarc") { result = new BadPermYarcTrafficPattern(nodes, k, n, xr); } } else if(pattern_name == "hotspot") { if(params.empty()) { cout << "Error: Missing parameter for hotspot traffic pattern: " << pattern << endl; exit(-1); } vector<string> hotspots_str = tokenize(params[0]); vector<int> hotspots(hotspots_str.size()); for(size_t i = 0; i < hotspots.size(); ++i) { hotspots[i] = atoi(hotspots_str[i].c_str()); } vector<int> rates(hotspots.size(), 1); if(params.size() >= 2) { vector<string> rates_str = tokenize(params[1]); rates_str.resize(hotspots.size(), rates_str.back()); for(size_t i = 0; i < rates.size(); ++i) { rates[i] = atoi(rates_str[i].c_str()); } } result = new HotSpotTrafficPattern(nodes, hotspots, rates); } else { cout << "Error: Unknown traffic pattern: " << pattern << endl; exit(-1); } return result; }
static int cddbfilltoc(Toc *t) { int fd; int i; char *p, *q; Biobuf bin; Msf *m; char *f[10]; int nf; char *id, *categ; char gottrack[MTRACK]; int gottitle; fd = dial("tcp!freedb.freedb.org!888", 0, 0, 0); if(fd < 0) { fprint(2, "cannot dial: %r\n"); return -1; } Binit(&bin, fd, OREAD); if((p=Brdline(&bin, '\n')) == nil || atoi(p)/100 != 2) { died: close(fd); Bterm(&bin); fprint(2, "error talking to server\n"); if(p) { p[Blinelen(&bin)-1] = 0; fprint(2, "server says: %s\n", p); } return -1; } fprint(fd, "cddb hello gre plan9 9cd 1.0\r\n"); if((p = Brdline(&bin, '\n')) == nil || atoi(p)/100 != 2) goto died; fprint(fd, "cddb query %8.8lux %d", diskid(t), t->ntrack); DPRINT(2, "cddb query %8.8lux %d", diskid(t), t->ntrack); for(i=0; i<t->ntrack; i++) { m = &t->track[i].start; fprint(fd, " %d", (m->m*60+m->s)*75+m->f); DPRINT(2, " %d", (m->m*60+m->s)*75+m->f); } m = &t->track[t->ntrack-1].end; fprint(fd, " %d\r\n", m->m*60+m->s); DPRINT(2, " %d\r\n", m->m*60+m->s); if((p = Brdline(&bin, '\n')) == nil || atoi(p)/100 != 2) goto died; p[Blinelen(&bin)-1] = 0; DPRINT(2, "cddb: %s\n", p); nf = tokenize(p, f, nelem(f)); if(nf < 1) goto died; switch(atoi(f[0])) { case 200: /* exact match */ if(nf < 3) goto died; categ = f[1]; id = f[2]; break; case 211: /* close matches */ if((p = Brdline(&bin, '\n')) == nil) goto died; if(p[0] == '.') /* no close matches? */ goto died; p[Blinelen(&bin)-1] = '\0'; /* accept first match */ nf = tokenize(p, f, nelem(f)); if(nf < 2) goto died; categ = f[0]; id = f[1]; /* snarf rest of buffer */ while(p[0] != '.') { if((p = Brdline(&bin, '\n')) == nil) goto died; p[Blinelen(&bin)-1] = '\0'; DPRINT(2, "cddb: %s\n", p); } break; case 202: /* no match */ default: goto died; } /* fetch results for this cd */ fprint(fd, "cddb read %s %s\r\n", categ, id); memset(gottrack, 0, sizeof(gottrack)); gottitle = 0; do { if((p = Brdline(&bin, '\n')) == nil) goto died; q = p+Blinelen(&bin)-1; while(isspace(*q)) *q-- = 0; DPRINT(2, "cddb %s\n", p); if(strncmp(p, "DTITLE=", 7) == 0) { if (gottitle) append(&t->title, p + 7); else t->title = estrdup(p+7); gottitle = 1; } else if(strncmp(p, "TTITLE", 6) == 0 && isdigit(p[6])) { i = atoi(p+6); if(i < t->ntrack) { p += 6; while(isdigit(*p)) p++; if(*p == '=') p++; if (gottrack[i]) append(&t->track[i].title, p); else t->track[i].title = estrdup(p); gottrack[i] = 1; } } } while(*p != '.'); fprint(fd, "quit\r\n"); close(fd); Bterm(&bin); return 0; }
template <typename R, typename F> void tokenize(R const& range, F const& f) { tokenize(std::begin(range), std::end(range), f); }
int main(int argc, const char * argv[]) { // Method call to read input. //char *code = initialize(argv[1]); char *code = NULL; // Create pointer to input file. FILE* ifp = fopen(argv[1], "r"); // Return null if file could not be read. if (!ifp) { printf("Error: File not found.\n"); exit(1); } // Determine the length of the input file. fseek(ifp, 0, SEEK_END); int len = (int)ftell(ifp); fseek(ifp, 0, SEEK_SET); // Dynamically size string. code = (char*)calloc(len + 1, sizeof(char)); char *index = code; char c; // Continue appending to String until end of character is reached. if ( code ) { while ( (c = getc(ifp)) != EOF ) *index++ = c; *index = '\0'; } else printf("Error: Memory allocation failed.\n"); // printf("Input Code:\n%s\n\n",head); // bug printing //return head; // Method to remove comments. char *cleaned = clean(code, len); // Method call to parse tokens. token *lexemes = tokenize(cleaned); // Print to output files. print(lexemes); // Free allocated memory. free(cleaned); if ( !lexemes ) free(lexemes); return 0; }
void AssOverrideTag::ParseParameters(const wxString &text, AssOverrideTagProto::iterator proto_it) { Clear(); // Tokenize text, attempting to find all parameters std::vector<wxString> paramList = tokenize(text); size_t totalPars = paramList.size(); int parsFlag = 1 << (totalPars - 1); // Get optional parameters flag // vector (i)clip is the second clip proto_ittype in the list if ((Name == "\\clip" || Name == "\\iclip") && totalPars != 4) { ++proto_it; } unsigned curPar = 0; for (size_t n = 0; n < proto_it->params.size(); n++) { AssOverrideParamProto *curproto = &proto_it->params[n]; // Create parameter AssOverrideParameter *newparam = new AssOverrideParameter; newparam->classification = curproto->classification; Params.push_back(newparam); // Check if it's optional and not present if (!(curproto->optional & parsFlag) || curPar >= totalPars) { newparam->omitted = true; continue; } wxString curtok = paramList[curPar++]; if (curtok.empty()) { curPar++; continue; } wxChar firstChar = curtok[0]; bool auto4 = (firstChar == '!' || firstChar == '$' || firstChar == '%') && curproto->type != VARDATA_BLOCK; if (auto4) { newparam->Set(curtok); } else { switch (curproto->type) { case VARDATA_INT: { long temp; curtok.ToLong(&temp); newparam->Set<int>(temp); break; } case VARDATA_FLOAT: { double temp; curtok.ToDouble(&temp); newparam->Set(temp); break; } case VARDATA_TEXT: newparam->Set(curtok); break; case VARDATA_BOOL: { long temp; curtok.ToLong(&temp); newparam->Set<bool>(temp != 0); break; } case VARDATA_BLOCK: { AssDialogueBlockOverride *temp = new AssDialogueBlockOverride(curtok); temp->ParseTags(); newparam->Set(temp); break; } default: break; } } } }
/** * main function. Parses command-line arguments. */ int bowtie_build(int argc, const char **argv) { try { // Reset all global state, including getopt state opterr = optind = 1; resetOptions(); string infile; vector<string> infiles; string outfile; parseOptions(argc, argv); argv0 = argv[0]; if(showVersion) { cout << argv0 << " version " << BOWTIE_VERSION << endl; if(sizeof(void*) == 4) { cout << "32-bit" << endl; } else if(sizeof(void*) == 8) { cout << "64-bit" << endl; } else { cout << "Neither 32- nor 64-bit: sizeof(void*) = " << sizeof(void*) << endl; } cout << "Built on " << BUILD_HOST << endl; cout << BUILD_TIME << endl; cout << "Compiler: " << COMPILER_VERSION << endl; cout << "Options: " << COMPILER_OPTIONS << endl; cout << "Sizeof {int, long, long long, void*, size_t, off_t}: {" << sizeof(int) << ", " << sizeof(long) << ", " << sizeof(long long) << ", " << sizeof(void *) << ", " << sizeof(size_t) << ", " << sizeof(off_t) << "}" << endl; return 0; } // Get input filename if(optind >= argc) { cerr << "No input sequence or sequence file specified!" << endl; printUsage(cerr); return 1; } infile = argv[optind++]; // Get output filename if(optind >= argc) { cerr << "No output file specified!" << endl; printUsage(cerr); return 1; } outfile = argv[optind++]; tokenize(infile, ",", infiles); if(infiles.size() < 1) { cerr << "Tokenized input file list was empty!" << endl; printUsage(cerr); return 1; } // Optionally summarize if(verbose) { cout << "Settings:" << endl << " Output files: \"" << outfile << ".*.ebwt\"" << endl << " Line rate: " << lineRate << " (line is " << (1<<lineRate) << " bytes)" << endl << " Lines per side: " << linesPerSide << " (side is " << ((1<<lineRate)*linesPerSide) << " bytes)" << endl << " Offset rate: " << offRate << " (one in " << (1<<offRate) << ")" << endl << " FTable chars: " << ftabChars << endl << " Strings: " << (packed? "packed" : "unpacked") << endl ; if(bmax == 0xffffffff) { cout << " Max bucket size: default" << endl; } else { cout << " Max bucket size: " << bmax << endl; } if(bmaxMultSqrt == 0xffffffff) { cout << " Max bucket size, sqrt multiplier: default" << endl; } else { cout << " Max bucket size, sqrt multiplier: " << bmaxMultSqrt << endl; } if(bmaxDivN == 0xffffffff) { cout << " Max bucket size, len divisor: default" << endl; } else { cout << " Max bucket size, len divisor: " << bmaxDivN << endl; } cout << " Difference-cover sample period: " << dcv << endl; cout << " Endianness: " << (bigEndian? "big":"little") << endl << " Actual local endianness: " << (currentlyBigEndian()? "big":"little") << endl << " Sanity checking: " << (sanityCheck? "enabled":"disabled") << endl; #ifdef NDEBUG cout << " Assertions: disabled" << endl; #else cout << " Assertions: enabled" << endl; #endif cout << " Random seed: " << seed << endl; cout << " Sizeofs: void*:" << sizeof(void*) << ", int:" << sizeof(int) << ", long:" << sizeof(long) << ", size_t:" << sizeof(size_t) << endl; cout << "Input files DNA, " << file_format_names[format] << ":" << endl; for(size_t i = 0; i < infiles.size(); i++) { cout << " " << infiles[i] << endl; } } // Seed random number generator srand(seed); { Timer timer(cout, "Total time for call to driver() for forward index: ", verbose); if(!packed) { try { driver<String<Dna, Alloc<> > >(infile, infiles, outfile); } catch(bad_alloc& e) { if(autoMem) { cerr << "Switching to a packed string representation." << endl; packed = true; } else { throw e; } } } if(packed) { driver<String<Dna, Packed<Alloc<> > > >(infile, infiles, outfile); } } if(doubleEbwt) { srand(seed); Timer timer(cout, "Total time for backward call to driver() for mirror index: ", verbose); if(!packed) { try { driver<String<Dna, Alloc<> > >(infile, infiles, outfile + ".rev", true); } catch(bad_alloc& e) { if(autoMem) { cerr << "Switching to a packed string representation." << endl; packed = true; } else { throw e; } } } if(packed) { driver<String<Dna, Packed<Alloc<> > > >(infile, infiles, outfile + ".rev", true); } } return 0; } catch(std::exception& e) { cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; return 1; } catch(int e) { if(e != 0) { cerr << "Command: "; for(int i = 0; i < argc; i++) cerr << argv[i] << " "; cerr << endl; } return e; } }
static BOOL CALLBACK addDlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { // only one add dialog at a time! static CScreenInfo* info = NULL; switch (message) { case WM_INITDIALOG: { info = (CScreenInfo*)lParam; // set title CString title; if (info->m_screen.empty()) { title = getString(IDS_ADD_SCREEN); } else { title = CStringUtil::format( getString(IDS_EDIT_SCREEN).c_str(), info->m_screen.c_str()); } SendMessage(hwnd, WM_SETTEXT, 0, (LPARAM)title.c_str()); // fill in screen name HWND child = getItem(hwnd, IDC_ADD_SCREEN_NAME_EDIT); SendMessage(child, WM_SETTEXT, 0, (LPARAM)info->m_screen.c_str()); // fill in aliases CString aliases; for (CStringList::const_iterator index = info->m_aliases.begin(); index != info->m_aliases.end(); ++index) { if (!aliases.empty()) { aliases += "\r\n"; } aliases += *index; } child = getItem(hwnd, IDC_ADD_ALIASES_EDIT); SendMessage(child, WM_SETTEXT, 0, (LPARAM)aliases.c_str()); // set options CConfig::CScreenOptions::const_iterator index; child = getItem(hwnd, IDC_ADD_HD_CAPS_CHECK); index = info->m_options.find(kOptionHalfDuplexCapsLock); setItemChecked(child, (index != info->m_options.end() && index->second != 0)); child = getItem(hwnd, IDC_ADD_HD_NUM_CHECK); index = info->m_options.find(kOptionHalfDuplexNumLock); setItemChecked(child, (index != info->m_options.end() && index->second != 0)); child = getItem(hwnd, IDC_ADD_HD_SCROLL_CHECK); index = info->m_options.find(kOptionHalfDuplexScrollLock); setItemChecked(child, (index != info->m_options.end() && index->second != 0)); // modifier options for (UInt32 i = 0; i < sizeof(s_modifiers) / sizeof(s_modifiers[0]); ++i) { child = getItem(hwnd, s_modifiers[i].m_ctrlID); // fill in options for (UInt32 j = 0; j < sizeof(s_modifiers) / sizeof(s_modifiers[0]); ++j) { SendMessage(child, CB_ADDSTRING, 0, (LPARAM)s_modifiers[j].m_name); } // choose current value index = info->m_options.find(s_modifiers[i].m_optionID); KeyModifierID id = s_modifiers[i].m_modifierID; if (index != info->m_options.end()) { id = index->second; } SendMessage(child, CB_SETCURSEL, id - baseModifier, 0); } // dead corners UInt32 corners = 0; index = info->m_options.find(kOptionScreenSwitchCorners); if (index != info->m_options.end()) { corners = index->second; } child = getItem(hwnd, IDC_ADD_DC_TOP_LEFT); setItemChecked(child, (corners & kTopLeftMask) != 0); child = getItem(hwnd, IDC_ADD_DC_TOP_RIGHT); setItemChecked(child, (corners & kTopRightMask) != 0); child = getItem(hwnd, IDC_ADD_DC_BOTTOM_LEFT); setItemChecked(child, (corners & kBottomLeftMask) != 0); child = getItem(hwnd, IDC_ADD_DC_BOTTOM_RIGHT); setItemChecked(child, (corners & kBottomRightMask) != 0); index = info->m_options.find(kOptionScreenSwitchCornerSize); SInt32 size = 0; if (index != info->m_options.end()) { size = index->second; } char buffer[20]; sprintf(buffer, "%d", size); child = getItem(hwnd, IDC_ADD_DC_SIZE); SendMessage(child, WM_SETTEXT, 0, (LPARAM)buffer); return TRUE; } case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: { CString newName; CStringList newAliases; // extract name and aliases HWND child = getItem(hwnd, IDC_ADD_SCREEN_NAME_EDIT); newName = getWindowText(child); child = getItem(hwnd, IDC_ADD_ALIASES_EDIT); tokenize(newAliases, getWindowText(child)); // name must be valid if (!ARG->m_config.isValidScreenName(newName)) { showError(hwnd, CStringUtil::format( getString(IDS_INVALID_SCREEN_NAME).c_str(), newName.c_str())); return TRUE; } // aliases must be valid for (CStringList::const_iterator index = newAliases.begin(); index != newAliases.end(); ++index) { if (!ARG->m_config.isValidScreenName(*index)) { showError(hwnd, CStringUtil::format( getString(IDS_INVALID_SCREEN_NAME).c_str(), index->c_str())); return TRUE; } } // new name may not be in the new alias list if (isNameInList(newAliases, newName)) { showError(hwnd, CStringUtil::format( getString(IDS_SCREEN_NAME_IS_ALIAS).c_str(), newName.c_str())); return TRUE; } // name must not exist in config but allow same name. also // allow name if it exists in the old alias list but not the // new one. if (ARG->m_config.isScreen(newName) && !CStringUtil::CaselessCmp::equal(newName, info->m_screen) && !isNameInList(info->m_aliases, newName)) { showError(hwnd, CStringUtil::format( getString(IDS_DUPLICATE_SCREEN_NAME).c_str(), newName.c_str())); return TRUE; } // aliases must not exist in config but allow same aliases and // allow an alias to be the old name. for (CStringList::const_iterator index = newAliases.begin(); index != newAliases.end(); ++index) { if (ARG->m_config.isScreen(*index) && !CStringUtil::CaselessCmp::equal(*index, info->m_screen) && !isNameInList(info->m_aliases, *index)) { showError(hwnd, CStringUtil::format( getString(IDS_DUPLICATE_SCREEN_NAME).c_str(), index->c_str())); return TRUE; } } // dead corner size must be non-negative child = getItem(hwnd, IDC_ADD_DC_SIZE); CString valueString = getWindowText(child); int cornerSize = atoi(valueString.c_str()); if (cornerSize < 0) { showError(hwnd, CStringUtil::format( getString(IDS_INVALID_CORNER_SIZE).c_str(), valueString.c_str())); SetFocus(child); return TRUE; } // save name data info->m_screen = newName; info->m_aliases = newAliases; // save options child = getItem(hwnd, IDC_ADD_HD_CAPS_CHECK); if (isItemChecked(child)) { info->m_options[kOptionHalfDuplexCapsLock] = 1; } else { info->m_options.erase(kOptionHalfDuplexCapsLock); } child = getItem(hwnd, IDC_ADD_HD_NUM_CHECK); if (isItemChecked(child)) { info->m_options[kOptionHalfDuplexNumLock] = 1; } else { info->m_options.erase(kOptionHalfDuplexNumLock); } child = getItem(hwnd, IDC_ADD_HD_SCROLL_CHECK); if (isItemChecked(child)) { info->m_options[kOptionHalfDuplexScrollLock] = 1; } else { info->m_options.erase(kOptionHalfDuplexScrollLock); } // save modifier options for (UInt32 i = 0; i < sizeof(s_modifiers) / sizeof(s_modifiers[0]); ++i) { child = getItem(hwnd, s_modifiers[i].m_ctrlID); KeyModifierID id = static_cast<KeyModifierID>( SendMessage(child, CB_GETCURSEL, 0, 0) + baseModifier); if (id != s_modifiers[i].m_modifierID) { info->m_options[s_modifiers[i].m_optionID] = id; } else { info->m_options.erase(s_modifiers[i].m_optionID); } } // save dead corner options UInt32 corners = 0; if (isItemChecked(getItem(hwnd, IDC_ADD_DC_TOP_LEFT))) { corners |= kTopLeftMask; } if (isItemChecked(getItem(hwnd, IDC_ADD_DC_TOP_RIGHT))) { corners |= kTopRightMask; } if (isItemChecked(getItem(hwnd, IDC_ADD_DC_BOTTOM_LEFT))) { corners |= kBottomLeftMask; } if (isItemChecked(getItem(hwnd, IDC_ADD_DC_BOTTOM_RIGHT))) { corners |= kBottomRightMask; } info->m_options[kOptionScreenSwitchCorners] = corners; info->m_options[kOptionScreenSwitchCornerSize] = cornerSize; // success EndDialog(hwnd, 1); info = NULL; return TRUE; } case IDCANCEL: EndDialog(hwnd, 0); info = NULL; return TRUE; } default: break; } return FALSE; }
SWIGEXPORT void JNICALL Java_hu_rilmta_gate_tokenizers_dummyctokenizer_DummyCTokenizerWrapperJNI_tokenize(JNIEnv *jenv, jclass jcls, jstring jarg1, jint jarg2, jint jarg3, jlong jarg4, jlong jarg5, jintArray jarg6, jlong jarg7, jlong jarg8, jintArray jarg9) { char *arg1 = (char *) 0 ; int arg2 ; int arg3 ; int *arg4 = (int *) 0 ; int *arg5 = (int *) 0 ; int *arg6 = (int *) 0 ; int *arg7 = (int *) 0 ; int *arg8 = (int *) 0 ; int *arg9 = (int *) 0 ; int temp6 ; int temp9 ; (void)jenv; (void)jcls; arg1 = 0; if (jarg1) { arg1 = (char *)(*jenv)->GetStringUTFChars(jenv, jarg1, 0); if (!arg1) return ; } arg2 = (int)jarg2; arg3 = (int)jarg3; arg4 = *(int **)&jarg4; arg5 = *(int **)&jarg5; { if (!jarg6) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null"); return ; } if ((*jenv)->GetArrayLength(jenv, jarg6) == 0) { SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element"); return ; } temp6 = (int)0; arg6 = &temp6; } arg7 = *(int **)&jarg7; arg8 = *(int **)&jarg8; { if (!jarg9) { SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "array null"); return ; } if ((*jenv)->GetArrayLength(jenv, jarg9) == 0) { SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array must contain at least 1 element"); return ; } temp9 = (int)0; arg9 = &temp9; } tokenize((char const *)arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); { jint jvalue = (jint)temp6; (*jenv)->SetIntArrayRegion(jenv, jarg6, 0, 1, &jvalue); } { jint jvalue = (jint)temp9; (*jenv)->SetIntArrayRegion(jenv, jarg9, 0, 1, &jvalue); } if (arg1) (*jenv)->ReleaseStringUTFChars(jenv, jarg1, (const char *)arg1); }
gint read_dmol_frame(FILE *fp, struct model_pak *model) { gint i, num_tokens; gchar *line, **buff; struct core_pak *core; g_assert(fp != NULL); line = file_read_line(fp); while (line) { /* read cell vectors */ if (g_ascii_strncasecmp(line, "$cell", 5) == 0 && model) { for (i=0 ; i<3 ; i++) { g_free(line); line = file_read_line(fp); buff = tokenize(line, &num_tokens); if (num_tokens > 2) { model->latmat[i] = AU2ANG*str_to_float(*(buff)); model->latmat[i+3] = AU2ANG*str_to_float(*(buff+1)); model->latmat[i+6] = AU2ANG*str_to_float(*(buff+2)); } g_strfreev(buff); } model->periodic = 3; model->construct_pbc = TRUE; } /* read coordinates */ if (g_ascii_strncasecmp(line, "$coord", 5) == 0 && model) { g_free(line); line = file_read_line(fp); buff = tokenize(line, &num_tokens); while (num_tokens > 3) { if (elem_symbol_test(*buff)) { core = new_core(*buff, model); model->cores = g_slist_prepend(model->cores, core); core->x[0] = AU2ANG*str_to_float(*(buff+1)); core->x[1] = AU2ANG*str_to_float(*(buff+2)); core->x[2] = AU2ANG*str_to_float(*(buff+3)); } g_free(line); line = file_read_line(fp); g_strfreev(buff); buff = tokenize(line, &num_tokens); } g_strfreev(buff); model->fractional = FALSE; } /* terminate frame read */ if (g_ascii_strncasecmp(line, "$end", 4) == 0) return(0); g_free(line); line = file_read_line(fp); } return(1); }
void ThermTrace::read_floorplan_mapping() { GI(input_file_[0]!=0,!mapping.empty()); // first call read_sesc_variable const char *flpSec = SescConf->getCharPtr("","floorplan"); size_t min = SescConf->getRecordMin(flpSec,"blockDescr"); size_t max = SescConf->getRecordMax(flpSec,"blockDescr"); // Floor plan parameters for(size_t id=min;id<=max;id++) { if (!SescConf->checkCharPtr(flpSec,"blockDescr", id)) { MSG("There is a WHOLE on the floorplan. This can create problems blockDescr[%d]", id); exit(-1); continue; } const char *blockDescr = SescConf->getCharPtr(flpSec,"blockDescr", id); TokenVectorType descr; tokenize(blockDescr, descr); FLPUnit *xflp = new FLPUnit(strdup(descr[0])); xflp->id = id; xflp->area = atof(descr[1])*atof(descr[2]); xflp->x = atof(descr[3]); xflp->y = atof(descr[4]); xflp->delta_x = atof(descr[1]); xflp->delta_y = atof(descr[2]); const char *blockMatch = SescConf->getCharPtr(flpSec,"blockMatch", id); tokenize(blockMatch, xflp->match); flp.push_back(xflp); } // Find mappings between variables and flp for(size_t id=0;id<flp.size();id++) { for(size_t i=0; i<flp[id]->match.size(); i++) { for(size_t j=0; j<mapping.size(); j++) { if (grep(mapping[j].name, flp[id]->match[i])) { #ifdef DEBUG MSG("mapping[%d].map[%d]=%d (%s -> %s)", j, mapping[j].map.size(), id, flp[id]->match[i], mapping[j].name); #endif I(id < flp.size()); flp[id]->units++; I(j < mapping.size()); mapping[j].area += flp[id]->area; mapping[j].map.push_back(id); } } } } for(size_t i=0;i<mapping.size();i++) { for(size_t j=0; j<mapping[i].map.size(); j++) { float ratio = flp[mapping[i].map[j]]->area/mapping[i].area; mapping[i].ratio.push_back(ratio); } } for(size_t j=0; j<mapping.size(); j++) { I(mapping[j].map.size() == mapping[j].ratio.size()); if (mapping[j].map.empty()) { MSG("Error: sesc variable %s [%d] does not update any block", mapping[j].name, j); exit(3); } } }
int main(int argc, char *argv[]) { //Initialize the shell init_shell(); int numofpipes[MAXCMD]; //Initialize jobs array init_jobsarray(); //Holds the command char wholecommand[MAXNUM]; char dupwholecommand[MAXNUM]; char *cmdarr[MAXCMD][MAXOP]; //The rows hold commands separated by ; //while the columns hold the command and its options separated by " " or \t char *pipecmdarr[MAXCMD][MAXCMD][MAXOP]; char maincmd[MAXNUM]; //For prompt char username[MAXNUM],sysname[MAXNUM],cwdir[MAXNUM]; char homedir[MAXNUM]; getcwd(homedir,MAXNUM); char duphomedir[MAXNUM]; duphomedir[0] = '\0'; strcat(duphomedir,homedir); //For tokenizing char *str1 = NULL; char *token = NULL; //Counters int i; //Initializing background process array for(i=0; i<(MAXNUM*MAXOP); i++) { bgrounds[i].used = 0; } //Initializing ends //Initialize to NULL initarray(cmdarr); char *hdir[MAXNUM]; //Tokenize home directory tokenize(str1,hdir,token,duphomedir); //Tokenize home directory done while(1) { if(signal(SIGINT,signal_handler)==SIG_ERR) perror("Signal not caught!!"); if(signal(SIGCHLD,signal_handler)==SIG_ERR) perror("Signal not caught!!"); for(i=0; i<MAXCMD; i++) numofpipes[i] = 0; rectifyjobsarray(); //Printing message on background process completion for(i=0; i<(MAXNUM*MAXOP); i++) { if(bgrounds[i].used == 0) continue; bgrounds[i].used = 0; if(bgrounds[i].status == 1) { //printf("Process %s with pid %d terminated normally\n",bgrounds[i].name,bgrounds[i].pid); } else { //printf("Process %s with pid %d terminated with status %d\n",bgrounds[i].name,bgrounds[i].pid,bgrounds[i].status); } } //Renitializing background process array for(i=0; i<(MAXNUM*MAXOP); i++) { bgrounds[i].used = 0; } //Renitializing ends //Initialize to NULL initarray(cmdarr); initpipecmd(pipecmdarr); //For prompt username[0] = '\0'; cwdir[0] = '\0'; strcat(username,getlogin()); gethostname(sysname,MAXNUM); getcwd(cwdir,MAXNUM); char dupcwdir[MAXNUM]; dupcwdir[0] = '\0'; strcat(dupcwdir,cwdir); directorysettings(cwdir,homedir,dupcwdir,hdir); //Prompt settings done //Take commands printf("<%s@%s:%s>",username,sysname,cwdir); wholecommand[0] = '\0'; dupwholecommand[0] = '\0'; readLine(wholecommand); wholecommand[strlen(wholecommand)-1]='\0'; strcpy(dupwholecommand,wholecommand); //Done taking commands //Tokenize maintokenize(cmdarr,dupwholecommand); //tokentest(cmdarr); pipetokenize(cmdarr,pipecmdarr,numofpipes); //pipetokenizetest(cmdarr,pipecmdarr,numofpipes); //exit(EXIT_SUCCESS); //continue; //Tokenize done //Executing each ; separated command for(i = 0; i< MAXCMD; i++) { if(cmdarr[i][0] == NULL) continue; maincmd[0] = '\0'; strcat(maincmd,cmdarr[i][0]); strcpy(infile,"\0"); strcpy(outfile,"\0"); if(numofpipes[i] != 0) { //Execute piped commands pipesexecute(cmdarr, pipecmdarr, numofpipes, i); continue; } if((strcmp(maincmd,"echo") == 0) || (strcmp(maincmd,"pwd") == 0) || (strcmp(maincmd,"cd") == 0)\ || (strcmp(maincmd,"clear") == 0) || (strcmp(maincmd,"quit") == 0) || (strcmp(maincmd,"pinfo") == 0) || strcmp(maincmd,"jobs") == 0 || strcmp(maincmd,"overkill") == 0 || strcmp(maincmd,"kjob") == 0 || strcmp(maincmd,"fg") == 0 ) { int dupstdout = dup(1); int dupstdin = dup(0); if(checkinfile(cmdarr,i) == 1) { if(strcmp(infile,"\0") != 0) { int in=open(infile,O_RDONLY); dup2(in,0); close(in); } } int outretval = checkoutfile(cmdarr,i); if(outretval == 1 || outretval == 2) { if(strcmp(outfile,"\0") != 0) { if(outretval == 1) { int out=open(outfile,O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); dup2(out,1); close(out); } else { if(fopen(outfile,"r") == NULL) { int out=open(outfile,O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); dup2(out,1); close(out); } else { int out=open(outfile,O_WRONLY | O_APPEND, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); dup2(out,1); close(out); } } } } //echo execution if(strcmp (maincmd,"echo") == 0) { exececho(wholecommand,cmdarr,i); } //echo done //pwd execution if(strcmp (maincmd,"pwd") == 0) { execpwd(); } //pwd done //chdir execution if(strcmp (maincmd,"cd") == 0) { execcd(cmdarr,homedir,i); } //chdir done //clear execution if(strcmp (maincmd,"clear") == 0) { printf("\e[1;1H\e[2J"); } //clear done //terminal quit if(strcmp (maincmd,"quit") == 0) { exit(EXIT_SUCCESS); } //terminal quit done //jobs if(strcmp (maincmd,"jobs") == 0) { execjobs(); } //jobs done //overkill if(strcmp (maincmd,"overkill") == 0) { execoverkill(); } //overkill done //kjob if(strcmp (maincmd,"kjob") == 0) { execkjob(cmdarr,i); } //kjob done //fg if(strcmp (maincmd,"fg") == 0) { execfg(cmdarr,i); } //fg done //pinfo if(strcmp (maincmd,"pinfo") == 0) { pid_t proid; int flag = 0; if(cmdarr[i][1] == NULL) //pinfo of shell proid = getpid(); else { //pinfo of given pid char temps[MAXNUM]; strcpy(temps,cmdarr[i][1]); proid = atoi(temps); if(kill(proid,0) == (-1)) { printf("No such process exists\n"); continue; } flag = 1; } getpinfo(proid, flag, homedir); } //pinfo done dup2(dupstdin,0); dup2(dupstdout,1); } else {
/* * docmd - decode the command line and execute a command */ static void docmd( const char *cmdline ) { char *tokens[1+MAXARGS+MOREARGS+2]; struct parse pcmd; int ntok; int i, ti; int rval; struct xcmd *xcmd; ai_fam_templ = ai_fam_default; /* * Tokenize the command line. If nothing on it, return. */ if (strlen(cmdline) >= MAXLINE) { fprintf(stderr, "***Command ignored, more than %d characters:\n%s\n", MAXLINE - 1, cmdline); return; } tokenize(cmdline, tokens, &ntok); if (ntok == 0) return; /* * Find the appropriate command description. */ i = findcmd(tokens[0], builtins, opcmds, &xcmd); if (i == 0) { (void) fprintf(stderr, "***Command `%s' unknown\n", tokens[0]); return; } else if (i >= 2) { (void) fprintf(stderr, "***Command `%s' ambiguous\n", tokens[0]); return; } /* * Save the keyword, then walk through the arguments, interpreting * as we go. */ pcmd.keyword = tokens[0]; pcmd.nargs = 0; ti = 1; for (i = 0; i < MAXARGS && xcmd->arg[i] != NO;) { if ((i+ti) >= ntok) { if (!(xcmd->arg[i] & OPT)) { printusage(xcmd, stderr); return; } break; } if ((xcmd->arg[i] & OPT) && (*tokens[i+ti] == '>')) break; rval = getarg(tokens[i+ti], (int)xcmd->arg[i], &pcmd.argval[i]); if (rval == -1) { ti++; continue; } if (rval == 0) return; pcmd.nargs++; i++; } /* Any extra args are assumed to be "OPT|NTP_STR". */ for ( ; i < MAXARGS + MOREARGS;) { if ((i+ti) >= ntok) break; rval = getarg(tokens[i+ti], (int)(OPT|NTP_STR), &pcmd.argval[i]); if (rval == -1) { ti++; continue; } if (rval == 0) return; pcmd.nargs++; i++; } i += ti; if (i < ntok && *tokens[i] == '>') { char *fname; if (*(tokens[i]+1) != '\0') fname = tokens[i]+1; else if ((i+1) < ntok) fname = tokens[i+1]; else { (void) fprintf(stderr, "***No file for redirect\n"); return; } current_output = fopen(fname, "w"); if (current_output == NULL) { (void) fprintf(stderr, "***Error opening %s: ", fname); perror(""); return; } } else { current_output = stdout; } if (interactive && setjmp(interrupt_buf)) { return; } else { jump = 1; (xcmd->handler)(&pcmd, current_output); jump = 0; if (current_output != stdout) (void) fclose(current_output); current_output = NULL; } }
bool DoRefresh() { char cmdline[1024]; sprintf(cmdline, "xearth -bmp"); strcat(cmdline, Settings.proj ? " -proj merc" : " -proj orth"); if (Settings.pos.type != Position::_default) { strcat(cmdline, " -pos"); switch (Settings.pos.type) { case Position::fixed: sprintf(&cmdline[strlen(cmdline)], " fixed,%f,%f", Settings.pos.latitude, Settings.pos.longitude); break; case Position::sunrel: sprintf(&cmdline[strlen(cmdline)], " sunrel,%f,%f", Settings.pos.rlatitude, Settings.pos.rlongitude); break; case Position::orbit: sprintf(&cmdline[strlen(cmdline)], " orbit,%f,%f", Settings.pos.period, Settings.pos.inclination); break; case Position::random: strcat(cmdline, " random"); break; } } if (Settings.rot != 0) { sprintf(&cmdline[strlen(cmdline)], " -rot %f", Settings.rot); } if (Settings.sunpos.type != Position::_default) { strcat(cmdline, " -sunpos"); switch (Settings.sunpos.type) { case Position::fixed: sprintf(&cmdline[strlen(cmdline)], " %f,%f", Settings.sunpos.latitude, Settings.sunpos.longitude); break; } } if (Settings.mag != 1) { sprintf(&cmdline[strlen(cmdline)], " -mag %f", Settings.mag); } strcat(cmdline, " -size"); if (Settings.size.cx == 0 || Settings.size.cy == 0) { sprintf(&cmdline[strlen(cmdline)], " %d,%d", GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); } else { sprintf(&cmdline[strlen(cmdline)], " %d,%d", Settings.size.cx, Settings.size.cy); } if (Settings.shift.x != 0 || Settings.shift.y != 0) { sprintf(&cmdline[strlen(cmdline)], " -shift %d,%d", Settings.shift.x, Settings.shift.y); } strcat(cmdline, Settings.shade ? " -shade" : " -noshade"); strcat(cmdline, Settings.label ? " -label" : " -nolabel"); if (Settings.label) { sprintf(&cmdline[strlen(cmdline)], " -labelpos %d", Settings.labelpos); } strcat(cmdline, Settings.markers ? " -markers" : " -nomarkers"); // markerfile strcat(cmdline, Settings.stars ? " -stars" : " -nostars"); if (Settings.stars) { sprintf(&cmdline[strlen(cmdline)], " -starfreq %f", Settings.starfreq); if (Settings.bigstars > 0) { sprintf(&cmdline[strlen(cmdline)], " -bigstars %d", Settings.bigstars); } } strcat(cmdline, Settings.grid ? " -grid" : " -nogrid"); if (Settings.grid) { sprintf(&cmdline[strlen(cmdline)], " -grid1 %d", Settings.grid1); sprintf(&cmdline[strlen(cmdline)], " -grid2 %d", Settings.grid2); } if (Settings.shade) { sprintf(&cmdline[strlen(cmdline)], " -day %d", Settings.day); sprintf(&cmdline[strlen(cmdline)], " -night %d", Settings.night); sprintf(&cmdline[strlen(cmdline)], " -term %d", Settings.term); } sprintf(&cmdline[strlen(cmdline)], " -gamma %f", Settings.gamma); if (Settings.timewarp != 1) { sprintf(&cmdline[strlen(cmdline)], " -timewarp %f", Settings.timewarp); } if (Settings.time) { sprintf(&cmdline[strlen(cmdline)], " -time %d", Settings.time); } int argc; char **argv = tokenize(cmdline, &argc); int err = setjmp(fataljmp); if (err == 0) { main(argc, argv); } else { const char *msg = reinterpret_cast<const char *>(err); return false; } free(argv); return true; }
gint read_nwout_block(FILE *fp, struct model_pak *model) { gint num_tokens; gchar **buff, line[LINELEN], *text; GString *gstring; GSList *clist; struct core_pak *core; clist = model->cores; /* skip until get a 1 in first column for first coordinate */ if (fgetline(fp, line)) return(1); while (g_ascii_strncasecmp(line, " 1", 5) != 0) { if (fgetline(fp, line)) return(1); } buff = tokenize(line, &num_tokens); while (num_tokens > 0) { if (clist) { core = clist->data; clist = g_slist_next(clist); } else { core = new_core(*(buff+1), model); model->cores = g_slist_append(model->cores, core); } core->x[0] = str_to_float(*(buff+3)); core->x[1] = str_to_float(*(buff+4)); core->x[2] = str_to_float(*(buff+5)); #if DEBUG_READ_NWOUT P3VEC("coords: ", core->x); #endif /* get next line */ g_strfreev(buff); if (fgetline(fp, line)) return(2); buff = tokenize(line, &num_tokens); } g_strfreev(buff); /* read until get the details of the current optimisation step */ while (g_ascii_strncasecmp(line, "@", 1) != 0) { if (fgetline(fp, line)) return(0); } buff = tokenize(line, &num_tokens); while (g_ascii_strncasecmp(line, "@", 1) == 0) { if (g_ascii_isdigit(buff[1][0])) { text = format_value_and_units(*(buff+2), 5); gstring = g_string_new(text); g_free(text); g_string_append(gstring, " a.u."); property_add_ranked(3, "Energy", gstring->str, model); g_string_free(gstring, TRUE); text = format_value_and_units(*(buff+5), 5); gstring = g_string_new(text); g_free(text); g_string_append(gstring, " a.u./A"); property_add_ranked(4, "RMS Gradient", gstring->str, model); g_string_free(gstring, TRUE); } /* get next line */ g_strfreev(buff); if (fgetline(fp, line)) return(2); buff = tokenize(line, &num_tokens); } return(0); }
void xml_parse_atom(const gchar **names, const gchar **values) { gint i, n; gchar **buff; g_assert(xml_model != NULL); /* init structure */ if (!xml_core) { xml_core = new_core("X", xml_model); xml_model->cores = g_slist_prepend(xml_model->cores, xml_core); } /* process attributes (if any) */ i=0; while (*(names+i)) { if (g_ascii_strncasecmp(*(names+i), "elementType\0", 12) == 0) { /* FIXME - potential overflow bug here, since label is an array */ g_free(xml_core->atom_label); xml_core->atom_label = g_strdup(*(values+i)); core_init(xml_core->atom_label, xml_core, xml_model); } if (g_ascii_strncasecmp(*(names+i), "xyzf", 4) == 0) { buff = tokenize(*(values+i), &n); if (n > 2) { xml_core->x[0] = str_to_float(*(buff+0)); xml_core->x[1] = str_to_float(*(buff+1)); xml_core->x[2] = str_to_float(*(buff+2)); xml_model->fractional = TRUE; } } if (g_ascii_strncasecmp(*(names+i), "xf", 2) == 0) { xml_core->x[0] = str_to_float(*(values+i)); /* FIXME - inefficient to repeat this for all atoms */ /* but may be necessary if every atom is allowed to be cart or fract */ xml_model->fractional = TRUE; } if (g_ascii_strncasecmp(*(names+i), "x3", 2) == 0) { xml_core->x[0] = str_to_float(*(values+i)); /* FIXME - inefficient to repeat this for all atoms */ /* but may be necessary if every atom is allowed to be cart or fract */ xml_model->fractional = FALSE; } if (g_ascii_strncasecmp(*(names+i), "yf", 2) == 0 || g_ascii_strncasecmp(*(names+i), "y3", 2) == 0) { xml_core->x[1] = str_to_float(*(values+i)); } if (g_ascii_strncasecmp(*(names+i), "zf", 2) == 0 || g_ascii_strncasecmp(*(names+i), "z3", 2) == 0) { xml_core->x[2] = str_to_float(*(values+i)); } i++; } }
//--------------------------------------------------------- bool ofXml::setAttribute(const string& path, const string& value) { string attributeName, pathToAttribute; bool hasPath = false; // you can pass either /node[@attr] or just attr if(path.find("[@") != string::npos) { size_t attrBegin = path.find("[@"); size_t start = attrBegin + 2; size_t end = path.find("]", start); attributeName = path.substr( start, end - start ); pathToAttribute = path.substr(0, attrBegin); hasPath = true; } else { attributeName = path; } // we don't have a path to resolve Poco::AutoPtr<Poco::XML::Attr> attr = getPocoDocument()->createAttribute(attributeName); attr->setValue(value); if(!hasPath) { Poco::AutoPtr<Poco::XML::NamedNodeMap> map = element->attributes(); map->setNamedItem(attr); return true; // and we're done } // we have a path to resolve Poco::XML::Element* curElement = getPocoElement(pathToAttribute); if(!curElement) { // if it doesn't exist vector<string> tokens; if(path.find('/') != string::npos) { tokens = tokenize(pathToAttribute, "/"); } // is this a tokenized tag? if(tokens.size() > 1) { // don't 'push' down into the new nodes curElement = element; // find the last existing tag size_t lastExistingTag = 0; // can't use reverse_iterator b/c accumulate doesn't like it for(vector<string>::iterator it = tokens.end(); it != tokens.begin(); it--) { string empty = ""; string concat = accumulate(tokens.begin(), it, std::string()); Poco::XML::Element* testElement = getPocoElement(concat); if(testElement) { lastExistingTag++; curElement = testElement; break; } } // create all the tags that don't exist for(size_t i = lastExistingTag; i < tokens.size(); i++) { Poco::XML::Element *newElement = getPocoDocument()->createElement(tokens.at(i)); curElement->appendChild(newElement); curElement = newElement; } curElement->setAttribute(attributeName, value); return true; } else { Poco::XML::Element* testElement = getPocoElement(pathToAttribute); if(testElement) { curElement = testElement; } else { Poco::XML::Element *newElement = getPocoDocument()->createElement(pathToAttribute); curElement->appendChild(newElement); curElement = newElement; } curElement->setAttribute(attributeName, value); return true; } } return false; }
void command_main_loop(int argc, char **argv) { gint n, status, num_tokens; gchar *inp, *out, *ext, *tmp, *line, *base, **buff; gboolean exit=FALSE; GSList *list, *files, *item, *structures; struct file_pak *inp_pak, *out_pak; struct model_pak *model; if (argc < 2) printf("gdis> Commandline interface. Enter ? for help.\n"); /* command line */ do { /* if additional keywords - process as single command line */ if (argc > 1) { /* convert options into single string for processing */ buff = g_malloc(argc*sizeof(gchar *)); for (n=1 ; n<argc ; n++) *(buff+n-1) = g_strdup(argv[n]); *(buff+argc-1) = NULL; line = g_strjoinv(" ", buff); g_strfreev(buff); exit = TRUE; } else { /* standard repeating prompt */ printf("gdis> "); line = file_read_line(stdin); } /* quit primitive */ if (g_ascii_strncasecmp("qu", line, 2) == 0 || g_ascii_strncasecmp("ex", line, 2) == 0) exit=TRUE; /* test primitive */ if (g_ascii_strncasecmp("te", line, 2) == 0) { buff = tokenize(line, &num_tokens); for (n=1 ; n<num_tokens ; n++) test_run(*(buff+n)); g_strfreev(buff); } /* copy primitive */ if (g_ascii_strncasecmp("co", line, 2) == 0 || g_ascii_strncasecmp("cp", line, 2) == 0) { buff = tokenize(line, &num_tokens); if (num_tokens > 2) { out_pak = get_file_info(*(buff+2), BY_EXTENSION); if (!out_pak) { printf("Error: unrecognized output filetype.\n"); break; } if (!out_pak->write_file) { printf("Error: write method for this filetype does not exist.\n"); break; } /* FIXME! - this is all wrong - should be no dependence on sysenv.cwd for path */ /* since this falls over with something like prompt:>gdis cp /tmp/gok.sot /tmp/dest/gok.meta */ ext = file_extension_get(*(buff+2)); files = file_dir_list_pattern(sysenv.cwd, *(buff+1)); for (list=files ; list ; list=g_slist_next(list)) { inp_pak = get_file_info(list->data, BY_EXTENSION); inp = g_build_filename(sysenv.cwd, list->data, NULL); /* FIXME - changed to correct a problem with Florian's metadata store */ // base = parse_strip(list->data); base = g_strdup(list->data); if (inp_pak) { if (inp_pak->read_file) { model = model_new(); status = inp_pak->read_file(inp, model); structures = g_slist_find(sysenv.mal, model); #if DEBUG_COMMAND_MAIN_LOOP printf("Items loaded = %d [status = %d]\n", g_slist_length(structures), status); #endif if (g_slist_length(structures) > 1) { /* multiple output for input files that contain more than one structure */ n = 1; for (item=structures ; item ; item=g_slist_next(item)) { model = item->data; tmp = g_strdup_printf("%s_%d.%s", base, n, ext); out = g_build_filename(sysenv.cwd, tmp, NULL); status = out_pak->write_file(out, model); #if DEBUG_COMMAND_MAIN_LOOP printf("a [%s] -> [%s]\n", inp, out); #endif g_free(out); g_free(tmp); model_free(model); n++; } } else { tmp = g_strdup_printf("%s.%s", base, ext); out = g_build_filename(sysenv.cwd, tmp, NULL); g_free(tmp); status = out_pak->write_file(out, model); #if DEBUG_COMMAND_MAIN_LOOP printf("b [%s] -> [%s]\n", inp, out); #endif g_free(out); model_free(model); } } else printf("Error: read method for this filetype does not exist.\n"); } else { printf("Error: unrecognized input filetype.\n"); } g_free(base); g_free(inp); } /* CURRENT hack */ if (!files) { /* FIXME */ } g_free(ext); free_slist(files); } else printf("Error: insufficient tokens for <copy> command\n"); g_strfreev(buff); } if (g_ascii_strncasecmp("ls", line, 2) == 0) { buff = tokenize(line, &num_tokens); if (num_tokens > 1) files = file_dir_list_pattern(sysenv.cwd, *(buff+1)); else files = file_dir_list(sysenv.cwd, FALSE); for (list=files ; list ; list=g_slist_next(list)) { printf("%s\n", (gchar *) list->data); } g_strfreev(buff); } if (g_ascii_strncasecmp("cd", line, 2) == 0) { buff = tokenize(line, &num_tokens); if (num_tokens > 1) { inp = g_build_path(DIR_SEP, sysenv.cwd, *(buff+1), NULL); set_path(inp); g_free(inp); } printf("%s\n", sysenv.cwd); g_strfreev(buff); } if (g_ascii_strncasecmp("pwd", line, 3) == 0) { printf("%s\n", sysenv.cwd); } if (g_ascii_strncasecmp("?", line, 1) == 0 || g_ascii_strncasecmp("h", line, 1) == 0) { printf("GDIS v%4.2f available commands\n\n", VERSION); printf("cd <destination>\n"); printf(" - changes to target directory\n"); printf("pwd\n"); printf(" - prints the current working directory\n"); printf("ls\n"); printf(" - lists the files in the current working directory\n"); printf("copy <source> <destination>\n"); printf(" - convert between filetypes, based on extension (wildcards allowed)\n"); printf("quit\n"); printf(" - exit program\n"); } /* done -> next line */ g_free(line); } while (!exit); }
int main() { char line[MAX_LINE_LENGTH] = { 0 }; char* lines[MAX_NUM_LINES]; char* words[MAX_NUM_WORDS_PER_LINE] = { 0 }; /* * lines_to_ignore[line_number] is set to true when line is a #define/#undef statement. * If we didn't do this, the following line: * #define foo bar * would be converted to: * #define bar bar * which is clearly not the desired behaviour. */ bool lines_to_ignore[MAX_NUM_LINES] = { 0 }; int num_lines = 0; while (get_line(line) > 0) { lines[num_lines++] = line; int num_words = tokenize(line, words); switch (num_words) { /* * This does not (yet) support defines with multiple words * following the name of the macro. */ case POSSIBLE_DEFINE: lines_to_ignore[num_lines - 1] = handle_possible_define(words); break; case POSSIBLE_UNDEFINE: lines_to_ignore[num_lines - 1] = handle_possible_undefine(words); break; default: break; } /* * For each #defined word for each line, do a strstr for the defined symbol. * If a substring is found and the characters before and after the substring aren't: * numeric * alphabetic * and we are not: * in a string * in a comment * ignoring this line (because it is the line in which the symbol was defined) * then replace the symbol with the replacement text. */ for (int i = 0; i < num_lines; ++i) { if (lines_to_ignore[i]) { continue; } for (int j = 0; j < HASH_SIZE; ++j) { struct list* node = hash_table[j]; for (; node != NULL; node = node->next) { char* start = lines[i]; char* occurence = strstr(lines[i], node->name); while (occurence != NULL) { /* Print characters before the occurence. */ for (char* c = start; c < occurence; ++c) { putchar(*c); } if (suitable_for_replacement(lines[i], occurence, strlen(node->replacement))) { printf("%s", node->replacement); } else { char* c = occurence; for (; c < occurence + strlen(node->name); ++c) { putchar(*c); } start = c; } occurence = strstr(occurence + strlen(node->name), node->name); } } } } } return 0; }
token next_tok(tokenizer_t t){ t = tokenize(t); return t->tok; }
Parser::Parser(const string& s) : tokens{tokenize(s)} {}
/* parse_group_member() */ static link_t * parse_group_member(const char *gname, uint32_t num, struct group_acct *grps) { link_t *l; linkiter_t iter; struct group_acct *g; int cc; char *w; char *p; uint32_t sum; struct share_acct *sacct; l = make_link(); g = NULL; for (cc = 0; cc < num; cc++) { if (strcmp(gname, grps[cc].group) == 0) { g = calloc(1, sizeof(struct group_acct)); assert(g); g->group = strdup(grps[cc].group); g->memberList = strdup(grps[cc].memberList); g->user_shares = strdup(grps[cc].user_shares); tokenize(g->user_shares); break; } } /* gudness leaf member * caller will free the link */ if (g == NULL) return l; p = g->memberList; sum = 0; while ((w = get_next_word(&p))) { sacct = get_sacct(w, g->user_shares); if (sacct == NULL) { while ((sacct = pop_link(l))) free_sacct(sacct); fin_link(l); return NULL; } sum = sum + sacct->shares; enqueue_link(l, sacct); } traverse_init(l, &iter); while ((sacct = traverse_link(&iter))) { sacct->dshares = (double)sacct->shares/(double)sum; } _free_(g->group); _free_(g->memberList); _free_(g->user_shares); _free_(g); return l; }