//------------------------------------------------------------------------------ // void LoadData() //------------------------------------------------------------------------------ void CallFunctionPanel::LoadData() { #ifdef DEBUG_CALLFUNCTION_PANEL_LOAD MessageInterface::ShowMessage(wxT("CallFunctionPanel::LoadData() entered\n")); #endif // Set the pointer for the "Show Script" button mObject = theCommand; int id = theCommand->GetParameterID(wxT("FunctionName")); wxString functionName = theCommand->GetStringParameter(id); // If function name is not in the ComboBox list, add blank if (!theFunctionComboBox->SetStringSelection(functionName.c_str())) { theFunctionComboBox->Append(wxT("")); theFunctionComboBox->SetStringSelection(wxT("")); } #ifdef DEBUG_CALLFUNCTION_PANEL_LOAD MessageInterface::ShowMessage (wxT(" Function name is: <%s>\n"), functionName.c_str()); #endif // get input parameters StringArray inputList = theCommand->GetStringArrayParameter(wxT("AddInput")); mNumInput = inputList.size(); mInputWxStrings.Clear(); #ifdef DEBUG_CALLFUNCTION_PANEL_LOAD MessageInterface::ShowMessage (wxT(" Found %d input parameters:\n"), mNumInput); for (StringArray::iterator i = inputList.begin(); i != inputList.end(); ++i) MessageInterface::ShowMessage(wxT(" '%s'\n"), i->c_str()); #endif if (mNumInput > 0) { wxString *inputNames = new wxString[mNumInput]; GmatBase *param; wxString cellValue = wxT(""); wxString delimiter = wxT(", "); for (int i=0; i<mNumInput; i++) { inputNames[i] = inputList[i].c_str(); #ifdef DEBUG_CALLFUNCTION_PANEL_LOAD MessageInterface::ShowMessage(wxT(" Looking up ") + inputList[i] + wxT("\n")); #endif param = theGuiInterpreter->GetConfiguredObject(inputList[i]); if (i == mNumInput-1) delimiter = wxT(""); if (param != NULL) { cellValue = cellValue + param->GetName().c_str() + delimiter; mInputWxStrings.Add(param->GetName().c_str()); } } #ifdef __USE_GRID_FOR_INPUT_OUTPUT__ theInputGrid->SetCellValue(0, 0, cellValue); #else theInputTextCtrl->SetValue(cellValue); #endif delete [] inputNames; } // get output parameters StringArray outputList = theCommand->GetStringArrayParameter(wxT("AddOutput")); mNumOutput = outputList.size(); mOutputWxStrings.Clear(); #ifdef DEBUG_CALLFUNCTION_PANEL_LOAD MessageInterface::ShowMessage (wxT(" Found %d output parameters:\n"), mNumOutput); for (StringArray::iterator i = outputList.begin(); i != outputList.end(); ++i) MessageInterface::ShowMessage(wxT(" '%s'\n"), i->c_str()); #endif if (mNumOutput > 0) { wxString *outputNames = new wxString[mNumOutput]; GmatBase *param; wxString cellValue = wxT(""); wxString delimiter = wxT(", "); for (int i=0; i<mNumOutput; i++) { outputNames[i] = outputList[i].c_str(); #ifdef DEBUG_CALLFUNCTION_PANEL_LOAD MessageInterface::ShowMessage(wxT(" Looking up ") + outputList[i] + wxT("\n")); #endif param = theGuiInterpreter->GetConfiguredObject(outputList[i]); if (i == mNumOutput-1) delimiter = wxT(""); if (param != NULL) { cellValue = cellValue + param->GetName().c_str() + delimiter; mOutputWxStrings.Add(param->GetName().c_str()); } } #ifdef __USE_GRID_FOR_INPUT_OUTPUT__ theOutputGrid->SetCellValue(0, 0, cellValue); #else theOutputTextCtrl->SetValue(cellValue); #endif delete [] outputNames; } }
void PluginListComponent::scanFor (AudioPluginFormat* format) { if (format == 0) return; FileSearchPath path (format->getDefaultLocationsToSearch()); if (propertiesToUse != 0) path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString()); { AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon); FileSearchPathListComponent pathList; pathList.setSize (500, 300); pathList.setPath (path); aw.addCustomComponent (&pathList); aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey); aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey); if (aw.runModalLoop() == 0) return; path = pathList.getPath(); } if (propertiesToUse != 0) { propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString()); propertiesToUse->saveIfNeeded(); } double progress = 0.0; AlertWindow aw (TRANS("Scanning for plugins..."), TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon); aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey); aw.addProgressBarComponent (progress); aw.enterModalState(); MessageManager::getInstance()->runDispatchLoopUntil (300); PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile); for (;;) { aw.setMessage (TRANS("Testing:\n\n") + scanner.getNextPluginFileThatWillBeScanned()); MessageManager::getInstance()->runDispatchLoopUntil (20); if (! scanner.scanNextFile (true)) break; if (! aw.isCurrentlyModal()) break; progress = scanner.getProgress(); } if (scanner.getFailedFiles().size() > 0) { StringArray shortNames; for (int i = 0; i < scanner.getFailedFiles().size(); ++i) shortNames.add (File (scanner.getFailedFiles()[i]).getFileName()); AlertWindow::showMessageBox (AlertWindow::InfoIcon, TRANS("Scan complete"), TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n") + shortNames.joinIntoString (", ")); } }
StringArray StringArray::fromTokens (StringRef stringToTokenise, bool preserveQuotedStrings) { StringArray s; s.addTokens (stringToTokenise, preserveQuotedStrings); return s; }
StringArray DdParser::get_string_components(const std::string &line) { StringArray result; size_t progress = 0; std::string remaining = line; size_t comment = remaining.find("#",0); remaining = remaining.substr(0, comment); while(remaining.size() > 0) { progress += clear_front_back_whitespace(remaining); if(remaining.size() > 0) { size_t count=0; if(remaining.at(0) == '\"') { ++count; while(remaining.at(count) != '\"') { ++count; if(count >= remaining.size()) { error() << "Unclosed quotes starting at character #" << progress-1; report_error(); result.clear(); return result; } } if(count+1 < remaining.size()) { if(!isspace(remaining.at(count+1))) { error() << "Found illegal quotes at character #" << progress+count+1; report_error(); result.clear(); return result; } } progress += count+1; std::string component = remaining.substr(1, count-1); remaining = remaining.substr(count+1, std::string::npos); result.push_back(component); } else { while(!isspace(remaining.at(count))) { if(remaining.at(count) == '\"') { error() << "Found illegal quotes at character #" << progress+count+1; report_error(); result.clear(); return result; } ++count; if(count >= remaining.size()) break; } progress += count; std::string component = remaining.substr(0, count); remaining = remaining.substr(count, std::string::npos); result.push_back(component); } } } return result; }
void Utils::uniquifyPaths(HashMap<String,String>& paths) { // Get all file paths that have the same filename (i.e. /foo/bar.mdl and /bar.mdl) SortedSet<String> fileSet; for (HashMap<String, String>::Iterator i (paths); i.next();) { for (HashMap<String, String>::Iterator j(paths); j.next();) { if(i.getKey() != j.getKey()) { File fi = i.getKey(); File fj = j.getKey(); if(fi.getFileName().compare(fj.getFileName()) == 0) { fileSet.add(fj.getFullPathName()); } } } } //if there are no same filenames just return if(fileSet.size() == 0) return; // Split paths to an Array HashMap<String, StringArray> sameFiles; for (int i = 0; i < fileSet.size(); ++i) { StringArray arr; arr.addTokens(fileSet[i], File::separatorString, "\""); sameFiles.set(fileSet[i], arr); } // Create unique paths by adding a parent directory to the files until // the path is unique bool uniquePaths = false; int lvl = 0; HashMap<String, String> sameFiles2; while(! uniquePaths) { SortedSet<String> tmpSet; ++lvl; for (HashMap<String, StringArray>::Iterator k(sameFiles); k.next();) { StringArray arr = k.getValue(); int arrSize = arr.size(); String tmpPath2; if(arrSize - lvl > 0) { StringArray tmpPath; for (int l = lvl; --l >= 0;) { tmpPath.add(arr[arrSize - 1 - l]); } tmpPath2 = tmpPath.joinIntoString(File::separatorString); } else { tmpPath2 = k.getValue().joinIntoString(File::separatorString); } tmpSet.add(tmpPath2); sameFiles2.set(k.getKey(), tmpPath2); } if(tmpSet.size() == fileSet.size()) { uniquePaths = true; } } for (HashMap<String, String>::Iterator it(sameFiles2); it.next();) { paths.set(it.getKey(), it.getValue()); } }
void AccountNumbersConverter::validateLines(StringArray const lines) { if (lines.size() == 0) { throw invalid_argument("The file is empty!"); } }
Variant _jobject_to_variant(JNIEnv * env, jobject obj) { jclass c = env->GetObjectClass(obj); bool array; String name = _get_class_name(env, c, &array); //print_line("name is " + name + ", array "+Variant(array)); print_line("ARGNAME: "+name); if (name == "java.lang.String") { return String::utf8(env->GetStringUTFChars( (jstring)obj, NULL )); }; if (name == "[Ljava.lang.String;") { jobjectArray arr = (jobjectArray)obj; int stringCount = env->GetArrayLength(arr); //print_line("String array! " + String::num(stringCount)); DVector<String> sarr; for (int i=0; i<stringCount; i++) { jstring string = (jstring) env->GetObjectArrayElement(arr, i); const char *rawString = env->GetStringUTFChars(string, 0); sarr.push_back(String(rawString)); env->DeleteLocalRef(string); } return sarr; }; if (name == "java.lang.Boolean") { jmethodID boolValue = env->GetMethodID(c, "booleanValue", "()Z"); bool ret = env->CallBooleanMethod(obj, boolValue); return ret; }; if (name == "java.lang.Integer") { jclass nclass = env->FindClass("java/lang/Number"); jmethodID intValue = env->GetMethodID(nclass, "intValue", "()I"); int ret = env->CallIntMethod(obj, intValue); return ret; }; if (name == "[I") { jintArray arr = (jintArray)obj; int fCount = env->GetArrayLength(arr); DVector<int> sarr; sarr.resize(fCount); DVector<int>::Write w = sarr.write(); env->GetIntArrayRegion(arr,0,fCount,w.ptr()); w = DVector<int>::Write(); return sarr; }; if (name == "[B") { jbyteArray arr = (jbyteArray)obj; int fCount = env->GetArrayLength(arr); DVector<uint8_t> sarr; sarr.resize(fCount); DVector<uint8_t>::Write w = sarr.write(); env->GetByteArrayRegion(arr,0,fCount,reinterpret_cast<signed char*>(w.ptr())); w = DVector<uint8_t>::Write(); return sarr; }; if (name == "java.lang.Float" || name == "java.lang.Double") { jclass nclass = env->FindClass("java/lang/Number"); jmethodID doubleValue = env->GetMethodID(nclass, "doubleValue", "()D"); double ret = env->CallDoubleMethod(obj, doubleValue); return ret; }; if (name == "[D") { jdoubleArray arr = (jdoubleArray)obj; int fCount = env->GetArrayLength(arr); RealArray sarr; sarr.resize(fCount); RealArray::Write w = sarr.write(); for (int i=0; i<fCount; i++) { double n; env->GetDoubleArrayRegion(arr, i, 1, &n); w.ptr()[i] = n; }; return sarr; }; if (name == "[F") { jfloatArray arr = (jfloatArray)obj; int fCount = env->GetArrayLength(arr); RealArray sarr; sarr.resize(fCount); RealArray::Write w = sarr.write(); for (int i=0; i<fCount; i++) { float n; env->GetFloatArrayRegion(arr, i, 1, &n); w.ptr()[i] = n; }; return sarr; }; if (name == "[Ljava.lang.Object;") { jobjectArray arr = (jobjectArray)obj; int objCount = env->GetArrayLength(arr); Array varr(true); for (int i=0; i<objCount; i++) { jobject jobj = env->GetObjectArrayElement(arr, i); Variant v = _jobject_to_variant(env, jobj); varr.push_back(v); env->DeleteLocalRef(jobj); } return varr; }; if (name == "java.util.HashMap" || name == "com.android.godot.Dictionary") { Dictionary ret(true); jclass oclass = c; jmethodID get_keys = env->GetMethodID(oclass, "get_keys", "()[Ljava/lang/String;"); jobjectArray arr = (jobjectArray)env->CallObjectMethod(obj, get_keys); StringArray keys = _jobject_to_variant(env, arr); env->DeleteLocalRef(arr); jmethodID get_values = env->GetMethodID(oclass, "get_values", "()[Ljava/lang/Object;"); arr = (jobjectArray)env->CallObjectMethod(obj, get_values); Array vals = _jobject_to_variant(env, arr); env->DeleteLocalRef(arr); //print_line("adding " + String::num(keys.size()) + " to Dictionary!"); for (int i=0; i<keys.size(); i++) { ret[keys[i]] = vals[i]; }; return ret; }; env->DeleteLocalRef(c); return Variant(); };
StringArray getCommaOrWhitespaceSeparatedItems (const String& sourceString) { StringArray s; s.addTokens (sourceString, ", \t\r\n", StringRef()); return getCleanedStringArray (s); }
void UnitTests::logReport (StringArray const& report) { for (int i = 0; i < report.size (); ++i) logMessage (report [i]); }
sp<Retval> MonDiskstats::loadData(sp<MonBase>& out, String& sLine) { sp<Retval> retval; StringArray ar; if( DFW_RET(retval, ar.split(sLine, "|")) ) return DFW_RETVAL_D(retval); if( !(ar.size() > 1) ) return DFW_RETVAL_NEW_MSG(DFW_ERROR, 0 , "Unknown format. ground-size=%d", ar.size()); sp<String> ar1 = ar.getString(0); uint64_t d_sec = Long::parseLong(ar1->toChars()); sp<MonDiskstats> dest = create(d_sec); // get datas String s_type, s_devtype, s_name; String s_rcount, s_rmerged, s_rsector, s_rtime; String s_wcount, s_wmerged, s_wsector, s_wtime; String s_iocount, s_iotime, s_iowtime; for(int k=1; k<ar.size(); k++){ sp<String> arx = ar.getString(k); int round = 0; const char* v = NULL; const char* p = arx->toChars(); do{ if( *p == ' ' || *p == '\t' || *p == '|' || *p=='\0'){ if( v ){ switch(round){ case 0: s_type.set(v, p-v); break; case 1: s_devtype.set(v, p-v); break; case 2: s_name.set(v, p-v); break; case 3: s_rcount.set(v, p-v); break; case 4: s_rmerged.set(v, p-v); break; case 5: s_rsector.set(v, p-v); break; case 6: s_rtime.set(v, p-v); break; case 7: s_wcount.set(v, p-v); break; case 8: s_wmerged.set(v, p-v); break; case 9: s_wsector.set(v, p-v); break; case 10: s_wtime.set(v, p-v); break; case 11: s_iocount.set(v, p-v); break; case 12: s_iotime.set(v, p-v); break; case 13: s_iowtime.set(v, p-v); break; } v= NULL; round++; } if( *p=='\0' ) break; }else if(!v){ v = p; } p++; }while(true); if( round != 14 ){ return DFW_RETVAL_NEW_MSG(DFW_ERROR, 0 , "Unknown format %s", sLine.toChars()); } sp<Data> d = new Data(); d->m_type = Integer::parseInt(s_type); d->m_devtype = Integer::parseInt(s_devtype); d->m_sName = s_name; d->m_rcount = Long::parseLong(s_rcount); d->m_rmerged = Long::parseLong(s_rmerged); d->m_rsector = Long::parseLong(s_rsector); d->m_rtime = Long::parseLong(s_rtime); d->m_wcount = Long::parseLong(s_wcount); d->m_wmerged = Long::parseLong(s_wmerged); d->m_wsector = Long::parseLong(s_wsector); d->m_wtime = Long::parseLong(s_wtime); d->m_iocount = Long::parseLong(s_iocount); d->m_iotime = Long::parseLong(s_iotime); d->m_iowtime = Long::parseLong(s_iowtime); if( d->m_devtype == 0 ) { dest->m_all->m_rcount += d->m_rcount; dest->m_all->m_rmerged += d->m_rmerged; dest->m_all->m_rsector += d->m_rsector; dest->m_all->m_rtime += d->m_rtime; dest->m_all->m_wcount += d->m_wcount; dest->m_all->m_wmerged += d->m_wmerged; dest->m_all->m_wsector += d->m_wsector; dest->m_all->m_wtime += d->m_wtime; dest->m_all->m_iocount += d->m_iocount; dest->m_all->m_iotime += d->m_iotime; dest->m_all->m_iowtime += d->m_iowtime; } if( DFW_RET(retval, dest->m_aLists.insert(d)) ) return DFW_RETVAL_D(retval); } out = dest; return NULL; }
StringArray getSearchPathsFromString (const String& searchPath) { StringArray s; s.addTokens (searchPath, ";\r\n", StringRef()); return getCleanedStringArray (s); }
void ChildAlias::mouseDown (const MouseEvent& e) { //if (e.mods.isLeftButtonDown()){ ((CabbageMainPanel*)(getTarget()->getParentComponent()))->setMouseState("down"); toFront (true); if (e.eventComponent == resizer) { } else { //added a constrainer so that components can't be dragged off-screen constrainer->setMinimumOnscreenAmounts(getHeight(), getWidth(), getHeight(), getWidth()); dragger.startDraggingComponent (this,e); } userAdjusting = true; startBounds = getBounds (); userStartedChangingBounds (); //get the bounds of each of the child components if we are dealing with a plant Component* c = (Component*) target.getComponent (); origBounds.clear(); for(int i=0;i<c->getNumChildComponents();i++){ origBounds.add(c->getChildComponent(i)->getBounds()); } //update dimensions int offX = getProperties().getWithDefault(var::identifier("plantX"), 0); int offY = getProperties().getWithDefault(var::identifier("plantY"), 0); ((CabbageMainPanel*)(getTarget()->getParentComponent()))->setIndex(index); ((CabbageMainPanel*)(getTarget()->getParentComponent()))->currentBounds.setBounds(getPosition().getX()-offX, getPosition().getY()-offY, getWidth(), getHeight()); ((CabbageMainPanel*)(getTarget()->getParentComponent()))->sendActionMessage("Message sent from CabbageMainPanel:Down"); #ifdef Cabbage_Build_Standalone if(e.mods.isRightButtonDown()){ PopupMenu m; m.setLookAndFeel(&getParentComponent()->getLookAndFeel()); m.addItem(2, "Delete"); m.addItem(1, "Add to repository"); int choice = m.show(); if(choice==1){ this->getTopLevelComponent()->setAlwaysOnTop(false); AlertWindow alert("Add to Repository", "Enter a name and hit 'escape'", AlertWindow::NoIcon, this->getTopLevelComponent()); CabbageLookAndFeel basicLookAndFeel; alert.setLookAndFeel(&basicLookAndFeel); alert.setColour(TextEditor::textColourId, Colours::white); //alert.addTextBlock("Enter a name and hit 'escape'(The following symbols not premitted in names:"" $ % ^ & * ( ) - + )"); alert.addTextEditor("textEditor", "name", ""); alert.runModalLoop(); this->getTopLevelComponent()->setAlwaysOnTop(true); bool clashingNames=false; int result; String plantDir = appProperties->getUserSettings()->getValue("PlantFileDir", ""); Logger::writeToLog(plantDir); Array<File> tempfiles; StringArray plants; addFileToPpopupMenu(m, tempfiles, plantDir, "*.plant"); for(int i=0;i<tempfiles.size();i++){ Logger::outputDebugString(tempfiles[i].getFullPathName()); plants.add(tempfiles[i].getFileNameWithoutExtension()); } for(int i=0;i<plants.size();i++) if(plants[i]==alert.getTextEditorContents("textEditor")) clashingNames = true; if(clashingNames==true){ result = CabbageUtils::showYesNoMessage("Do you wish to overwrite the existing plant?", &getLookAndFeel()); if(result == 0) ((CabbageMainPanel*)(getTarget()->getParentComponent()))->sendActionMessage("Message sent from CabbageMainPanel:AddingPlant:"+alert.getTextEditorContents("textEditor")); else showMessage("Nothing written to repository", &getLookAndFeel()); } else ((CabbageMainPanel*)(getTarget()->getParentComponent()))->sendActionMessage("Message sent from CabbageMainPanel:AddingPlant:"+alert.getTextEditorContents("textEditor")); } else if(choice==2){ ((CabbageMainPanel*)(getTarget()->getParentComponent()))->sendActionMessage("Message sent from CabbageMainPanel:delete:"); } } #endif }
void filesDropped (const StringArray& files, int, int) { setText (getText() + files.joinIntoString (isMultiline ? "\n" : ", "), true); showEditor(); }
void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& file, const String& filters, bool isDirectory, bool /* selectsFiles */, bool isSave, bool /* warnAboutOverwritingExistingFiles */, bool selectMultipleFiles, FilePreviewComponent* /* previewComponent */) { String separator; StringArray args; const File previousWorkingDirectory (File::getCurrentWorkingDirectory()); const bool isKdeFullSession = SystemStats::getEnvironmentVariable ("KDE_FULL_SESSION", String::empty) .equalsIgnoreCase ("true"); if (exeIsAvailable ("kdialog") && (isKdeFullSession || ! exeIsAvailable ("zenity"))) { // use kdialog for KDE sessions or if zenity is missing args.add ("kdialog"); if (title.isNotEmpty()) args.add ("--title=" + title); if (selectMultipleFiles) { separator = "\n"; args.add ("--multiple"); args.add ("--separate-output"); args.add ("--getopenfilename"); } else { if (isSave) args.add ("--getsavefilename"); else if (isDirectory) args.add ("--getexistingdirectory"); else args.add ("--getopenfilename"); } String startPath; if (file.exists()) { startPath = file.getFullPathName(); } else if (file.getParentDirectory().exists()) { startPath = file.getParentDirectory().getFullPathName(); } else { startPath = File::getSpecialLocation (File::userHomeDirectory).getFullPathName(); if (isSave) startPath += "/" + file.getFileName(); } args.add (startPath); args.add (filters.replaceCharacter (';', ' ')); args.add ("2>/dev/null"); } else { // zenity args.add ("zenity"); args.add ("--file-selection"); if (title.isNotEmpty()) args.add ("--title=" + title); if (selectMultipleFiles) { separator = ":"; args.add ("--multiple"); args.add ("--separator=" + separator); } else { if (isDirectory) args.add ("--directory"); if (isSave) args.add ("--save"); } if (file.isDirectory()) file.setAsCurrentWorkingDirectory(); else if (file.getParentDirectory().exists()) file.getParentDirectory().setAsCurrentWorkingDirectory(); else File::getSpecialLocation (File::userHomeDirectory).setAsCurrentWorkingDirectory(); if (! file.getFileName().isEmpty()) args.add ("--filename=" + file.getFileName()); } ChildProcess child; if (child.start (args, ChildProcess::wantStdOut)) { const String result (child.readAllProcessOutput().trim()); if (result.isNotEmpty()) { StringArray tokens; if (selectMultipleFiles) tokens.addTokens (result, separator, "\""); else tokens.add (result); for (int i = 0; i < tokens.size(); ++i) results.add (File::getCurrentWorkingDirectory().getChildFile (tokens[i])); } child.waitForProcessToFinish (60 * 1000); } previousWorkingDirectory.setAsCurrentWorkingDirectory(); }
int main(int argc, const char *argv[]) { InitModuleObjects(); int ret = 0; bool dryRun = false; bool offline = false; StringAttr daliServer, envPath; enum CmdType { cmd_none, cmd_swap, cmd_auto, cmd_history, cmd_email, cmd_swapped, cmd_reset, cmd_resetspares, cmd_addspares, cmd_removespares, cmd_resethistory }; CmdType cmd = cmd_none; ArgvIterator iter(argc, argv); try { bool stop=false; StringArray params; for (; !ret&&!iter.done(); iter.next()) { const char *arg = iter.query(); if ('-' == *arg) { bool value; if (iter.matchFlag(value, "-dryrun")) dryRun = value; else if (iter.matchFlag(value, "-offline")) offline = value; else { PROGLOG("Unknown option"); ret = 2; usage(); break; } } else { switch (cmd) { case cmd_none: if (strieq("swap", arg)) cmd = cmd_swap; else if (strieq("auto", arg)) cmd = cmd_auto; else if (strieq("history", arg)) cmd = cmd_history; else if (strieq("email", arg)) cmd = cmd_email; else if (strieq("swapped", arg)) cmd = cmd_swapped; else if (strieq("reset", arg)) cmd = cmd_reset; else if (strieq("resetspares", arg)) cmd = cmd_resetspares; else if (strieq("addspares", arg)) cmd = cmd_addspares; else if (strieq("removespares", arg)) cmd = cmd_removespares; else if (strieq("resethistory", arg)) cmd = cmd_resethistory; else { PROGLOG("Unknown command"); usage(); ret = 2; } break; default: params.append(iter.query()); break; } } } unsigned requiredParams=UINT_MAX; switch (cmd) { case cmd_swap: requiredParams = 4; break; case cmd_addspares: case cmd_removespares: requiredParams = 3; break; case cmd_auto: case cmd_history: case cmd_email: case cmd_swapped: case cmd_reset: case cmd_resetspares: case cmd_resethistory: requiredParams = 2; break; } if (params.ordinality() < requiredParams) { usage(); ret = 2; } else { StringAttr daliServer = params.item(0); StringAttr clusterName = params.item(1); DaliClient dclient(daliServer); StringBuffer logname; splitFilename(argv[0], NULL, NULL, &logname, NULL); addFileTimestamp(logname, true); logname.append(".log"); StringBuffer lf; openLogFile(lf, logname.str(),0,false,true); queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_prefix); Owned<IRemoteConnection> conn = querySDS().connect("/Environment", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT); IPropertyTree *environment = conn->queryRoot(); StringBuffer xpath("Software/ThorCluster[@name=\""); xpath.append(clusterName).append("\"]"); IPropertyTree *cluster = environment->queryPropTree(xpath.str()); if (!cluster) { PROGLOG("Unknown cluster: %s", clusterName.get()); ret = 3; } if (!ret) { Owned<IPropertyTree> options = createPTreeFromIPT(cluster); conn.clear(); if (options&&options->getPropBool("@enableSysLog",true)) UseSysLogForOperatorMessages(); switch (cmd) { case cmd_auto: { if (!autoSwapNode(clusterName, dryRun)) ret = 3; break; } case cmd_swap: { const char *oldip=params.item(2); const char *newip=params.item(3); if (!swapNode(clusterName, oldip, newip)) ret = 3; break; } case cmd_history: case cmd_swapped: case cmd_email: { unsigned days = params.isItem(2) ? atoi(params.item(2)) : 0; // for history or swapped switch (cmd) { case cmd_history: swapNodeHistory(clusterName, days, NULL); break; case cmd_swapped: swappedList(clusterName, days, NULL); break; case cmd_email: { bool sendSwapped = false; bool sendHistory = false; if (params.isItem(2)) { if (strieq("swapped", params.item(2))) sendSwapped = true; else if (strieq("history", params.item(2))) sendHistory = true; } emailSwap(clusterName, NULL, true, sendSwapped, sendHistory); break; } } break; } case cmd_reset: case cmd_resetspares: { StringBuffer response; if (!resetClusterGroup(clusterName, "ThorCluster", cmd==cmd_resetspares, response)) { WARNLOG("%s", response.str()); ret = 3; } break; } case cmd_addspares: case cmd_removespares: { SocketEndpointArray allEps; unsigned p=2; do { const char *ipOrRange = params.item(p); SocketEndpointArray epa; epa.fromText(ipOrRange, 0); ForEachItemIn(e, epa) allEps.append(epa.item(e)); p++; } while (p<params.ordinality()); StringBuffer response; bool res; if (cmd == cmd_addspares) res = addClusterSpares(clusterName, "ThorCluster", allEps, response); else res = removeClusterSpares(clusterName, "ThorCluster", allEps, response); if (!res) { WARNLOG("%s", response.str()); ret = 3; } break; } case cmd_resethistory: { Owned<IRemoteConnection> conn = querySDS().connect("/SwapNode", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT); if (conn) { StringBuffer groupName; getClusterGroupName(*options, groupName); VStringBuffer xpath("Thor[@group=\"%s\"]", groupName.str()); if (conn->queryRoot()->removeProp(xpath.str())) PROGLOG("SwapNode info for cluster %s removed", clusterName.get()); else PROGLOG("SwapNode info for cluster %s not found", clusterName.get()); } break; } } } } UseSysLogForOperatorMessages(false); } catch (IException *e) { EXCLOG(e,"SWAPNODE"); e->Release(); ret = -1; } ExitModuleObjects(); return ret; }
//------------------------------------------------------------------------------ // virtual void LoadData() //------------------------------------------------------------------------------ void GroundTrackPlotPanel::LoadData() { #if DEBUG_PANEL_LOAD MessageInterface::ShowMessage("GroundTrackPlotPanel::LoadData() entered.\n"); #endif try { // Load data from the core engine wxString str; Real rval; // Load central body wxString centralBody = mGroundTrackPlot->GetStringParameter("CentralBody").c_str(); mCentralBody = centralBody; #ifdef DEBUG_PANEL_LOAD MessageInterface::ShowMessage(" centralBody = '%s'\n", centralBody.c_str()); #endif mCentralBodyComboBox->SetValue(centralBody); // Load space objects to draw StringArray objects = mGroundTrackPlot->GetStringArrayParameter("Add"); int count = mObjectCheckListBox->GetCount(); #ifdef DEBUG_PANEL_LOAD MessageInterface::ShowMessage(" There are %d items in ObjectCheckListBox\n", count); for (int i = 0; i < count; i++) MessageInterface::ShowMessage(" %d = '%s'\n", i, mObjectCheckListBox->GetString(i).c_str()); MessageInterface::ShowMessage(" There are %d objects to draw\n", objects.size()); for (unsigned int i = 0; i < objects.size(); i++) MessageInterface::ShowMessage(" %d = '%s'\n", i, objects[i].c_str()); #endif std::string objName; // Load object drawing option and colors for (UnsignedInt i = 0; i < objects.size(); i++) { objName = objects[i]; #ifdef __USE_COLOR_FROM_SUBSCRIBER__ mOrbitColorMap[objName] = RgbColor(mGroundTrackPlot->GetColor("Orbit", objName)); mTargetColorMap[objName] = RgbColor(mGroundTrackPlot->GetColor("Target", objName)); #endif // Put check mark in the object list for (int j = 0; j < count; j++) { std::string itemName = mObjectCheckListBox->GetString(j).WX_TO_STD_STRING; if (itemName == objName) { mObjectCheckListBox->Check(j, true); break; } } } // Load drawing options str.Printf("%d", mGroundTrackPlot->GetIntegerParameter("DataCollectFrequency")); mDataCollectFreqTextCtrl->SetValue(str); str.Printf("%d", mGroundTrackPlot->GetIntegerParameter("UpdatePlotFrequency")); mUpdatePlotFreqTextCtrl->SetValue(str); str.Printf("%d", mGroundTrackPlot->GetIntegerParameter("NumPointsToRedraw")); mNumPointsToRedrawTextCtrl->SetValue(str); mShowPlotCheckBox->SetValue(mGroundTrackPlot->GetBooleanParameter("ShowPlot")); // Load solver iteration and texture map file mSolverIterComboBox->SetValue(mGroundTrackPlot->GetStringParameter("SolverIterations").c_str()); mTextureFile = mGroundTrackPlot->GetStringParameter("TextureMap").c_str(); mTextureMapTextCtrl->SetValue(mTextureFile); mTextureMapTextCtrl->SetInsertionPointEnd(); // Select first object in the list to show color if (objects.size() > 0) { mObjectCheckListBox->SetSelection(0); #ifdef __USE_COLOR_FROM_SUBSCRIBER__ ShowSpacePointColor(mObjectCheckListBox->GetStringSelection()); #endif } } catch (BaseException &e) { MessageInterface::PopupMessage(Gmat::ERROR_, e.GetFullMessage().c_str()); } EnableUpdate(false); #if DEBUG_PANEL_LOAD MessageInterface::ShowMessage("GroundTrackPlotPanel::LoadData() exiting.\n"); #endif }
void MainContentComponent::setLocalisation() { static String countryCode = SystemStats::getDisplayLanguage(); std::cout << "Language: " << countryCode << std::endl; File dataDir = File::getSpecialLocation (File::currentApplicationFile).getParentDirectory().getParentDirectory().getFullPathName() + File::separatorString + "Data"; //We may need to find suitable fonst that exists on the current system //for languages such as Chinese, Japanese, and Korean. //http://en.wikipedia.org/wiki/List_of_CJK_fonts StringArray availableFonts = Font::findAllTypefaceNames(); //countryCode will equal ISO 639-1 or ISO 639-2 codes as listed here: //http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes if (countryCode == "ja" || countryCode == "jpn") //japanese { File transFile (dataDir.getFullPathName() + File::separatorString + "trans_ja"); if (transFile.exists()) { trans = new LocalisedStrings (transFile); LocalisedStrings::setCurrentMappings(trans); String fontToUse = "Arial Unicode MS"; // available on OSX 10.5 and above if (availableFonts.contains(fontToUse) == false) { fontToUse = "Meiryo"; // available on Windows Vista and above if (availableFonts.contains(fontToUse) == false) { fontToUse = "MS PGothic"; // available on Windows XP //what about on Linux? } } lookAndFeel.setDefaultSansSerifTypefaceName(fontToUse); currentLanguage = "Japanese"; } } else if (countryCode == "zh" || countryCode == "zho" || countryCode == "zh-Hant" || countryCode == "zh-Hans") //chinese. do i need the first two? { File transFile (dataDir.getFullPathName() + File::separatorString + "trans_zh"); if (transFile.exists()) { trans = new LocalisedStrings (transFile); LocalisedStrings::setCurrentMappings(trans); String fontToUse = "Arial Unicode MS"; // available on OSX 10.5 and above if (availableFonts.contains(fontToUse) == false) { fontToUse = "Microsoft JhengHei"; // available on Windows Vista and above if (availableFonts.contains(fontToUse) == false) { fontToUse = "SimHei"; // available on Windows XP //do we neeed to consider simplified vs traditional? //what about on Linux? } } lookAndFeel.setDefaultSansSerifTypefaceName(fontToUse); currentLanguage = "Chinese"; } } else if (countryCode == "ko" || countryCode == "kor") //Korean { File transFile (dataDir.getFullPathName() + File::separatorString + "trans_ko"); if (transFile.exists()) { trans = new LocalisedStrings (transFile); LocalisedStrings::setCurrentMappings(trans); String fontToUse = "AppleMyungjo"; // available on OSX 10.5 and above if (availableFonts.contains(fontToUse) == false) { fontToUse = "Batang"; // available on Windows.. XP and above? } lookAndFeel.setDefaultSansSerifTypefaceName(fontToUse); currentLanguage = "Korean"; } } else //english { LocalisedStrings::setCurrentMappings(0); currentLanguage = "English"; } }
//============================================================================== void Project::createPropertyEditors (PropertyListBuilder& props) { props.add (new TextPropertyComponent (getProjectNameValue(), "Project Name", 256, false), "The name of the project."); props.add (new TextPropertyComponent (getVersionValue(), "Project Version", 16, false), "The project's version number, This should be in the format major.minor.point[.point]"); props.add (new TextPropertyComponent (getCompanyName(), "Company Name", 256, false), "Your company name, which will be added to the properties of the binary where possible"); props.add (new TextPropertyComponent (getCompanyWebsite(), "Company Website", 256, false), "Your company website, which will be added to the properties of the binary where possible"); props.add (new TextPropertyComponent (getCompanyEmail(), "Company E-mail", 256, false), "Your company e-mail, which will be added to the properties of the binary where possible"); { StringArray projectTypeNames; Array<var> projectTypeCodes; const Array<ProjectType*>& types = ProjectType::getAllTypes(); for (int i = 0; i < types.size(); ++i) { projectTypeNames.add (types.getUnchecked(i)->getDescription()); projectTypeCodes.add (types.getUnchecked(i)->getType()); } props.add (new ChoicePropertyComponent (getProjectTypeValue(), "Project Type", projectTypeNames, projectTypeCodes)); } props.add (new TextPropertyComponent (getBundleIdentifier(), "Bundle Identifier", 256, false), "A unique identifier for this product, mainly for use in OSX/iOS builds. It should be something like 'com.yourcompanyname.yourproductname'"); getProjectType().createPropertyEditors (*this, props); { const int maxSizes[] = { 20480, 10240, 6144, 2048, 1024, 512, 256, 128, 64 }; StringArray maxSizeNames; Array<var> maxSizeCodes; maxSizeNames.add (TRANS("Default")); maxSizeCodes.add (var::null); maxSizeNames.add (String::empty); maxSizeCodes.add (var::null); for (int i = 0; i < numElementsInArray (maxSizes); ++i) { const int sizeInBytes = maxSizes[i] * 1024; maxSizeNames.add (File::descriptionOfSizeInBytes (sizeInBytes)); maxSizeCodes.add (sizeInBytes); } props.add (new ChoicePropertyComponent (getMaxBinaryFileSize(), "BinaryData.cpp size limit", maxSizeNames, maxSizeCodes), "When splitting binary data into multiple cpp files, the Introjucer attempts to keep the file sizes below this threshold. " "(Note that individual resource files which are larger than this size cannot be split across multiple cpp files)."); } props.add (new BooleanPropertyComponent (shouldIncludeBinaryInAppConfig(), "Include Binary", "Include BinaryData.h in the AppConfig.h file")); props.add (new TextPropertyComponent (getProjectPreprocessorDefs(), "Preprocessor definitions", 32768, true), "Global preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace, commas, or " "new-lines to separate the items - to include a space or comma in a definition, precede it with a backslash."); props.add (new TextPropertyComponent (getProjectUserNotes(), "Notes", 32768, true), "Extra comments: This field is not used for code or project generation, it's just a space where you can express your thoughts."); }
void runTests(const CIMOMHandleIFCRef& hdl) { // GetClass // CIM_ERR_INVALID_NAMESPACE try { hdl->getClass("badNamespace", "foo"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER - Can't do without doing straight XML. Handle it in a separate test. // CIM_ERR_NOT_FOUND try { hdl->getClass("root/testsuite", "fooXXX"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // GetInstance // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("fooKey", CIMValue(String("fooKeyValue"))); hdl->getInstance("badNamespace", cop); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER - Can't do without doing straight XML. Handle it in a separate test. // CIM_ERR_INVALID_CLASS try { CIMObjectPath cop("fooXXX"); cop.setKeyValue("fooKey", CIMValue(String("fooKeyValue"))); hdl->getInstance("root/testsuite", cop); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // CIM_ERR_NOT_FOUND try { CIMObjectPath cop("CIM_PhysicalElement"); cop.setKeyValue("CreationClassName", CIMValue(String("fooKeyValue"))); cop.setKeyValue("Tag", CIMValue(String("fooKeyValue"))); hdl->getInstance("root/testsuite", cop); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // DeleteClass // CIM_ERR_INVALID_NAMESPACE try { hdl->deleteClass("badNamespace", "foo"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER - Can only be done with doctored XML // CIM_ERR_NOT_FOUND try { hdl->deleteClass("root/testsuite", "fooXXX"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // CIM_ERR_CLASS_HAS_CHILDREN - Impossible to produce with OpenWBEM // CIM_ERR_CLASS_HAS_INSTANCES - Impossible to produce with OpenWBEM // DeleteInstance // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("fooKey", CIMValue(String("fooKeyValue"))); hdl->deleteInstance("badNamespace", cop); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER - Can only be done with doctored XML // CIM_ERR_INVALID_CLASS try { CIMObjectPath cop("fooXXX"); cop.setKeyValue("fooKey", CIMValue(String("fooKeyValue"))); hdl->deleteInstance("root/testsuite", cop); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // CIM_ERR_NOT_FOUND try { CIMObjectPath cop("CIM_PhysicalElement"); cop.setKeyValue("CreationClassName", CIMValue(String("fooKeyValue"))); cop.setKeyValue("Tag", CIMValue(String("fooKeyValue"))); hdl->deleteInstance("root/testsuite", cop); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // CreateClass CIMClass cc("footest"); CIMQualifierType keyQualType = hdl->getQualifierType("root/testsuite", CIMQualifier::CIM_QUAL_KEY); CIMQualifier keyQual(keyQualType); keyQual.setValue(CIMValue(true)); CIMProperty theKeyProp("theKeyProp", CIMDataType::BOOLEAN); theKeyProp.addQualifier(keyQual); theKeyProp.setValue(CIMValue(true)); cc.addProperty(theKeyProp); // create a base class that has the associator qualifier, which can't be overridden CIMClass baseClass("invalidTestBase"); CIMQualifierType assocQualType = hdl->getQualifierType("root/testsuite", CIMQualifier::CIM_QUAL_ASSOCIATION); CIMQualifier assocQual(assocQualType); assocQual.setValue(CIMValue(true)); baseClass.addProperty(theKeyProp); baseClass.addQualifier(assocQual); // CIM_ERR_INVALID_NAMESPACE try { hdl->createClass("badNamespace", cc); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER - thrown from MetaRepository::_throwIfBadClass() and MetaRepository::adjustClass() // There are different ways to get this error. Let's try all of them. // 1. A subclass overrides a qualifier that has the DISABLEOVERRIDE flavor // on the base class try { try { hdl->deleteClass("root/testsuite", baseClass.getName()); } catch (const CIMException&) { } hdl->createClass("root/testsuite", baseClass); } catch (const CIMException& e) { if (e.getErrNo() != CIMException::ALREADY_EXISTS) { throw e; } } try { CIMInstance ci = baseClass.newInstance(); ci.setProperty(theKeyProp); hdl->createInstance("root/testsuite", ci); } catch (const CIMException& e) { TEST_ASSERT(0); } // setup's done, now do the tests try { // test overriding an DISABLEOVERRIDE qualifier CIMClass cc2("invalidTestSub"); cc2.setSuperClass("invalidTestBase"); CIMQualifier assocQual2(assocQual); assocQual2.setValue(CIMValue(false)); cc2.addQualifier(assocQual2); hdl->createClass("root/testsuite", cc2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } try { // test adding an key to a subclass when the parent already has keys. CIMClass cc2("invalidTestSub"); cc2.setSuperClass("invalidTestBase"); CIMProperty theKeyProp2("theKeyProp2", CIMDataType::BOOLEAN); theKeyProp2.addQualifier(keyQual); cc2.addProperty(theKeyProp2); hdl->createClass("root/testsuite", cc2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } // CIM_ERR_ALREADY_EXISTS try { // test adding a class with no keys hdl->createClass("root/testsuite", baseClass); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::ALREADY_EXISTS); } // CIM_ERR_INVALID_SUPERCLASS try { CIMClass cc2(baseClass); cc2.setSuperClass("invalid"); hdl->createClass("root/testsuite", cc2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_SUPERCLASS); } // CreateInstance // CIM_ERR_INVALID_NAMESPACE try { CIMInstance ci = baseClass.newInstance(); ci.setProperty(theKeyProp); hdl->createInstance("badNamespace", ci); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { CIMInstance ci = baseClass.newInstance(); ci.setClassName("nonexistentClass"); ci.setProperty(theKeyProp); hdl->createInstance("root/testsuite", ci); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // CIM_ERR_ALREADY_EXISTS try { CIMInstance ci = baseClass.newInstance(); ci.setProperty(theKeyProp); hdl->createInstance("root/testsuite", ci); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::ALREADY_EXISTS); } // ModifyClass // CIM_ERR_INVALID_NAMESPACE try { hdl->modifyClass("badNamespace", cc); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // first create a class to modify try { CIMClass cc2("invalidTestSub"); cc2.setSuperClass("invalidTestBase"); CIMObjectPath cop(cc2.getName(), "root/testsuite"); hdl->createClass("root/testsuite", cc2); } catch (const CIMException& e) { TEST_ASSERT(0); } try { // test overriding an DISABLEOVERRIDE qualifier CIMClass cc2("invalidTestSub"); cc2.setSuperClass("invalidTestBase"); CIMQualifier assocQual2(assocQual); assocQual2.setValue(CIMValue(false)); cc2.addQualifier(assocQual2); hdl->modifyClass("root/testsuite", cc2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } try { // test adding an key to a subclass when the parent already has keys. CIMClass cc2("invalidTestSub"); cc2.setSuperClass("invalidTestBase"); CIMProperty theKeyProp2("theKeyProp2", CIMDataType::BOOLEAN); theKeyProp2.addQualifier(keyQual); cc2.addProperty(theKeyProp2); hdl->modifyClass("root/testsuite", cc2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } // CIM_ERR_NOT_FOUND try { CIMClass cc2("invalidTestSub2"); hdl->modifyClass("root/testsuite", cc2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // CIM_ERR_INVALID_SUPERCLASS try { CIMClass cc2(baseClass); cc2.setSuperClass("invalid"); hdl->modifyClass("root/testsuite", cc2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_SUPERCLASS); } // CIM_ERR_CLASS_HAS_CHILDREN - Can't get OpenWBEM to produce this as of July 30, 2002 // CIM_ERR_CLASS_HAS_INSTANCES - Can't get OpenWBEM to produce this as of July 30, 2002 // ModifyInstance CIMInstance ci = baseClass.newInstance(); ci.setProperty(theKeyProp); try { try { CIMObjectPath cop("root/testsuite", ci); hdl->deleteInstance("root/testsuite", cop); } catch (const CIMException& e) { } hdl->createInstance("root/testsuite", ci); } catch (const CIMException& e) { TEST_ASSERT(0); } // CIM_ERR_INVALID_NAMESPACE try { hdl->modifyInstance("badNamespace", ci); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { CIMInstance ci2(ci); ci2.setClassName("fooBad"); hdl->modifyInstance("root/testsuite", ci2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // CIM_ERR_NOT_FOUND try { CIMInstance ci2(ci); ci2.setProperty("theKeyProp", CIMValue(false)); hdl->modifyInstance("root/testsuite", ci2); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // EnumerateClasses // CIM_ERR_INVALID_NAMESPACE try { hdl->enumClassE("badNamespace", "foo"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { hdl->enumClassE("root/testsuite", "badClass"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // EnumerateClassNames // CIM_ERR_INVALID_NAMESPACE try { hdl->enumClassNamesE("badNamespace", "foo"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { hdl->enumClassNamesE("root/testsuite", "badClass"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // EnumerateInstances // CIM_ERR_INVALID_NAMESPACE try { hdl->enumInstancesE("badNamespace", "foo"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { hdl->enumInstancesE("root/testsuite", "badClass"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // EnumerateInstanceNames // CIM_ERR_INVALID_NAMESPACE try { hdl->enumInstanceNamesE("badNamespace", "foo"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { hdl->enumInstanceNamesE("root/testsuite", "badClass"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // ExecQuery // CIM_ERR_INVALID_NAMESPACE try { hdl->execQueryE("badNameSpace", "select * from junk", "wql1"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_QUERY_LANGUAGE_NOT_SUPPORTED try { hdl->execQueryE("root/testsuite", "select * from junk", "badql"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::QUERY_LANGUAGE_NOT_SUPPORTED); } // CIM_ERR_INVALID_QUERY try { hdl->execQueryE("root/testsuite", "xxx", "wql1"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_QUERY); } try { hdl->execQueryE("root/testsuite", "select * from junk", "wql1"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_QUERY); } // Associators // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->associatorsE("badNamespace", cop,"","","",""); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // AssociatorNames // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->associatorNamesE("badNamespace", cop, "", "", "", ""); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // References // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->referencesE("badNamespace", cop,"",""); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // ReferenceNames // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->referenceNamesE("badNamespace", cop,"",""); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // GetProperty // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->getProperty("badNamespace", cop, "theKeyProp"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { CIMObjectPath cop("badClass"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->getProperty("root/testsuite", cop, "theKeyProp"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // CIM_ERR_NOT_FOUND try { CIMObjectPath cop(baseClass.getName()); cop.setKeyValue("theKeyProp", CIMValue(false)); hdl->getProperty("root/testsuite", cop, "theKeyProp"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // CIM_ERR_NO_SUCH_PROPERTY try { CIMObjectPath cop(baseClass.getName()); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->getProperty("root/testsuite", cop, "badProp"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NO_SUCH_PROPERTY); } // SetProperty // CIM_ERR_INVALID_NAMESPACE try { CIMObjectPath cop("foo"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->setProperty("badNamespace", cop, "theKeyProp", CIMValue(true)); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_INVALID_CLASS try { CIMObjectPath cop("badClass"); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->setProperty("root/testsuite", cop, "theKeyProp", CIMValue(true)); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_CLASS); } // CIM_ERR_NOT_FOUND try { CIMObjectPath cop(baseClass.getName()); cop.setKeyValue("theKeyProp", CIMValue(false)); hdl->setProperty("root/testsuite", cop, "theKeyProp", CIMValue(false)); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // CIM_ERR_NO_SUCH_PROPERTY try { CIMObjectPath cop(baseClass.getName()); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->setProperty("root/testsuite", cop, "badProp", CIMValue(true)); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NO_SUCH_PROPERTY); } // CIM_ERR_TYPE_MISMATCH try { CIMObjectPath cop(baseClass.getName()); cop.setKeyValue("theKeyProp", CIMValue(true)); hdl->setProperty("root/testsuite", cop, "theKeyProp", CIMValue(String("x"))); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::TYPE_MISMATCH); } // GetQualifier // CIM_ERR_INVALID_NAMESPACE try { hdl->getQualifierType("badNamespace", CIMQualifier::CIM_QUAL_ABSTRACT); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_NOT_FOUND try { hdl->getQualifierType("root/testsuite", "badQualifierType"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // SetQualifier // CIM_ERR_INVALID_NAMESPACE try { CIMQualifierType cqt("fooqt"); cqt.setDataType(CIMDataType::BOOLEAN); cqt.addScope(CIMScope::ANY); hdl->setQualifierType("badNamespace", cqt); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // DeleteQualifier // CIM_ERR_INVALID_NAMESPACE try { hdl->deleteQualifierType("badNamespace", CIMQualifier::CIM_QUAL_ABSTRACT); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CIM_ERR_NOT_FOUND try { hdl->deleteQualifierType("root/testsuite", "badQualifierType"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // EnumerateQualifiers // CIM_ERR_INVALID_NAMESPACE try { hdl->enumQualifierTypesE("badNamespace"); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER // CreateNamespace // DeleteNamespace // EnumNameSpaces // invokeMethod // CIM_ERR_INVALID_NAMESPACE try { CIMParamValueArray in, out; hdl->invokeMethod("badNamespace", CIMObjectPath("EXP_BartComputerSystem"), "getstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_NAMESPACE); } // CIM_ERR_INVALID_PARAMETER - missing a required parameter try { CIMParamValueArray in, out; hdl->invokeMethod("root/testsuite", CIMObjectPath("EXP_BartComputerSystem"), "getstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } // CIM_ERR_INVALID_PARAMETER - wrong name of some parameter try { CIMParamValueArray in, out; in.push_back(CIMParamValue("io16", CIMValue(Int16(16)))); in.push_back(CIMParamValue("nullParam", CIMValue(CIMNULL))); in.push_back(CIMParamValue("s", CIMValue(String("input string")))); UInt8Array uint8array; in.push_back(CIMParamValue("uint8array", CIMValue(uint8array))); CIMObjectPathArray paths; in.push_back(CIMParamValue("pathsBAD", CIMValue(paths))); hdl->invokeMethod("root/testsuite", CIMObjectPath("EXP_BartComputerSystem"), "getstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } // CIM_ERR_INVALID_PARAMETER - wrong type of some parameter try { CIMParamValueArray in, out; in.push_back(CIMParamValue("io16", CIMValue(Int16(16)))); in.push_back(CIMParamValue("nullParam", CIMValue(CIMNULL))); in.push_back(CIMParamValue("s", CIMValue(String("input string")))); StringArray sarray; sarray.push_back("x"); in.push_back(CIMParamValue("uint8array", CIMValue(sarray))); CIMObjectPathArray paths; in.push_back(CIMParamValue("paths", CIMValue(paths))); hdl->invokeMethod("root/testsuite", CIMObjectPath("EXP_BartComputerSystem"), "getstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } // CIM_ERR_INVALID_PARAMETER - duplicate parameter try { CIMParamValueArray in, out; in.push_back(CIMParamValue("io16", CIMValue(Int16(16)))); in.push_back(CIMParamValue("nullParam", CIMValue(CIMNULL))); in.push_back(CIMParamValue("s", CIMValue(String("input string")))); UInt8Array uint8array; in.push_back(CIMParamValue("uint8array", CIMValue(uint8array))); CIMObjectPathArray paths; in.push_back(CIMParamValue("uint8array", CIMValue(paths))); hdl->invokeMethod("root/testsuite", CIMObjectPath("EXP_BartComputerSystem"), "getstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::INVALID_PARAMETER); } // CIM_ERR_NOT_FOUND - no class try { CIMParamValueArray in, out; hdl->invokeMethod("root/testsuite", CIMObjectPath("BADEXP_BartComputerSystem"), "getstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // CIM_ERR_NOT_FOUND - no instance try { CIMParamValueArray in, out; CIMObjectPath cop("EXP_BartComputerSystem"); cop.setKeyValue("Name", CIMValue("badKey")); cop.setKeyValue("CreationClassName", CIMValue("badKey")); hdl->invokeMethod("root/testsuite", cop, "getstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::NOT_FOUND); } // CIM_ERR_METHOD_NOT_FOUND try { CIMParamValueArray in, out; CIMObjectPath cop("EXP_BartComputerSystem"); hdl->invokeMethod("root/testsuite", cop, "BADgetstate", in, out); TEST_ASSERT(0); } catch (const CIMException& e) { TEST_ASSERT(e.getErrNo() == CIMException::METHOD_NOT_FOUND); } // cleanup hdl->deleteClass("root/testsuite", baseClass.getName()); }
void GroupFromAnnotation::GetGroupFromFile(FILE * log) { //Fill in annoGroups. StringArray tmp; FILE * file = fopen(groupFile,"r"); if(file==NULL) { printf("ERROR! Cannot open group file %s.\n",groupFile.c_str()); error("ERROR! Cannot open group file %s.\n",groupFile.c_str()); } String buffer; int line = 0; while (!feof(file)) { buffer.ReadLine(file); tmp.Clear(); tmp.AddTokens(buffer, SEPARATORS); if(tmp.Length()==0) continue; annoGroups.Push(tmp[0]); chrom.Push(tmp[1]); line++; } fclose(file); //Fill in SNPlist. SNPlist = new StringArray [line]; SNPNoAllele = new StringArray [line]; FILE * samefile = fopen(groupFile,"r"); line = 0; Vector pos; while (!feof(samefile)) { buffer.ReadLine(samefile); tmp.Clear(); pos.Clear(); tmp.AddTokens(buffer, "\t "); SNPlist[line].Dimension(0); SNPNoAllele[line].Dimension(0); for(int i=1;i<tmp.Length();i++) { SNPlist[line].Push(tmp[i]); StringArray sub; sub.Clear(); sub.AddTokens(tmp[i],":_/"); if(sub.Length()!=4) { printf("Warning: group %s has a variant %s that has invalid format. The correct format should be chr:pos:allele1:allele2.\n",tmp[0].c_str(),tmp[i].c_str()); fprintf(log,"Warning: group %s has a variant %s that has invalid format. The correct format should be chr:pos:allele1:allele2.\n",tmp[0].c_str(),tmp[i].c_str()); continue; } pos.Push(sub[1].AsInteger()); SNPNoAllele[line].Push(sub[0] + ":" + sub[1]); } //sort SNPlist[line] and SNPNoAllele[line] if(SNPlist[line].Length()>1) { Vector sorted_pos,order; sorted_pos.Copy(pos); sorted_pos.Sort(); order.Dimension(pos.Length()); for(int i=0;i<sorted_pos.Length();i++) { for(int j=0;j<pos.Length();j++) { if(sorted_pos[i]==pos[j]) { order[i]=j; break; } } } StringArray cp_SNPlist,cp_SNPNoAllele; cp_SNPlist.Dimension(SNPlist[line].Length()); cp_SNPNoAllele.Dimension(SNPNoAllele[line].Length()); for(int l=0;l<SNPlist[line].Length();l++) { cp_SNPlist[l] = SNPlist[line][l]; cp_SNPNoAllele[l] = SNPNoAllele[line][l]; } for(int i=0;i<order.Length();i++) { SNPlist[line][i] = cp_SNPlist[order[i]]; //printf("%s\t",SNPlist[line][i].c_str()); SNPNoAllele[line][i] = cp_SNPNoAllele[order[i]] ; } //printf("\n"); } line++; } fclose(samefile); }
static void test() { std::ostringstream oss; if(debug) printf("\ntestBitSetUtil\n"); StringArray fieldNames; PVFieldPtrArray pvFields; fieldNames.reserve(5); pvFields.reserve(5); fieldNames.push_back("timeStamp"); fieldNames.push_back("alarm"); fieldNames.push_back("voltage"); fieldNames.push_back("power"); fieldNames.push_back("current"); pvFields.push_back( pvDataCreate->createPVStructure(standardField->timeStamp())); pvFields.push_back( pvDataCreate->createPVStructure(standardField->alarm())); pvFields.push_back( pvDataCreate->createPVStructure( standardField->scalar(pvDouble,"alarm"))); pvFields.push_back( pvDataCreate->createPVStructure( standardField->scalar(pvDouble,"alarm"))); pvFields.push_back( pvDataCreate->createPVStructure( standardField->scalar(pvDouble,"alarm"))); PVStructurePtr pvs = pvDataCreate->createPVStructure( fieldNames,pvFields); if(debug) { oss.clear(); oss << "pvs" << std::endl; oss << *pvs << std::endl; std::cout << oss.str(); } int32 nfields = (int32)pvs->getNumberFields(); BitSetPtr bitSet = BitSet::create(nfields); for(int32 i=0; i<nfields; i++) bitSet->set(i); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } BitSetUtil::compress(bitSet,pvs); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } bitSet->clear(); PVFieldPtr pvField = pvs->getSubField("timeStamp"); int32 offsetTimeStamp = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("timeStamp.secondsPastEpoch"); int32 offsetSeconds = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("timeStamp.nanoseconds"); int32 offsetNano = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("timeStamp.userTag"); int32 offsetUserTag = (int32)pvField->getFieldOffset(); bitSet->set(offsetSeconds); BitSetUtil::compress(bitSet,pvs); testOk1(bitSet->get(offsetSeconds)==true); bitSet->set(offsetNano); bitSet->set(offsetUserTag); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } BitSetUtil::compress(bitSet,pvs); testOk1(bitSet->get(offsetSeconds)==false); testOk1(bitSet->get(offsetTimeStamp)==true); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } bitSet->clear(); pvField = pvs->getSubField("current"); int32 offsetCurrent = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("current.value"); int32 offsetValue = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("current.alarm"); int32 offsetAlarm = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("current.alarm.severity"); int32 offsetSeverity = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("current.alarm.status"); int32 offsetStatus = (int32)pvField->getFieldOffset(); pvField = pvs->getSubField("current.alarm.message"); int32 offsetMessage = (int32)pvField->getFieldOffset(); bitSet->set(offsetValue); bitSet->set(offsetSeverity); bitSet->set(offsetStatus); bitSet->set(offsetMessage); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } BitSetUtil::compress(bitSet,pvs); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } testOk1(bitSet->get(offsetCurrent)==true); bitSet->clear(); bitSet->set(offsetSeverity); bitSet->set(offsetStatus); bitSet->set(offsetMessage); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } BitSetUtil::compress(bitSet,pvs); if(debug) { oss.clear(); oss << "bitSet" << std::endl; oss << *bitSet << std::endl; std::cout << oss.str(); } testOk1(bitSet->get(offsetAlarm)==true); bitSet->clear(); printf("testBitSetUtil PASSED\n"); }
void GroupFromAnnotation::GetGeneMap(String path) { IFILE genemap; genemap = ifopen(mapFile,"r"); if(genemap==NULL) { if(mapFile=="../data/refFlat_hg19.txt") { mapFile += ".gz"; genemap = ifopen(mapFile,"r"); if(genemap==NULL) { int loc = path.Find("bin"); if(loc!=-1) { mapFile = path.Left(loc-1); mapFile += "/data/refFlat_hg19.txt"; } else { mapFile += "../data/refFlat_hg19.txt"; } genemap = ifopen(mapFile,"r"); } if(genemap==NULL) { mapFile += ".gz"; genemap = ifopen(mapFile,"r"); } if(genemap==NULL) error("Cannot open gene mapping file %s.\n",mapFile.c_str()); } else error("Cannot open gene mapping file %s.\n",mapFile.c_str()); } StringIntHash GeneLocHash; StringArray strand; int gene_idx =0; while(!ifeof(genemap)) { String buffer; buffer.ReadLine(genemap); StringArray record; record.AddTokens(buffer,"\t"); int loc = GeneLocHash.Integer(record[0]); if(loc==-1) { GeneLocHash.SetInteger(record[0],gene_idx); //save chr, start and end positions StringArray gene_chr; if(record[2][2]=='r' || record[2][2]=='R') record[2] = record[2].SubStr(3); gene_chr.AddTokens(record[2],"_,;."); if(gene_chr[0].Find("Un")!=-1) continue; /* if(ChrLocHash.Integer(gene_chr[0])==-1) { chr_count++; unique_chr.Push(gene_chr[0]); ChrLocHash.SetInteger(gene_chr[0],chr_count); } */ chr.Push(gene_chr[0]); //printf("%d\t%s\t%s\n",idx,record[0].c_str(),gene_chr[0].c_str()); start_pos.Push(record[4].AsInteger()); end_pos.Push(record[5].AsInteger()); strand.Push(record[3]); genename.Push(record[0]); gene_idx++; } else { //get the current chr StringArray gene_chr; if(record[2][2]=='r' || record[2][2]=='R') record[2] = record[2].SubStr(3); gene_chr.AddTokens(record[2],"_,;."); if(gene_chr[0].Find("Un")!=-1) continue; //check if strand and chr are consistent with previous record if(chr[loc]!=gene_chr[0]) //if(strand[loc]!=record[3] || chr[loc]!=gene_chr[0]) // printf("Gene %s in %s has multiple records in different chromosome or strand.\n",record[0].c_str(),mapFile.c_str()); continue; //update start and end position if(record[4].AsInteger()<start_pos[loc]) start_pos[loc] = record[4].AsInteger(); if(record[5].AsInteger()>end_pos[loc]) end_pos[loc] = record[5].AsInteger(); } } ifclose(genemap); //ifclose(genemap); chr_idx.Index(chr); String chr_=chr[chr_idx[0]]; for(int i=1;i<chr.Length();i++) { if(chr[chr_idx[i]]!=chr_) { ChrStartHash.SetInteger(chr[chr_idx[i]],i); ChrEndHash.SetInteger(chr_,i-1); chr_ = chr[chr_idx[i]]; } } }
dd_result_t DdParser::next_line(StringArray &components) { components.clear(); if(_status == DD_ERROR) return DD_ERROR; while( components.size() == 0 && _next_index < _contents.size()) { components = get_string_components(_contents[_next_index].data); ++_next_index; } if(_status == DD_ERROR) return DD_ERROR; if(_next_index >= _contents.size()) { _status = DD_END_FILE; return _status; } if(components[0] == "begin") { if(_current_device_type != "") { error() << "The keyword 'begin' is being used inside of a device's description!"; report_error(); return _status; } if(components.size() < 2) { error() << "The keyword 'begin' must be followed by a device type!"; report_error(); _current_device_type = ""; return _status; } else { _current_device_type = components[1]; } _status = DD_BEGIN_DEVICE; return _status; } if(components[0] == "end") { if(components.size() < 2) { error() << "The keyword 'end' must be followed by a device type!"; report_error(); return _status; } else { if(components[1] == _current_device_type) { _current_device_type = ""; } else { error() << "The device type accompanying this 'end' does not match the last 'begin'!"; report_error(); return _status; } } _status = DD_END_DEVICE; return _status; } _status = DD_OKAY; return _status; }
void GroupFromAnnotation::vcfInitialize() { // func_upper if ( function != "" ) { func_upper.AddTokens( function, "/" ); for( int i=0; i<func_upper.Length(); i++ ) func_upper[i] = func_upper[i].ToUpper(); } FILE * inFile; inFile = fopen(vcfInput,"r"); while (!feof(inFile)) { String buffer; buffer.ReadLine( inFile); if ( buffer[0] == '#' ) continue; StringArray vfield; vfield.AddTokens(buffer, "\t"); if ( vfield.Length() < 8 ) error("Annotation vcf only has %d columns!\n", vfield.Length()); StringArray info_semicolon; info_semicolon.AddTokens( vfield[7],";" ); int annofull_index = -1; for( int i=0; i<info_semicolon.Length(); i++ ) { String iheader = info_semicolon[i].SubStr(0,8); if (iheader == "ANNOFULL") { annofull_index = i; break; } } if (annofull_index == -1) continue; String anno_full_str = info_semicolon[annofull_index].SubStr(9); StringArray alts; alts.AddTokens( anno_full_str, "|" ); for( int a=0; a<alts.Length(); a++ ) { StringArray sub; sub.AddTokens( alts[a], ":/="); if (func_upper.Length() != 0) { // match before add for(int f =0;f<func_upper.Length();f++) { bool pattern_match = checkPatternMatch( sub, func_upper[f] ); if ( pattern_match ) { chrom.Push( vfield[0] ); addGeneToGroupHash( sub[0] ); break; } } } else { // no pattern to match chrom.Push( vfield[0] ); addGeneToGroupHash( sub[0] ); } } } // vectors SNPlist = new StringArray [geneCount]; SNPNoAllele = new StringArray [geneCount]; pos = new Vector [geneCount]; }
void CFileSpraySoapBindingEx::downloadFile(IEspContext &context, CHttpRequest* request, CHttpResponse* response) { try { StringBuffer netAddressStr, osStr, pathStr, nameStr; request->getParameter("NetAddress", netAddressStr); request->getParameter("OS", osStr); request->getParameter("Path", pathStr); request->getParameter("Name", nameStr); #if 0 StringArray files; IProperties* params = request->queryParameters(); Owned<IPropertyIterator> iter = params->getIterator(); if (iter && iter->first()) { while (iter->isValid()) { const char *keyname=iter->getPropKey(); if (!keyname || strncmp(keyname, "Names", 5)) continue; files.append(params->queryProp(iter->getPropKey())); iter->next(); } } #endif if (netAddressStr.length() < 1) throw MakeStringException(ECLWATCH_INVALID_INPUT, "Network address not specified."); if (pathStr.length() < 1) throw MakeStringException(ECLWATCH_INVALID_INPUT, "Path not specified."); if (nameStr.length() < 1) throw MakeStringException(ECLWATCH_INVALID_INPUT,"File name not specified."); char pathSep = '/'; if ((osStr.length() > 1) && (atoi(osStr.str())== OS_WINDOWS)) { pathSep = '\\'; } pathStr.replace(pathSep=='\\'?'/':'\\', pathSep); if (*(pathStr.str() + pathStr.length() -1) != pathSep) pathStr.append( pathSep ); StringBuffer fullName; fullName.appendf("%s%s", pathStr.str(), nameStr.str()); StringBuffer headerStr("attachment;"); headerStr.appendf("filename=%s", nameStr.str()); RemoteFilename rfn; rfn.setRemotePath(fullName.str()); SocketEndpoint ep(netAddressStr.str()); rfn.setIp(ep); Owned<IFile> rFile = createIFile(rfn); if (!rFile) throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE,"Cannot open file %s.",fullName.str()); OwnedIFileIO rIO = rFile->openShared(IFOread,IFSHfull); if (!rIO) throw MakeStringException(ECLWATCH_CANNOT_READ_FILE,"Cannot read file %s.",fullName.str()); IFileIOStream* ioS = createIOStream(rIO); context.addCustomerHeader("Content-disposition", headerStr.str()); response->setContent(ioS); response->setContentType(HTTP_TYPE_OCTET_STREAM); response->send(); } catch(IException* e) { FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR); } return; }
std::string Json::serialize(const Variant &data, bool &success, const std::string& tab) { std::string str; success = true; if( !data.isValid() ) // invalid or null? { str = "null"; } else if( (data.type() == Variant::List) || (data.type() == Variant::NStringArray) ) // variant is a list? { StringArray values; const VariantList rlist = data.toList(); for( VariantList::const_iterator it = rlist.begin(); it != rlist.end(); it++) { std::string serializedValue = serialize( *it, "" ); if( serializedValue.empty() ) { success = false; break; } values.push_back( serializedValue ); } str = "[ " + join( values, ", " ) + " ]"; } // else if(data.type() == Variant::Hash) // variant is a hash? // { // const VariantHash vhash = data.toHash(); // QHashIterator<std::string, Variant> it( vhash ); // str = "{ "; // QList<QByteArray> pairs; // // while(it.hasNext()) // { // it.next(); // QByteArray serializedValue = serialize(it.value(), ""); // // if(serializedValue.isNull()) // { // success = false; // break; // } // // pairs << tab.toAscii() + sanitizeString(it.key()).toUtf8() + " : " + serializedValue; // } // // str += join(pairs, ", "); // str += " }"; // } else if(data.type() == Variant::Map) // variant is a map? { VariantMap vmap = data.toMap(); str = "{ \n"; StringArray pairs; for( VariantMap::iterator it = vmap.begin(); it != vmap.end(); it++ ) { std::string serializedValue = serialize( it->second, tab + " "); if( serializedValue.empty()) { //success = false; pairs.push_back( tab + sanitizeString( it->first ) + std::string( " : \"nonSerializableValue\"" ) ); continue; } pairs.push_back( tab + sanitizeString( it->first ) + " : " + serializedValue ); } str += join(pairs, ",\n"); std::string rtab( tab ); rtab.resize( std::max<int>( 0, tab.size() - 2 ) ); str += std::string( "\n" ) + rtab + "}"; } else if((data.type() == Variant::String) || (data.type() == Variant::NByteArray)) // a string or a byte array? { str = sanitizeString( data.toString() ); } else if(data.type() == Variant::Double || data.type() == Variant::Float) // double? { str = StringHelper::format( 0xff, "\"%f\"", data.toDouble() ); if( str.find(".") == std::string::npos && str.find("e") == std::string::npos ) { str += ".0"; } } else if( data.type() == Variant::NTilePos) { TilePos pos = data.toTilePos(); str = StringHelper::format( 0xff, "[ %d, %d ]", pos.getI(), pos.getJ() ); } else if( data.type() == Variant::NSize) { Size size = data.toSize(); str = StringHelper::format( 0xff, "[ %d, %d ]", size.getWidth(), size.getHeight() ); } else if( data.type() == Variant::NPoint) { Point pos = data.toPoint(); str = StringHelper::format( 0xff, "[ %d, %d ]", pos.getX(), pos.getY() ); } else if( data.type() == Variant::NPointF) { PointF pos = data.toPointF(); str = StringHelper::format( 0xff, "[ \"%f\", \"%f\" ]", pos.getX(), pos.getY() ); } else if (data.type() == Variant::Bool) // boolean value? { str = data.toBool() ? "true" : "false"; } else if (data.type() == Variant::ULongLong) // large unsigned number? { str = StringHelper::format( 0xff, "%u", data.toULongLong() ); } else if ( data.canConvert( Variant::LongLong ) ) // any signed number? { str = StringHelper::format( 0xff, "%d", data.toLongLong() ); } else if (data.canConvert( Variant::Long )) { str = StringHelper::format( 0xff, "%d", data.toLongLong() ); } else if (data.canConvert( Variant::String ) ) // can value be converted to string? { // this will catch Date, DateTime, Url, ... str = sanitizeString( data.toString() ); } else { success = false; } if (success) { return str; } else { return std::string(); } }
StringArray getDeviceNames (bool wantInputNames) const { StringArray s; s.add ("Android Audio"); return s; }
//============================================================================== String AudioDeviceManager::initialise (const int numInputChannelsNeeded, const int numOutputChannelsNeeded, const XmlElement* const e, const bool selectDefaultDeviceOnFailure, const String& preferredDefaultDeviceName, const AudioDeviceSetup* preferredSetupOptions) { scanDevicesIfNeeded(); numInputChansNeeded = numInputChannelsNeeded; numOutputChansNeeded = numOutputChannelsNeeded; if (e != nullptr && e->hasTagName ("DEVICESETUP")) { lastExplicitSettings = new XmlElement (*e); String error; AudioDeviceSetup setup; if (preferredSetupOptions != nullptr) setup = *preferredSetupOptions; if (e->getStringAttribute ("audioDeviceName").isNotEmpty()) { setup.inputDeviceName = setup.outputDeviceName = e->getStringAttribute ("audioDeviceName"); } else { setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName"); setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName"); } currentDeviceType = e->getStringAttribute ("deviceType"); if (findType (currentDeviceType) == nullptr) { if (AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName)) currentDeviceType = type->getTypeName(); else if (availableDeviceTypes.size() > 0) currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName(); } setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize"); setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate"); setup.inputChannels .parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2); setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2); setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans"); setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans"); error = setAudioDeviceSetup (setup, true); midiInsFromXml.clear(); forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT") midiInsFromXml.add (c->getStringAttribute ("name")); const StringArray allMidiIns (MidiInput::getDevices()); for (int i = allMidiIns.size(); --i >= 0;) setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i])); if (error.isNotEmpty() && selectDefaultDeviceOnFailure) error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0, false, preferredDefaultDeviceName); setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput")); return error; } else { AudioDeviceSetup setup; if (preferredSetupOptions != nullptr) { setup = *preferredSetupOptions; } else if (preferredDefaultDeviceName.isNotEmpty()) { for (int j = availableDeviceTypes.size(); --j >= 0;) { AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j); const StringArray outs (type->getDeviceNames (false)); for (int i = 0; i < outs.size(); ++i) { if (outs[i].matchesWildcard (preferredDefaultDeviceName, true)) { setup.outputDeviceName = outs[i]; break; } } const StringArray ins (type->getDeviceNames (true)); for (int i = 0; i < ins.size(); ++i) { if (ins[i].matchesWildcard (preferredDefaultDeviceName, true)) { setup.inputDeviceName = ins[i]; break; } } } } insertDefaultDeviceNames (setup); return setAudioDeviceSetup (setup, false); } }
StringArray StringArray::fromLines (StringRef stringToBreakUp) { StringArray s; s.addLines (stringToBreakUp); return s; }
StructureConstPtr StandardField::createProperties(String id,FieldConstPtr field,String properties) { bool gotAlarm = false; bool gotTimeStamp = false; bool gotDisplay = false; bool gotControl = false; bool gotValueAlarm = false; int numProp = 0; if(properties.find("alarm")!=String::npos) { gotAlarm = true; numProp++; } if(properties.find("timeStamp")!=String::npos) { gotTimeStamp = true; numProp++; } if(properties.find("display")!=String::npos) { gotDisplay = true; numProp++; } if(properties.find("control")!=String::npos) { gotControl = true; numProp++; } if(properties.find("valueAlarm")!=String::npos) { gotValueAlarm = true; numProp++; } StructureConstPtr valueAlarm; Type type= field->getType(); while(gotValueAlarm) { if(type==epics::pvData::scalar || type==epics::pvData::scalarArray) { ScalarType scalarType = (type==epics::pvData::scalar) ? static_pointer_cast<const Scalar>(field)->getScalarType() : static_pointer_cast<const ScalarArray>(field)->getElementType(); switch(scalarType) { case pvBoolean: valueAlarm = booleanAlarmField; break; case pvByte: valueAlarm = byteAlarmField; break; case pvShort: valueAlarm = shortAlarmField; break; case pvInt: valueAlarm = intAlarmField; break; case pvLong: valueAlarm = longAlarmField; break; case pvUByte: valueAlarm = ubyteAlarmField; break; case pvUShort: valueAlarm = ushortAlarmField; break; case pvUInt: valueAlarm = uintAlarmField; break; case pvULong: valueAlarm = ulongAlarmField; break; case pvFloat: valueAlarm = floatAlarmField; break; case pvDouble: valueAlarm = doubleAlarmField; break; case pvString: throw std::logic_error(String("valueAlarm property not supported for pvString")); } break; } if(type==structure) { StructureConstPtr structurePtr = static_pointer_cast<const Structure>(field); StringArray names = structurePtr->getFieldNames(); if(names.size()==2) { FieldConstPtrArray fields = structurePtr->getFields(); FieldConstPtr first = fields[0]; FieldConstPtr second = fields[1]; String nameFirst = names[0]; String nameSecond = names[1]; int compareFirst = nameFirst.compare("index"); int compareSecond = nameSecond.compare("choices"); if(compareFirst==0 && compareSecond==0) { if(first->getType()==epics::pvData::scalar && second->getType()==epics::pvData::scalarArray) { ScalarConstPtr scalarFirst = static_pointer_cast<const Scalar>(first); ScalarArrayConstPtr scalarArraySecond = static_pointer_cast<const ScalarArray>(second); if(scalarFirst->getScalarType()==pvInt && scalarArraySecond->getElementType()==pvString) { valueAlarm = enumeratedAlarmField; break; } } } } } throw std::logic_error(String("valueAlarm property for illegal type")); } size_t numFields = numProp+1; FieldConstPtrArray fields(numFields); StringArray names(numFields); int next = 0; names[0] = "value"; fields[next++] = field; if(gotAlarm) { names[next] = "alarm"; fields[next++] = alarmField; } if(gotTimeStamp) { names[next] = "timeStamp"; fields[next++] = timeStampField; } if(gotDisplay) { names[next] = "display"; fields[next++] = displayField; } if(gotControl) { names[next] = "control"; fields[next++] = controlField; } if(gotValueAlarm) { names[next] = "valueAlarm"; fields[next++] = valueAlarm; } return fieldCreate->createStructure(id,names,fields); }