//@Override
/*public*/ void XmlFileLocationAction::actionPerformed(ActionEvent* ev) {

    /*final*/ QString user = FileUtil::getUserFilesPath();
    /*final*/ QString roster = Roster::getDefault()->getRosterLocation();
    /*final*/ QString profile = FileUtil::getProfilePath();
    /*final*/ QString settings = FileUtil::getPreferencesPath();
    /*final*/ QString scripts = FileUtil::getScriptsPath();
    /*final*/ QString prog = System::getProperty("user.dir");
    /*final*/ QString log = System::getProperty("jmri.log.path");

    QString configName = System::getProperty("org.jmri.Apps.configFilename");
    if (!( File(configName).isAbsolute())) {
        // must be relative, but we want it to
        // be relative to the preferences directory
        configName = profile + configName;
    }

    JFrame* frame = new JmriJFrame();  // to ensure fits
    frame->setTitle(tr("Locations"));

    QWidget* pane = new QWidget();
    pane->setLayout(new QVBoxLayout); //(pane, BoxLayout.Y_AXIS));

    QWidget* buttons = new QWidget();
    buttons->setLayout(new FlowLayout());
    pane->layout()->addWidget(buttons);

    QPushButton* b = new QPushButton("Open User Files Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        //@Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new File(user));
//            } catch (IOException e) {
//                XmlFileLocationAction.log.error("Error when opening user files location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening user files location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openUserFilesButton()));
    b = new QPushButton("Open Roster Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(roster));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening roster location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening roster location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openRosterButton()));
    b = new QPushButton("Open Profile Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(profile));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening profile location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening profile location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openProfileButton()));
    b = new QPushButton("Open Settings Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(settings));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening settings location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening settings location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openSettingsButton()));
    b = new QPushButton("Open Scripts Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(scripts));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening scripts location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening scripts location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openScriptsButton(ActionEvent*)));
    b = new QPushButton("Open Program Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(prog));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening program location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening program location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openProgramButton()));
    b = new QPushButton("Open Log Files Location");
    buttons->layout()->addWidget(b);
//    b.addActionListener(new ActionListener() {
//        @Override
//        /*public*/ void actionPerformed(ActionEvent event) {
//            try {
//                Desktop.getDesktop().open(new java.io.File(log));
//            } catch (java.io.IOException e) {
//                XmlFileLocationAction.log.error("Error when opening log files location: " + e);
//            } catch (UnsupportedOperationException e) {
//                XmlFileLocationAction.log.error("Error when opening log files location: " + e);
//            }
//        }
//    });
    connect(b, SIGNAL(clicked(bool)), this, SLOT(on_openLogFilesButton()));

    //QScrollArea* scroll = new JScrollPane(pane);
    //frame.getContentPane().add(scroll);
    //QVBoxLayout* thisLayout = new QVBoxLayout(frame->getContentPane());

    QTextBrowser* textPane = new QTextBrowser();
    //textPane->setEditable(false);
    pane->layout()->addWidget(textPane);
    frame->getContentPane()->layout()->addWidget(pane);

    textPane->append("User Files Location: " + user + "\n");

    textPane->append("Roster Location: " + roster + "\n");

    textPane->append("Profile Location: " + profile + "\n");

    textPane->append("Settings Location: " + settings + "\n");

    textPane->append("Current Config file: " + configName + "\n");

    textPane->append("Scripts Location: " + scripts + "\n");

    textPane->append("Program Location: " + prog + "\n");

    textPane->append("Log Files Location: " + log + "\n");

    addLogFiles(textPane, log);

    frame->adjustSize();
    frame->setVisible(true);
}
예제 #2
0
파일: optionsS.cpp 프로젝트: fduhia/Easy68k
//--------------------------------------------------------------------------
// Loads all the editor settings from file.  True and false settings are saved
//  as 1 and 0.
//  If the contents of settings.dat to not match expected then default values
//  are used.
void __fastcall TOptions::LoadSettings()
{
  try {
    const int SIZE = 256;
    AnsiString str;
    str = ExtractFilePath(Application->ExeName) + "settings.dat";
    char fileName[SIZE];
    strcpy(fileName, str.c_str());        // fileName is path + settings.dat

    defaultSettings();          // start with default settings

    if(FileExists(fileName))    //check if settings file exists
    {                           //if it did then load all the settings
      char buffer[SIZE+1];
      char temp[SIZE+1];        //temp storage
      unsigned int index;       //looping index
      ifstream File(fileName);  //open settings file

      // read and set flags from file
      File.getline(buffer, SIZE); //first line contains version number

      File.getline(buffer, SIZE); // 'generate list' setting
      if (!strcmp(&buffer[1],"$generate list")) {   // if expected setting
        if(buffer[0] == '1') {
          listFlag = true;
          chkGenList->Checked = true;
        } else {
          listFlag   = false;
          chkGenList->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'generate s-record' setting
      if (!strcmp(&buffer[1],"$generate s-record")) {   // if expected setting
        if(buffer[0] == '1') {
          objFlag = true;
          chkGenSRec->Checked = true;
        } else {
          objFlag    = false;
          chkGenSRec->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'save before assemble' setting
      if (!strcmp(&buffer[1],"$save then assemble")) {  // if expected setting
        if(buffer[0] == '1') {
          bSave = true;
          chkSave->Checked = true;
        } else {
          bSave      = false;
          chkSave->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'Show Warnings' setting
      if (!strcmp(&buffer[1],"$show warnings")) {  // if expected setting
        if(buffer[0] == '1') {
          WARflag = true;
          chkShowWarnings->Checked = true;
        } else {
          WARflag    = false;
          chkShowWarnings->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'cross reference' setting
      if (!strcmp(&buffer[1],"$cross reference")) {  // if expected setting
        if(buffer[0] == '1') {
          CREflag = true;
          chkCrossRef->Checked = true;
        } else {
          CREflag    = false;
          chkCrossRef->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'macro expanded setting' setting
      if (!strcmp(&buffer[1],"$macros expanded")) {  // if expected setting
        if(buffer[0] == '1') {
          MEXflag = true;
          chkMacEx->Checked = true;
        } else {
          MEXflag    = false;
          chkMacEx->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'structured assembly expanded setting' setting
      if (!strcmp(&buffer[1],"$structured expand")) {  // if expected setting
        if(buffer[0] == '1') {
          SEXflag = true;
          chkStrucEx->Checked = true;
        } else {
          SEXflag    = false;
          chkStrucEx->Checked = false;
        }
      }

      File.getline(buffer, SIZE); // 'constants expanded setting' setting
      if (!strcmp(&buffer[1],"$constants expand")) {  // if expected setting
        if(buffer[0] == '1') {
          CEXflag = true;
          chkConstantsEx->Checked = true;
        } else {
          CEXflag    = false;
          chkConstantsEx->Checked = false;
        }
      }

      index = 0;
      File.getline(buffer, SIZE);        // 'font name' setting
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$font name")) {  // if expected setting
        EditorOptionsForm->cbFont->Text = temp;
      }

      File.getline(buffer, SIZE);        // 'font size' setting
      index = 0;                       //reset looping index
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$font size")) {  // if expected setting
        EditorOptionsForm->cbSize->Text = temp;
      }

      File.getline(buffer, SIZE);        // Tab Type setting
      if (!strcmp(&buffer[1],"$tab type")) {  // if expected setting
        if(buffer[0] == '0') {
          EditorOptionsForm->AssemblyTabs->Checked = true;
          EditorOptionsForm->FixedTabs->Checked = false;
          tabType = Assembly;
        } else {
          EditorOptionsForm->AssemblyTabs->Checked = false;
          EditorOptionsForm->FixedTabs->Checked = true;
          tabType = Fixed;
        }
      }

      File.getline(buffer, SIZE);         // Fixed Tab Size
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$fixed tab size")) {  // if expected setting
        EditorOptionsForm->FixedTabSize->Value = atoi(temp);
      }

      File.getline(buffer, SIZE);        // maximizedEdit setting
      if (!strcmp(&buffer[1],"$maximized edit")) {  // if expected setting
        if(buffer[0] == '1') {
          maximizedEdit = true;
        } else {
          maximizedEdit = false;
        }
      }

      File.getline(buffer, SIZE);        // autoIndent setting
      if (!strcmp(&buffer[1],"$auto indent")) {  // if expected setting
        if(buffer[0] == '1') {
          autoIndent = true;
          EditorOptionsForm->AutoIndent->Checked = true;
        } else {
          autoIndent = false;
          EditorOptionsForm->AutoIndent->Checked = false;
        }
      }

      File.getline(buffer, SIZE);        // realTabs setting
      if (!strcmp(&buffer[1],"$real tabs")) {  // if expected setting
        if(buffer[0] == '1') {
          realTabs = true;
          EditorOptionsForm->RealTabs->Checked = true;
        } else {
          realTabs = false;
          EditorOptionsForm->RealTabs->Checked = false;
        }
      }

      File.getline(buffer, SIZE);        // Bitfield setting
      if (!strcmp(&buffer[1],"$assemble bit field")) {  // if expected setting
        if(buffer[0] == '1') {
          BITflag = true;
          chkBitfield->Checked = true;
        } else {
          BITflag    = false;
          chkBitfield->Checked = false;
        }
      }

      File.getline(buffer, SIZE);         // 'Main Form Top' setting
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$main top")) {  // if expected setting
        Main->Top = atoi(temp);
      }

      File.getline(buffer, SIZE);         // 'Main Form Left' setting
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$main left")) {  // if expected setting
        Main->Left = atoi(temp);
      }

      File.getline(buffer, SIZE);         // 'Main Form Height' setting
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$main height")) {  // if expected setting
        Main->Height = atoi(temp);
      }

      File.getline(buffer, SIZE);         // 'Main Form Width' setting
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$main width")) {  // if expected setting
        Main->Width = atoi(temp);
      }

      // Syntax Highlight stuff
      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$code color")) {  // if expected setting
        codeStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$code bold")) {  // if expected setting
        codeStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$code italic")) {  // if expected setting
        codeStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$code underline")) {  // if expected setting
        codeStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$unknown color")) {  // if expected setting
        unknownStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$unknown bold")) {  // if expected setting
        unknownStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$unknown italic")) {  // if expected setting
        unknownStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$unknown underline")) {  // if expected setting
        unknownStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$directive color")) {  // if expected setting
        directiveStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$directive bold")) {  // if expected setting
        directiveStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$directive italic")) {  // if expected setting
        directiveStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$directive underline")) {  // if expected setting
        directiveStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$comment color")) {  // if expected setting
        commentStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$comment bold")) {  // if expected setting
        commentStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$comment italic")) {  // if expected setting
        commentStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$comment underline")) {  // if expected setting
        commentStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$label color")) {  // if expected setting
        labelStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$label bold")) {  // if expected setting
        labelStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$label italic")) {  // if expected setting
        labelStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$label underline")) {  // if expected setting
        labelStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$structure color")) {  // if expected setting
        structureStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$structure bold")) {  // if expected setting
        structureStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$structure italic")) {  // if expected setting
        structureStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$structure underline")) {  // if expected setting
        structureStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$error color")) {  // if expected setting
        errorStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$error bold")) {  // if expected setting
        errorStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$error italic")) {  // if expected setting
        errorStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$error underline")) {  // if expected setting
        errorStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$text color")) {  // if expected setting
        textStyle.color = (TColor)atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$text bold")) {  // if expected setting
        textStyle.bold = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$text italic")) {  // if expected setting
        textStyle.italic = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$text underline")) {  // if expected setting
        textStyle.underline = atoi(temp);
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$highlight disabled")) {  // if expected setting
        highlightDisabled = atoi(temp);
      }

      File.getline(buffer, SIZE);        // Print w/Black
      if (!strcmp(&buffer[1],"$print w/black")) {  // if expected setting
        if(buffer[0] == '1')
          EditorOptionsForm->PrintBlack->Checked = true;
        else
          EditorOptionsForm->PrintBlack->Checked = false;
      }

      File.getline(buffer,SIZE);
      index = 0;
      while(buffer[index] != '$' && index < SIZE)
      {
        temp[index] = buffer[index];
        index++;
      }
      temp[index] = '\0';
      if (!strcmp(&buffer[index],"$background color")) {  // if expected setting
        backColor = (TColor)atoi(temp);
      }

      File.close();
    } // endif
  }
  catch( ... ) {
    MessageDlg("Error loading editor settings",mtInformation, TMsgDlgButtons() << mbOK,0);
    return;
  }
}
예제 #3
0
파일: SD.cpp 프로젝트: c1t1zen1/RadioMusic
File SDClass::open(const char *filepath, uint8_t mode) {
  /*

     Open the supplied file path for reading or writing.

     The file content can be accessed via the `file` property of
     the `SDClass` object--this property is currently
     a standard `SdFile` object from `sdfatlib`.

     Defaults to read only.

     If `write` is true, default action (when `append` is true) is to
     append data to the end of the file.

     If `append` is false then the file will be truncated first.

     If the file does not exist and it is opened for writing the file
     will be created.

     An attempt to open a file for reading that does not exist is an
     error.

   */

  int pathidx;

  // do the interative search
  SdFile parentdir = getParentDir(filepath, &pathidx);
  // no more subdirs!

  filepath += pathidx;

  if (! filepath[0]) {
    // it was the directory itself!
    return File(parentdir, "/");
  }

  // Open the file itself
  SdFile file;

  // failed to open a subdir!
  if (!parentdir.isOpen())
    return File();

  // there is a special case for the Root directory since its a static dir
  if (parentdir.isRoot()) {
    if ( ! file.open(SD.root, filepath, mode)) {
      // failed to open the file :(
      return File();
    }
    // dont close the root!
  } else {
    if ( ! file.open(parentdir, filepath, mode)) {
      return File();
    }
    // close the parent
    parentdir.close();
  }

  if (mode & (O_APPEND | O_WRITE)) 
    file.seekSet(file.fileSize());
  return File(file, filepath);
}
BitcoinGUI::BitcoinGUI(QWidget *parent):
    QMainWindow(parent),
    clientModel(0),
    walletModel(0),
    encryptWalletAction(0),
    changePassphraseAction(0),
    lockWalletToggleAction(0),
    aboutQtAction(0),
    trayIcon(0),
    notificator(0),
    rpcConsole(0)
{
    resize(940, 550);
    setWindowTitle(tr("MintCoin") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
    qApp->setWindowIcon(QIcon(":icons/bitcoin"));
    setWindowIcon(QIcon(":icons/bitcoin"));
#else
    setUnifiedTitleAndToolBarOnMac(true);
    QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
    // Accept D&D of URIs
    setAcceptDrops(true);

    // Create actions for the toolbar, menu bar and tray/dock icon
    createActions();

    // Create application menu bar
    createMenuBar();

    // Create the toolbars
    createToolBars();

    // Create the tray icon (or setup the dock icon)
    createTrayIcon();

    // Create tabs
    overviewPage = new OverviewPage();

    transactionsPage = new QWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout();
    transactionView = new TransactionView(this);
    vbox->addWidget(transactionView);
    transactionsPage->setLayout(vbox);

    addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);

    receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);

    sendCoinsPage = new SendCoinsDialog(this);

    merchantPage = new MerchantPage(this);

    recurringSendPage = new RecurringSendPage(this);

    signVerifyMessageDialog = new SignVerifyMessageDialog(this);

    centralWidget = new QStackedWidget(this);
    centralWidget->addWidget(overviewPage);
    centralWidget->addWidget(transactionsPage);
    centralWidget->addWidget(addressBookPage);
    centralWidget->addWidget(receiveCoinsPage);
    centralWidget->addWidget(sendCoinsPage);
    centralWidget->addWidget(recurringSendPage);
    centralWidget->addWidget(merchantPage);
    setCentralWidget(centralWidget);

    // Create status bar
    statusBar();

    // Status bar notification icons
    QFrame *frameBlocks = new QFrame();
    frameBlocks->setContentsMargins(0,0,0,0);
    frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
    frameBlocksLayout->setContentsMargins(3,0,3,0);
    frameBlocksLayout->setSpacing(3);
    labelEncryptionIcon = new QLabel();
    labelMintingIcon = new QLabel();
    labelConnectionsIcon = new QLabel();
    labelBlocksIcon = new QLabel();
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelEncryptionIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelMintingIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelConnectionsIcon);
    frameBlocksLayout->addStretch();
    frameBlocksLayout->addWidget(labelBlocksIcon);
    frameBlocksLayout->addStretch();

    // Set minting pixmap
    labelMintingIcon->setPixmap(QIcon(":/icons/minting").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
    labelMintingIcon->setEnabled(false);
    // Add timer to update minting icon
    QTimer *timerMintingIcon = new QTimer(labelMintingIcon);
    timerMintingIcon->start(MODEL_UPDATE_DELAY);
    connect(timerMintingIcon, SIGNAL(timeout()), this, SLOT(updateMintingIcon()));
    // Add timer to update minting weights
    QTimer *timerMintingWeights = new QTimer(labelMintingIcon);
    timerMintingWeights->start(30 * 1000);
    connect(timerMintingWeights, SIGNAL(timeout()), this, SLOT(updateMintingWeights()));
    // Set initial values for user and network weights
    nWeight=0;
    nNetworkWeight = 0;

    // Progress bar and label for blocks download
    progressBarLabel = new QLabel();
    progressBarLabel->setVisible(false);
    progressBar = new QProgressBar();
    progressBar->setAlignment(Qt::AlignCenter);
    progressBar->setVisible(false);

    // Override style sheet for progress bar for styles that have a segmented progress bar,
    // as they make the text unreadable (workaround for issue #1071)
    // See https://qt-project.org/doc/qt-4.8/gallery.html
    QString curStyle = qApp->style()->metaObject()->className();
    if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
    {
        progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
    }

    statusBar()->addWidget(progressBarLabel);
    statusBar()->addWidget(progressBar);
    statusBar()->addPermanentWidget(frameBlocks);

    syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
    qApp->setStyleSheet("background-color: #effbef;");
    //load stylesheet if present
    QFile File("style/stylesheet.qss");
    File.open(QFile::ReadOnly);
    QString StyleSheet = QLatin1String(File.readAll());
    qApp->setStyleSheet(StyleSheet);

    // Clicking on a transaction on the overview page simply sends you to transaction history page
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
    connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));

    // Double-clicking on a transaction on the transaction history page shows details
    connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));

    rpcConsole = new RPCConsole(this);
    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));

    // Clicking on "Verify Message" in the address book sends you to the verify message tab
    connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
    // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
    connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));

    gotoOverviewPage();
    statusBar()->showMessage(tr("Remember to make an external backup of your wallet"));
    QTimer::singleShot(30000, this, SLOT(noMessage()));
}
예제 #5
0
void File::findFileSystemRoots (Array<File>& destArray)
{
    destArray.add (File ("/"));
}
예제 #6
0
//==============================================================================
void BinaryResources::fillInGeneratedCode (GeneratedCode& code) const
{
    if (resources.size() > 0)
    {
        code.publicMemberDeclarations << "// Binary resources:\n";

        MemoryOutputStream defs;

        defs << "//==============================================================================\n";
        defs << "// Binary resources - be careful not to edit any of these sections!\n\n";

        for (int i = 0; i < resources.size(); ++i)
        {
            code.publicMemberDeclarations
                << "static const char* "
                << resources[i]->name
                << ";\nstatic const int "
                << resources[i]->name
                << "Size;\n";

            const String name (resources[i]->name);
            const MemoryBlock& mb = resources[i]->data;

            defs << "// JUCER_RESOURCE: " << name << ", " << (int) mb.getSize()
                << ", \""
                << File (resources[i]->originalFilename)
                    .getRelativePathFrom (code.document->getCppFile())
                    .replaceCharacter ('\\', '/')
                << "\"\n";

            String line1;
            line1 << "static const unsigned char resource_"
                  << code.className << "_" << name << "[] = { ";

            defs << line1;

            int charsOnLine = line1.length();

            for (size_t j = 0; j < mb.getSize(); ++j)
            {
                const int num = (int) (unsigned char) mb[j];
                defs << num << ',';

                charsOnLine += 2;
                if (num >= 10)   ++charsOnLine;
                if (num >= 100)  ++charsOnLine;

                if (charsOnLine >= 200)
                {
                    charsOnLine = 0;
                    defs << '\n';
                }
            }

            defs
              << "0,0};\n\n"
                 "const char* " << code.className << "::" << name
              << " = (const char*) resource_" << code.className << "_" << name
              << ";\nconst int "
              << code.className << "::" << name << "Size = "
              << (int) mb.getSize()
              << ";\n\n";
        }

        code.staticMemberDefinitions << defs.toString();
    }
}
예제 #7
0
bool PureImageCache::CreateEmptyDB(const QString &file)
{
#ifdef DEBUG_PUREIMAGECACHE
    qDebug()<<"Create database at!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!:"<<file;
#endif //DEBUG_PUREIMAGECACHE
    QFileInfo File(file);
    QDir dir=File.absoluteDir();
    QString path=dir.absolutePath();
    QString filename=File.fileName();
    if(File.exists())
        QFile(filename).remove();
    if(!dir.exists())
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: Cache path doesn't exist, try to create";
#endif //DEBUG_PUREIMAGECACHE
        if(!dir.mkpath(path))
        {
#ifdef DEBUG_PUREIMAGECACHE
            qDebug()<<"CreateEmptyDB: Could not create path";
#endif //DEBUG_PUREIMAGECACHE
            return false;
        }
    }
    addDatabaseMutex.lock();
    QSqlDatabase db(QSqlDatabase::addDatabase("QSQLITE",QLatin1String("CreateConn")));
    addDatabaseMutex.unlock();
    db.setDatabaseName(file);
    if (!db.open())
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: Unable to create database";
#endif //DEBUG_PUREIMAGECACHE

        return false;
    }
    QSqlQuery query(db);
    query.exec("CREATE TABLE IF NOT EXISTS Tiles (id INTEGER NOT NULL PRIMARY KEY, X INTEGER NOT NULL, Y INTEGER NOT NULL, Zoom INTEGER NOT NULL, Type INTEGER NOT NULL,Date TEXT)");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec("CREATE TABLE IF NOT EXISTS TilesData (id INTEGER NOT NULL PRIMARY KEY CONSTRAINT fk_Tiles_id REFERENCES Tiles(id) ON DELETE CASCADE, Tile BLOB NULL)");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec(
                "CREATE TRIGGER fki_TilesData_id_Tiles_id "
                "BEFORE INSERT ON [TilesData] "
                "FOR EACH ROW BEGIN "
                "SELECT RAISE(ROLLBACK, 'insert on table TilesData violates foreign key constraint fki_TilesData_id_Tiles_id') "
                "WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL; "
                "END");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec(
                "CREATE TRIGGER fku_TilesData_id_Tiles_id "
                "BEFORE UPDATE ON [TilesData] "
                "FOR EACH ROW BEGIN "
                "SELECT RAISE(ROLLBACK, 'update on table TilesData violates foreign key constraint fku_TilesData_id_Tiles_id') "
                "WHERE (SELECT id FROM Tiles WHERE id = NEW.id) IS NULL; "
                "END");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    query.exec(
                "CREATE TRIGGER fkdc_TilesData_id_Tiles_id "
                "BEFORE DELETE ON Tiles "
                "FOR EACH ROW BEGIN "
                "DELETE FROM TilesData WHERE TilesData.id = OLD.id; "
                "END");
    if(query.numRowsAffected()==-1)
    {
#ifdef DEBUG_PUREIMAGECACHE
        qDebug()<<"CreateEmptyDB: "<<query.lastError().driverText();
#endif //DEBUG_PUREIMAGECACHE
        db.close();
        return false;
    }
    db.close();
    QSqlDatabase::removeDatabase(QLatin1String("CreateConn"));
    return true;
}
void ribi::Chess::GameWidget::Test() noexcept
{
  //Testing Chess::Piece exactly once
  {
    static bool is_tested = false;
    if (is_tested) return;
    is_tested = true;
  }
  const ribi::TestTimer test_timer(__func__,__FILE__,1.0);
  #ifdef FIX_ISSUE_240
  {
    {
      const boost::shared_ptr<Chess::Game> game
        = boost::make_shared<Chess::Game>();
      const boost::shared_ptr<Chess::ChessWidget> w(
        new GameWidget(game,Geometry().CreateRect(0,0,100,100)));
      w->ClickPixel(-1,-1);
      w->ClickPixel(1000,1000);
    }
    {
      const boost::shared_ptr<Chess::Game> game
        = boost::make_shared<Chess::Game>();
      const boost::shared_ptr<Chess::GameWidget> widget(
        new Chess::GameWidget(game,Geometry().CreateRect(0,0,100,100)));
      assert(widget->GetSelector()->GetCursor()->GetFile() == Chess::File("a"));
      assert(widget->GetSelector()->GetCursor()->GetRank() == Chess::Rank("1"));
      assert(!widget->GetSelector()->GetSelected());
      //Check clicking: cursor will always follow
      for (int x=0;x!=8;++x)
      {
        for (int y=0;y!=8;++y)
        {
          const boost::shared_ptr<Square> square {
            SquareFactory().Create(
              File(x),Rank(y)
            )
          };
          widget->Click(square);
          assert(*widget->GetSelector()->GetCursor() == *square);
        }
      }
      //Check selection: Board::Widget will select any Chess::Piece, Board::Game only those of the active player
      //Click on own piece, selecting it
      {
        const boost::shared_ptr<Square> square {
          SquareFactory().Create("b1")
        };
        widget->Click(square);
      }
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("b1"));
      assert(widget->GetSelector()->GetSelected());
      assert(*widget->GetSelector()->GetSelected() == *SquareFactory().Create("b1"));

      //Click on empty square, selected piece remains
      widget->Click(SquareFactory().Create("d4"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("d4"));
      assert(widget->GetSelector()->GetSelected());
      assert(*widget->GetSelector()->GetSelected() == *SquareFactory().Create("b1"));

      //Click on selected square, undoing selection
      widget->Click(SquareFactory().Create("b1"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("b1"));
      assert(!widget->GetSelector()->GetSelected());

      //Click on enemy square, Chess::Board will select it
      widget->Click(SquareFactory().Create("h8"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("g8"));
      assert(!widget->GetSelector()->GetSelected());

      //Playing e7-e5 must succeed for a Board, must fail for a Game
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e7")));
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e5")));
      widget->Click(SquareFactory().Create("e7"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e7"));
      assert(!widget->GetSelector()->GetSelected());

      widget->Click(SquareFactory().Create("e5"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e5"));
      assert(!widget->GetSelector()->GetSelected());
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e7")));
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e5")));

      //Playing e2-e4 must succeed for both Board and Game
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e2")));
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e4")));
      widget->Click(SquareFactory().Create("e2"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e2"));
      assert(widget->GetSelector()->GetSelected());
      assert(*widget->GetSelector()->GetSelected() == *SquareFactory().Create("e2"));

      widget->Click(SquareFactory().Create("e4"));
      assert(*widget->GetSelector()->GetCursor() == *SquareFactory().Create("e4"));
      assert(!widget->GetSelector()->GetSelected());
      assert(!game->GetBoard()->GetPiece(SquareFactory().Create("e2")));
      assert( game->GetBoard()->GetPiece(SquareFactory().Create("e4")));
    }
  }
  #endif
}
예제 #9
0
void QVX_TensileTest::RunTensileTest(QString* pDispMessage)
{
	QFile File(OutFilePath);
		
	if (!File.open(QIODevice::WriteOnly | QIODevice::Text)) {
		ProgressMessage = "Could not open file. Aborting.";
		return;
	}
	QTextStream out(&File); 

//	double CurMaxDisp = 9e9;
	std::string IntMsg;

	vfloat StepPercAmt = 1.0/NumStep;
	int VoxCount = NumVox();

	int count = 0;
	int MinimumPerStep = 5;

	int NumBCs = pEnv->GetNumBCs();
	for (int j=0; j<NumBCs; j++){
		if (pEnv->GetBC(j)->Displace.Length2() == 0 ) continue; //if zero displacement, continue
		out << "Disp (m)" << "\t" << "Force (N)" << "\t";
		if (IsBasicTensile){out << "Strain (%)" << "\t" << "Stress (MPa)" << "\t" << "Modulus (MPa)" << "\t";}
	}
	
	out << "\n";

	double LastStress; //so we can calculate modulus at each point...
	double LastStrain;

	for (int i=0; i<NumStep; i++){
		ProgressMessage = "Performing tensile test...";
		for (int j=0; j<VoxCount; j++) VoxArray[j].ScaleExternalInputs((i+1)*StepPercAmt);
		//wiat to settle between timesteps...
		int LastBroken = -1;
		ClearHistories(); //needed so it doesn't immediately "converge" on the next time step

		while (NumBroken() != LastBroken){ //if one breaks, repeat the settling undtil we're done breaking...
			LastBroken = NumBroken();
			EnableFailure(false);
	
//			SetSlowDampZ(CurDamp);

			count = 0;
//			bool LastUnder = false; //were we under the threshhold last time?
//			while (!LastUnder || CurMaxDisp > ConvThresh){
			while (!StopConditionMet()){
	//			if (CurMaxDisp < ConvThresh) LastUnder = true;

				for (int i=0; i<MinimumPerStep; i++){
					if (CancelFlag) break;

					if (!TimeStep(&IntMsg)){ //always do at least 5 steps...
						ProgressMessage = "Tensile test failed. \n \n" + IntMsg;
						CancelFlag = true; //get outta here!
					}
//					CurMaxDisp = SS.NormObjDisp;
				}
				if (CancelFlag) break;
				
				count+=MinimumPerStep;
				if (count > 20000){
					QString Num = QString::number(MaxMoveHistory[0]*1000);
					ProgressMessage = "Simulation not converging at " + Num.toStdString() + ". \n Retry with larger threshold.";
				}
			}
			if (CancelFlag) break;

			EnableFailure(true); //do one step to apply breaking and re-settle as needed...
			if (!TimeStep(&IntMsg)){
				ProgressMessage = "Tensile test failed. \n \n" + IntMsg;
				CancelFlag = true; //get outta here!
			}
		}

		for (int j=0; j<NumBCs; j++){
			CVX_FRegion* pThisBC = pEnv->GetBC(j);
			if (pThisBC->Displace.Length2() != 0 ){ //if non-zero displacement
				double CurDisp = pThisBC->Displace.Length()*(i+1.0)/((double)NumStep);
				double tmp2 = -GetSumForceDir(pThisBC);
				out << CurDisp << "\t" << tmp2 << "\t";
				if (IsBasicTensile){ //only two materials, only one with displacement, so we should only ever enter here once!!
					double ThisStress = tmp2/CSArea;
					double ThisStrain = CurDisp/IniLength;
					out << ThisStrain*100 << "\t" << ThisStress/1e6 << "\t";
					if (i!=0) out << (ThisStress-LastStress)/(ThisStrain-LastStrain)/1e6 << "\t";
					else out << "" << "\t";
					LastStress = ThisStress;
					LastStrain = ThisStrain;
				}
			}
		}
		
		out << "\n";

//		for (int k=0; k<VoxArray.size(); k++){
//			VoxArray[k].ExternalDisp *= (i+2.0)/(i+1.0);
//		}

		CurTick = i+1;
	}
	int stop = 1;

	
	File.close();
	ProgressMessage = ""; //flag to not display message boc on return...
	TestRunning = false;
	emit StopExternalGLUpdate();

}
예제 #10
0
파일: HTTPSock.cpp 프로젝트: NeilHanlon/znc
bool CHTTPSock::PrintFile(const CString& sFileName, CString sContentType) {
	CString sFilePath = sFileName;

	if (!m_sDocRoot.empty()) {
		sFilePath.TrimLeft("/");

		sFilePath = CDir::CheckPathPrefix(m_sDocRoot, sFilePath, m_sDocRoot);

		if (sFilePath.empty()) {
			PrintErrorPage(403, "Forbidden", "You don't have permission to access that file on this server.");
			DEBUG("THIS FILE:     [" << sFilePath << "] does not live in ...");
			DEBUG("DOCUMENT ROOT: [" << m_sDocRoot << "]");
			return false;
		}
	}

	CFile File(sFilePath);

	if (!File.Open()) {
		PrintNotFound();
		return false;
	}

	if (sContentType.empty()) {
		if (sFileName.Right(5).Equals(".html") || sFileName.Right(4).Equals(".htm")) {
			sContentType = "text/html; charset=utf-8";
		} else if (sFileName.Right(4).Equals(".css")) {
			sContentType = "text/css; charset=utf-8";
		} else if (sFileName.Right(3).Equals(".js")) {
			sContentType = "application/x-javascript; charset=utf-8";
		} else if (sFileName.Right(4).Equals(".jpg")) {
			sContentType = "image/jpeg";
		} else if (sFileName.Right(4).Equals(".gif")) {
			sContentType = "image/gif";
		} else if (sFileName.Right(4).Equals(".ico")) {
			sContentType = "image/x-icon";
		} else if (sFileName.Right(4).Equals(".png")) {
			sContentType = "image/png";
		} else if (sFileName.Right(4).Equals(".bmp")) {
			sContentType = "image/bmp";
		} else {
			sContentType = "text/plain; charset=utf-8";
		}
	}

	const time_t iMTime = File.GetMTime();
	bool bNotModified = false;
	CString sETag;

	if (iMTime > 0 && !m_bHTTP10Client) {
		sETag = "-" + CString(iMTime); // lighttpd style ETag

		AddHeader("Last-Modified", GetDate(iMTime));
		AddHeader("ETag", "\"" + sETag + "\"");
		AddHeader("Cache-Control", "public");

		if (!m_sIfNoneMatch.empty()) {
			m_sIfNoneMatch.Trim("\\\"'");
			bNotModified = (m_sIfNoneMatch.Equals(sETag, true));
		}
	}

	if (bNotModified) {
		PrintHeader(0, sContentType, 304, "Not Modified");
	} else {
		off_t iSize = File.GetSize();

		// Don't try to send files over 16 MiB, because it might block
		// the whole process and use huge amounts of memory.
		if (iSize > 16 * 1024 * 1024) {
			DEBUG("- Abort: File is over 16 MiB big: " << iSize);
			PrintErrorPage(500, "Internal Server Error", "File too big");
			return true;
		}

		char szBuf[4096];
		off_t iLen = 0;
		int i = 0;

		PrintHeader(iSize, sContentType);

		// while we haven't reached iSize and read() succeeds...
		while (iLen < iSize && (i = File.Read(szBuf, sizeof(szBuf))) > 0) {
			Write(szBuf, i);
			iLen += i;
		}

		if (i < 0) {
			DEBUG("- Error while reading file: " << strerror(errno));
		}
	}

	DEBUG("- ETag: [" << sETag << "] / If-None-Match [" << m_sIfNoneMatch << "]");

	Close(Csock::CLT_AFTERWRITE);

	return true;
}
예제 #11
0
void main() {
    srand(time(0));
    int* random = randomGen(20, 13000);
    for (int i = 0; i < 20; i++) {
        random[i] = abs(random[i]) % 4;
    }
    Giraffe Giraffe_array[] = { Giraffe("Edik", 18, 234, 200),
                                Giraffe("Masha", 35, 170, 500),
                                Giraffe("Vasya", 18, 234, 201),
                                Giraffe("Kesha", 18, 240, 195) };

    Array_List<Giraffe>* giraffe_array_list = new Array_List<Giraffe>(4);
    for (int i = 0; i < giraffe_array_list->get_capacity(); i++){
        giraffe_array_list->set(i, Giraffe_array[i]);
    }
    for (int i = 0; i < 20; i++) {
        giraffe_array_list->add(Giraffe_array[random[i]]);
    }

    Hash_Table<Giraffe, int> g_table;
    for (int i = 0; i < giraffe_array_list->get_size(); i++) {
        Giraffe* animal = new Giraffe(giraffe_array_list->get(i));

        int* counter = new int(0);

        if (g_table.contains(animal)) {
            try {
                *counter = *(g_table.get_value(animal));
                (*counter)++;
            }
            catch (Key_Doesnt_Exist_Exception e) {
                printf("Bizzare error appeared, we can't help it\n");
                return;
            }
        }
        else {
            *counter = 1;
        }
        Pair<Giraffe, int> p = { animal, counter };
        g_table.put(p);
    }

    for (int i = 0; i < 4; i++) {
        giraffe_array_list->get(i).print();
        printf("%d\n\n", *(g_table.get_value(&(giraffe_array_list->get(i)))));
    }

    Hash_Table<std::string, int> table;
    std::ifstream File("input.txt");
    while (!File.eof()) {
        std::string* word = new std::string();
        int* counter = new int(0);
        File >> *word;
        if (table.contains(word)) {
            try {
                *counter = *(table.get_value(word));
                (*counter)++;
            }
            catch (Key_Doesnt_Exist_Exception e) {
                printf("Bizzare error appeared, we can't help it\n");
                return;
            }
        }
        else {
            *counter = 1;
        }
        Pair<std::string, int> p = { word, counter };
        table.put(p);
    }

    for (int i = 0; i < 16; i++) {
        int max = table.get(i).get_size();
        for (int j = 0; j < max; j++) {
            std::cout << *(table.get(i).get(j).key);
            printf(" %d\t", *(table.get(i).get(j).value));
        }
        printf("\n\n");
    }
}
예제 #12
0
void Notation::image(const Board & b, const Move & m, OutputFormat format, ostream &image) {
   if (format == UCI) {
      return UCIMoveImage(m,image);
   }
   else if (format == WB_OUT) {
      if (TypeOfMove(m) == KCastle) {
          image << "O-O";
      }
      else if (TypeOfMove(m) == QCastle) {
          image << "O-O-O";
      }
      else {
         image << FileImage(StartSquare(m));
         image << RankImage(StartSquare(m));
         image << FileImage(DestSquare(m));
         image << RankImage(DestSquare(m));
         if (TypeOfMove(m) == Promotion) {
            // N.b. ICS requires lower case.
            image << (char)tolower((int)PieceImage(PromoteTo(m)));
         }
      }
      return;
   }
   // format is SAN
   if (IsNull(m)) {
       image << "(null)";
      return;
   }

   PieceType p = PieceMoved(m);
   ASSERT(p != Empty);
   if (TypeOfMove(m) == KCastle) {
       image << "O-O";
   }
   else if (TypeOfMove(m) == QCastle) {
       image << "O-O-O";
   }
   else {
      if (p == Pawn) {
         if (Capture(m) == Empty) {
            image << FileImage(DestSquare(m));
            image << RankImage(DestSquare(m));
         }
         else {
            image << FileImage(StartSquare(m));
            image << 'x';
            image << FileImage(DestSquare(m));
            image << RankImage(DestSquare(m));
         }
         if (TypeOfMove(m) == Promotion) {
            image << '=';
            image << PieceImage(PromoteTo(m));
         }
      }
      else {
         image << PieceImage(p);
         Bitboard attacks =
            b.calcAttacks(DestSquare(m), b.sideToMove());
         unsigned n = attacks.bitCount();
         int dups = 0;
         int filedups = 0;
         int rankdups = 0;
         int files[9];
         int ranks[9];

         if (n > 1) {
            Square sq;
            while (attacks.iterate(sq)) {
               if (TypeOfPiece(b[sq]) == p) {
                  files[dups] = File(sq);
                  if (files[dups] == File(StartSquare(m)))
                     filedups++;
                  ranks[dups] = Rank(sq,White);
                  if (ranks[dups] == Rank(StartSquare(m),White))
                     rankdups++;
                  ++dups;
               }
            }
         }
         if (dups > 1) {
            // need to disambiguate move.
            if (filedups == 1) {
               image << FileImage(StartSquare(m));
            }
            else if (rankdups == 1) {
               image << RankImage(StartSquare(m));
            }
            else {
               // need both rank and file to disambiguate
               image << FileImage(StartSquare(m));
               image << RankImage(StartSquare(m));
            }
         }
         if (Capture(m) != Empty) {
            image << 'x';
         }
         image << FileImage(DestSquare(m));
         image << RankImage(DestSquare(m));
      }
   }
   Board board_copy(b);
   board_copy.doMove(m);
   if (board_copy.checkStatus() == InCheck) {
      Move moves[Constants::MaxMoves];
      MoveGenerator mg(board_copy);
      if (mg.generateEvasions(moves))
         image << '+';
      else
         image << '#';                        // mate
   }
}
예제 #13
0
Move Notation::value(const Board & board, ColorType side, InputFormat format, const string &image) 
{
    int rank = 0;
    int file = 0;

    PieceType piece = Empty;
    PieceType promotion = Empty;
    Square dest = InvalidSquare, start = InvalidSquare;
    int capture = 0;

    stringstream s(image);
    string::const_iterator it = image.begin();
    int i = 0;
    while (it != image.end() && isspace(*it)) {
        it++;
        i++;
    }
    if (it == image.end() || !isalpha(*it)) return NullMove;
    string img(image,i); // string w/o leading spaces
    ASSERT(img.length());
    it = img.begin();
    if (*it == 'O' || *it == '0') {
       // castling, we presume
       return parseCastling(board, side, img);
    } else if (format == WB_IN) {
       if (img.length() < 4) return NullMove;
       Square start = SquareValue(img.substr(0,2));
       if (!OnBoard(start)) return NullMove;
       Square dest = SquareValue(img.substr(2,2));
       if (!OnBoard(dest)) return NullMove;
       PieceType promotion = Empty;
       if (img.length() > 4) {
          promotion = PieceCharValue(toupper(img[4]));
       }
       return CreateMove(board,start,dest,promotion);
    }
    int have_start = 0;
    if (isupper(*it)) {
       piece = PieceCharValue(*it);
       it++;
    }
    else {
       piece = Pawn;
       if ((it+1) != img.end()) {
          char next = *it;
          file = next-'a'+1;
          if (file < 1 || file > 8) return NullMove;
          char next2 = *(it+1);
          if (next2 == 'x' || is_file(next2)) {
             // allow "dc4" as in Informant, instead of dxc4
             it++;
             capture = 1;
          }
          else if (isdigit(next2) && img.length()>2) {
             char next3 = *(it+2);
             if ((next3 == 'x' || next3 == '-') && img.length()>=5) {
                // long algebraic notation
                have_start++;
                start = SquareValue(next,next2);
                if (start == InvalidSquare) return NullMove;
                it+=3; // point to dest
                piece = TypeOfPiece(board[start]);
             }
          }
       }
    }
    if (piece == Empty) {
       return NullMove;
    }
    if (piece != Pawn && !have_start && it != img.end()) {
       char next = *it;
       char next2 = '\0';
       if (it + 1 != img.end()) next2 = *(it+1);
       if (is_file(next) && isdigit(next2) && img.length()>=5) {
          // long algebraic notation, or a SAN move like Qd1d3
          start = SquareValue(next,next2);
          if (IsInvalid(start)) return NullMove;
          it+=2;
          have_start++;
       }
       // also look for disambiguating rank, e.g. '2' in "N2e4".
       else if (isdigit(next)) {
          rank = next - '0';
          if (rank < 1 || rank > 8) return NullMove;
          it++;
       }
       else if (is_file(next) && isalpha(next2)) {
          // disamiguating rank, e.g. "Rfd1"
          file = next - 'a' + 1;
          if (file < 1 || file > 8) return NullMove;
          it++;
       }
    }

    if (it != img.end() && *it == 'x') {
       capture = 1;
       it++;
    }
    if (it != img.end() && (it+1) != img.end()) {
       // remainder of move should be a square identifier, e.g. "g7"
       dest = SquareValue(*it,*(it+1));
       it += 2;
    }
    if (IsInvalid(dest)) {
       return NullMove;
    }
    if (it != img.end() && *it == '=') {
       it++;
       if (it == img.end()) {
          return NullMove;
       } else {
          promotion = PieceCharValue(*it);
          if (piece != Pawn || promotion == Empty)
             return NullMove;
          it++;
       }
    }
    else if (piece == Pawn && it != img.end() && isupper(*it)) {
       // Quite a few "PGN" files have a8Q instead of a8=Q.
       promotion = PieceCharValue(*it);
       if (promotion == Empty || Rank(dest,side) != 8)
          return NullMove;
    } else if (piece == Pawn && Rank(dest,side) == 8) {
       // promotion but no piece specified, treat as error
       return NullMove;
    }

    // Informant does not use "x" for captures.  Assume that if the destination
    // is occupied, this is a capture move.
    if (board[dest] != EmptyPiece) {
       capture = 1;
    }
    // Do a sanity check on capture moves:
    if (capture && !IsEmptyPiece(board[dest]) && PieceColor(board[dest]) == board.sideToMove()) {
       return NullMove;
    }

    // Ok, now we need to figure out where the start square is. For pawn
    // moves this is implicit.

    int dups = 0;

    if (!have_start) {
       if (capture && piece == Pawn && IsEmptyPiece(board[dest]) &&
           Rank(dest,board.sideToMove()) != 8) {
          // en passant capture, special case
          int start_rank = (board.sideToMove() == White) ?
             Rank(dest,White) - 1 :
             Rank(dest,White) + 1;

          start = MakeSquare(file, start_rank, White);
          dups = 1;
       }
       else if (piece == Pawn && board[dest] == EmptyPiece) {
          start = MakeSquare(file,Rank(dest,board.sideToMove())-1,board.sideToMove());
          if (board[start] == EmptyPiece && Rank(dest,board.sideToMove())==4) {
             start = MakeSquare(file,Rank(dest,board.sideToMove())-2,board.sideToMove());
          }
          if (board[start] == EmptyPiece) return NullMove;
          dups = 1;
       }
       else {
          Bitboard attacks = board.calcAttacks(dest,side);
          Square maybe;
          while (attacks.iterate(maybe)) {
             if (TypeOfPiece(board[maybe]) == piece &&
                 PieceColor(board[maybe]) == board.sideToMove()) {
                if (file && File(maybe) != file)
                   continue;
                if (rank && Rank(maybe,White) != rank)
                   continue;
                if (PieceColor(board[maybe]) == board.sideToMove()) {
                   // Possible move to this square.  Make sure it is legal.
                   Board board_copy(board);
                   Move emove = CreateMove(board,maybe,dest,
                                           promotion);
                   board_copy.doMove(emove);
                   if (!board_copy.anyAttacks(
                          board_copy.kingSquare(board_copy.oppositeSide()),
                          board_copy.sideToMove())) {
                      ++dups;
                      start = maybe;
                   }
                }
             }
          }
       }
    }
    if (dups == 1 || have_start) {
       if (start == InvalidSquare || board[start] == EmptyPiece)
          return NullMove;
       else
          return CreateMove(board, start, dest, promotion);
    }
    else                                           // ambiguous move
       return NullMove;
}
예제 #14
0
const File CtrlrLuaMethod::getSourceFile()
{
	return (File (methodTree.getProperty (Ids::luaMethodSourcePath)));
}
예제 #15
0
   //----------------------------------------------------------------------------------------------
   void TLoadDialogWizard::accept(void)
   {
   QString FilePrefix = m_LoadDialogWizardPathPage->m_JobsPrefix->currentText();
   QString Directory  = m_LoadDialogWizardPathPage->m_SavePath->currentText();

   // делим область на участки в соответствии с количеством задач
   QList<QPair<QPointF, QPointF> > Areas;
   if(m_LoadDialogWizardParametersPage->m_CountJobs->value() == 1) 
      Areas.append(qMakePair(m_PointF1, m_PointF2));
   else {
      // делим на вертикальные полосы
      qreal Y1 = m_PointF1.y();
      qreal Y2 = m_PointF2.y();
      qreal X  = m_PointF1.x();
      qreal DeltaX = 
         (m_PointF2.x() - m_PointF1.x()) / m_LoadDialogWizardParametersPage->m_CountJobs->value();
      for(int i = 1; i < m_LoadDialogWizardParametersPage->m_CountJobs->value(); i++) {
         Areas.append(qMakePair(QPointF(X, Y1), QPointF(X + DeltaX, Y2)));
         X += DeltaX;
         }
      Areas.append(qMakePair(QPointF(X, Y1), QPointF(m_PointF2.x(), Y2)));
      }
   // проходим по списку с формированием отдельных файлов заданий
   int i = 0;
   QPair<QPointF, QPointF> PointsPair;
   foreach(PointsPair, Areas) {
      QString FileNameTemplate = Directory + "/" + FilePrefix + "%1.xml";
      QFile File(FileNameTemplate.arg(i++));
      if(!File.exists()) {
         File.open(QIODevice::WriteOnly | QIODevice::Text);
         QTextStream out(&File);
         // начало документа
         out << QString("<?xml version=\"1.0\"?>\n<%1 %2=\"%3\">\n")
                   .arg(SPIDER_TAG_JOBDOCUMENT)
                   .arg(SPIDER_PARAMETER_REQUESTSCOUNT)
                   .arg(m_LoadDialogWizardParametersPage->m_SimultaneousRequestsCount->value());
         // проходим по картам
         for(QMap<QString, TMapDetails>::const_iterator it = m_LoadDialogWizardMapsPage->m_Maps.begin();
             it != m_LoadDialogWizardMapsPage->m_Maps.end(); ++it) {
            if(it.value().g_CheckBox->isChecked()) {
               IMapAdapterInterface* MapInterface = it.value().g_MapInterface;
               int FromZoom = it.value().g_FromZoom->value();
               int ToZoom   = it.value().g_ToZoom->value();
               // начинаем карту
               out << QString("\t<%1 %2=\"%3\">\n")
                         .arg(SPIDER_TAG_MAP)
                         .arg(SPIDER_PARAMETER_PLUGINNAME)
                         .arg(MapInterface->pluginName());
               // проходим по областям с масштабами
               for(int i = FromZoom; i <= ToZoom; i++) {
                  if(i >= MapInterface->minZoom() && i <= MapInterface->maxZoom()) {
                     // начинаем область
                     out << QString("\t\t<%1 %2=\"%3\">\n")
                               .arg(SPIDER_TAG_AREA)
                               .arg(SPIDER_PARAMETER_ZOOM)
                               .arg(i);
                     // пишем точки углов выделенной области
                     out << QString("\t\t\t<%1 %2=\"%3\" %4=\"%5\"/>\n")
                               .arg(SPIDER_TAG_POINT)
                               .arg(SPIDER_PARAMETER_LONGITUDE)
                               .arg(PointsPair.first.x())
                               .arg(SPIDER_PARAMETER_LATITUDE)
                               .arg(PointsPair.first.y());
                     out << QString("\t\t\t<%1 %2=\"%3\" %4=\"%5\"/>\n")
                               .arg(SPIDER_TAG_POINT)
                               .arg(SPIDER_PARAMETER_LONGITUDE)
                               .arg(PointsPair.second.x())
                               .arg(SPIDER_PARAMETER_LATITUDE)
                               .arg(PointsPair.second.y());
                     // завершаем область
                     out << QString("\t\t</%1>\n").arg(SPIDER_TAG_AREA);
                     }
                  }
               // завершаем карту
               out << QString("\t</%1>\n").arg(SPIDER_TAG_MAP);
               }
            }
         // завершаем документ
         out << QString("</%1>\n").arg(SPIDER_TAG_JOBDOCUMENT);
         File.close();
         reject();
         }
      else {
         QMessageBox::critical(0, QNetMapTranslator::tr("Error"), 
            // Russian: Файл '%1' уже существует.
            QNetMapTranslator::tr("File '%1' already exists.").arg(File.fileName()));
         }
      }
예제 #16
0
void ErrorReport::AddFile(const fs::path& fileName)
{
	// Do not include files that can't be found, and empty files...
	if(fs::exists(fileName) && fs::file_size(fileName) != 0)
		m_AttachedFiles.push_back(File(fileName, true));
}
예제 #17
0
bool BinaryResources::reload (const int index)
{
    return resources[index] != 0
            && add (resources [index]->name,
                    File (resources [index]->originalFilename));
}
예제 #18
0
파일: juce_File.cpp 프로젝트: EQ4/editor
File File::getParentDirectory() const
{
    return File (getPathUpToLastSlash(), (int) 0);
}
예제 #19
0
// Deserialize
//------------------------------------------------------------------------------
void ToolManifest::Deserialize( IOStream & ms )
{
	ms.Read( m_ToolId );

	ASSERT( m_Files.IsEmpty() );

	uint32_t numFiles( 0 );
	ms.Read( numFiles );
	m_Files.SetCapacity( numFiles );

	for ( size_t i=0; i<(size_t)numFiles; ++i )
	{		
		AStackString<> name;
		uint64_t timeStamp( 0 );
		uint32_t hash( 0 );
		uint32_t contentSize( 0 );
		ms.Read( name );
		ms.Read( timeStamp );
		ms.Read( hash );
		ms.Read( contentSize );
		m_Files.Append( File( name, timeStamp, hash, nullptr, contentSize ) );
	}

	// determine if any files are remaining from a previous run
	size_t numFilesAlreadySynchronized = 0;
	for ( size_t i=0; i<(size_t)numFiles; ++i )
	{
		AStackString<> localFile;
		GetRemoteFilePath( (uint32_t)i, localFile );

		// is this file already present?
		AutoPtr< FileStream > fileStream( FNEW( FileStream ) );
		FileStream & f = *( fileStream.Get() );
		if ( f.Open( localFile.Get() ) == false )
		{
			continue; // file not found
		}
		if ( f.GetFileSize() != m_Files[ i ].m_ContentSize )
		{
			continue; // file is not complete
		}
		AutoPtr< char > mem( (char *)ALLOC( (size_t)f.GetFileSize() ) );
		if ( f.Read( mem.Get(), (size_t)f.GetFileSize() ) != f.GetFileSize() )
		{
			continue; // problem reading file
		}
		if( Murmur3::Calc32( mem.Get(), (size_t)f.GetFileSize() ) != m_Files[ i ].m_Hash )
		{
			continue; // file contents unexpected
		}

		// file present and ok
		m_Files[ i ].m_FileLock = fileStream.Release(); // NOTE: keep file open to prevent deletions
		m_Files[ i ].m_SyncState = File::SYNCHRONIZED;
		numFilesAlreadySynchronized++;
	}

	// Generate Environment
	ASSERT( m_RemoteEnvironmentString == nullptr );

	// PATH=
	AStackString<> basePath;
	GetRemotePath( basePath );
	AStackString<> paths;
	paths.Format( "PATH=%s", basePath.Get() );

	// TMP=
	AStackString<> normalTmp;
	Env::GetEnvVariable( "TMP", normalTmp );
	AStackString<> tmp;
	tmp.Format( "TMP=%s", normalTmp.Get() );

	// SystemRoot=
	AStackString<> sysRoot( "SystemRoot=C:\\Windows" );

	char * mem = (char *)ALLOC( paths.GetLength() + 1 +
								  tmp.GetLength() + 1 +
								  sysRoot.GetLength() + 1 +
								  1 );
	m_RemoteEnvironmentString = mem;

	AString::Copy( paths.Get(), mem, paths.GetLength() + 1 ); // including null
	mem += ( paths.GetLength() + 1 ); // including null

	AString::Copy( tmp.Get(), mem, tmp.GetLength() + 1 ); // including null
	mem += ( tmp.GetLength() + 1 ); // including null

	AString::Copy( sysRoot.Get(), mem, sysRoot.GetLength() + 1 ); // including null
	mem += ( sysRoot.GetLength() + 1 ); // including null

	*mem = 0; ++mem; // double null

	// are all files already present?
	if ( numFilesAlreadySynchronized == m_Files.GetSize() )
	{
		m_Synchronized = true;		
	}
}
예제 #20
0
파일: juce_File.cpp 프로젝트: EQ4/editor
File File::createFileWithoutCheckingPath (const String& path)
{
    return File (path, 0);
}
예제 #21
0
    void run()
    {
        Vector screenSize(80, 48);
        int frames = 13125000 * 14 / (11 * 76 * 262);
        int maxRadius = 20;

        // Center of screen
        Vector2<double> c = Vector2Cast<double>(screenSize) / 2;

        // Positions of screen top-left relative to centre of each picture
        Array<Vector> p1s(frames);
        Array<Vector> p2s(frames);
        int minX = 0, maxX = 0;
        for (int t = 0; t < frames; ++t) {
            double f = static_cast<double>(t) / frames;
            double r = maxRadius; // *(1 - cos(f * tau)) / 2;
            Rotor2<double> z1(f * 6);
            Rotor2<double> z2(f * 7);
            Vector2<double> a1(r*cos(f*tau * 6), r*sin(f*tau * 7));
            Vector2<double> a2(r*cos(f*tau * 5), r*sin(f*tau * 4));

            // Positions of picture centres relative to screen top-left
            Vector p1 = -Vector2Cast<int>(c + a1);
            Vector p2 = -Vector2Cast<int>(c + a2);
            p1s[t] = p1;
            p2s[t] = p2;

            minX = min(min(minX, p1.x), p2.x);
            maxX = max(max(maxX, p1.x + screenSize.x), p2.x + screenSize.x);
        }
        int stride = (3 + maxX - minX) & ~3;

        // Offset in picture from start of screen to end
        int ss = (screenSize.y - 1)*stride + screenSize.x;

        Array<int> o1s(frames);
        Array<int> o2s(frames);
        int minO = 0, maxO = 0;
        for (int t = 0; t < frames; ++t) {
            Vector p1 = p1s[t];
            Vector p2 = p2s[t];

            // Offsets of screen top-left into pictures relative to pictures
            // center.
            int o1 = p1.y*stride + p1.x;
            int o2 = p2.y*stride + p2.x;

            int o1e = o1 + ss;
            int o2e = o2 + ss;

            // Picture bounds
            minO = min(min(minO, o1), o2);
            maxO = max(max(maxO, o1e), o2e);

            o1s[t] = o1;
            o2s[t] = o2;
        }
        minO &= -2;
        maxO = (maxO + 1) & -2;

        FileStream output = File("tables.asm").openWrite();
/*        output.write("cpu 8086\n"
            "segment _DATA public class = DATA\n"
            "\n"
            "global _picture, _motion\n"
            "\n"
            "\n"); */

        int d = ((-minO) / stride + 1)*stride + stride/2;

        int bytes = (maxO + 1 - minO) / 2;

        int xs = (minO + d) % stride;
        int ys = (minO - xs) / stride;
        console.write("First position: (" + decimal(xs) + ", " + decimal(ys) +
            ")\n");
        xs = (maxO + d) % stride;
        ys = (maxO - xs) / stride;
        console.write("Last position: (" + decimal(xs) + ", " + decimal(ys) +
            ")\n");
        console.write("Picture size: " + decimal(bytes) + "\n");
        console.write("Motion size: " + decimal(4 * frames) + "\n");

        output.write("frames equ " + decimal(frames) + "\n");
        output.write("stride equ " + decimal(stride/2) + "\n");
        output.write("p equ picture\n");
        output.write(
            "p2 equ pictureEnd+(pictureEnd-picture)+(headerEnd-header)\n\n");

        output.write("motion:");
        for (int t = 0; t < frames; ++t) {
            int o1 = o1s[t] - minO;
            int o2 = o2s[t] - minO;

            int sp = o1 / 2;
            if ((o1 & 1) != 0)
                sp += bytes;
            int bp = o2 / 2;
            if ((o2 & 1) != 0)
                bp += bytes;

            if (t % 3 == 0)
                output.write("\n  dw ");
            else
                output.write(", ");
            output.write("p+" + hex(sp, 4) + ", p+" + hex(bp, 4));
        }

        int lastX = 20;
        output.write("\n\n");

        int p2 = (maxO + 1 - minO) / 2;
        p2 += p2 - 1;

        output.write("transition:");
        Array<bool> cleared(20 * 13);
        for (int p = 0; p < 20 * 13; ++p)
            cleared[p] = false;
        int pp = 0;
        for (int t = 0; t < 1000000; ++t) {
            int r = 999 - t / 1000;
            int theta = t % 1000;
            Vector2<double> z =
                Vector2<double>(r/20.0, 0)*Rotor2<double>(theta / 1000.0);
            Vector p = Vector2Cast<int>(z + Vector2<double>(10, 6));
            if (p.x >= 0 && p.x < 20 && p.y >= 0 && p.y < 12) {
                int aa = p.y * 20 + p.x;
                if (cleared[aa])
                    continue;
                int a = p.y * 206 * 4 + p.x * 10;
                if (pp % 3 == 0)
                    output.write("\n  dw ");
                else
                    output.write(", ");
                ++pp;
                output.write("p2+" + hex(a, 4) + ", ");
                if (p.y == 12)
                    output.write("p2+" + hex(a, 4));
                else
                    output.write("p2+" + hex(a + 206*2, 4));
                cleared[aa] = true;
            }
        }
        console.write("pp = " + decimal(pp) + " \n");
        output.write("\n\npicture:");
        for (int o = minO; o < maxO + 1; o += 2) {
            int x = (o + d) % stride;
            int y = (o + d - x) / stride - d/stride;

            if (lastX == 20) {
                output.write("\n  db ");
                lastX = 0;
            }
            else
                output.write(", ");
            for (; lastX < x % 20; lastX += 2)
                output.write("      ");

            Vector p(x - stride / 2, y);
            int cL = colour(p);
            int cR = colour(p + Vector(1, 0));
            int b = cL | (cR << 4);
            output.write(String(hex(b, 2)));
            lastX += 2;
        }
        output.write("\n");
        output.write("pictureEnd:\n");
    }
예제 #22
0
    //==============================================================================
    void initialise (const String& commandLine) override
    {
        // This method is where you should put your application's initialisation code..

		String romName;
		String descriptorName;
		String midiNumberStr;
		String output;

		LPWSTR *szArglist;
		int nArgs;

		szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);

		for (int x = 0; x < nArgs; x++)
		{
			String commandLineStr = String(szArglist[x]);
			commandLineStr = commandLineStr.trim();
			
			if (commandLineStr.startsWith("-rom="))
			{
				romName = commandLineStr.substring(commandLineStr.indexOf("-rom=")+5);
				romName = romName.trim();
			}

			else if (commandLineStr.contains("-descriptor="))
			{
				descriptorName = commandLineStr.substring(commandLineStr.indexOf("-descriptor=")+12);
				descriptorName = descriptorName.trim();
			}
			else if (commandLineStr.contains("-midi="))
			{
				midiNumberStr = commandLineStr.substring(commandLineStr.indexOf("-midi=")+6);
				midiNumberStr = midiNumberStr.trim();
			}
			else if (commandLineStr.contains("-output="))
			{
				output = commandLineStr.substring(commandLineStr.indexOf("-output=")+8);
				output = output.trim();
			}
		}

		int midiNumber = midiNumberStr.getIntValue();

        mainWindow = new MainWindow();

		mainWindow->mainComponent->romfile = File(romName);
		mainWindow->mainComponent->romdescfile = File(descriptorName);

		mainWindow->setName("seq64");

		mainWindow->mainComponent->menuItemSelected(1, 0);
		mainWindow->mainComponent->menuItemSelected(11, 0);

		for (int x = 0; x < mainWindow->mainComponent->filespane->kfilelistnode.getNumChildren(); x++)
		{
			ValueTree selkfile = mainWindow->mainComponent->filespane->kfilelistnode.getChild(x);
			String type = selkfile.getProperty("type", "Unsupported");
			if (type == "Audioseq Index")
			{
				mainWindow->mainComponent->filespane->lstKFiles->selectRow(x);
				mainWindow->mainComponent->filespane->rowSelected(mainWindow->mainComponent->filespane->lsmKFiles, x);
				break;
			}
		}

		//mainWindow->mainComponent->filespane->lstIndex->selectRow(0);
		
		mainWindow->mainComponent->filespane->rowSelected(mainWindow->mainComponent->filespane->lsmIndex, midiNumber);
		
		mainWindow->mainComponent->filespane->buttonClicked(mainWindow->mainComponent->filespane->btnLoadEntry);

		mainWindow->mainComponent->midipane->dest = output;
		mainWindow->mainComponent->midipane->buttonClicked(mainWindow->mainComponent->midipane->btnMIDIExport);

		JUCEApplication::getInstance()->systemRequestedQuit();
    }
예제 #23
0
File File::getSpecialLocation (const SpecialLocationType type)
{
    switch (type)
    {
    case userHomeDirectory:
    {
        const char* homeDir = getenv ("HOME");

        if (homeDir == nullptr)
        {
            struct passwd* const pw = getpwuid (getuid());
            if (pw != nullptr)
                homeDir = pw->pw_dir;
        }

        return File (CharPointer_UTF8 (homeDir));
    }

    case userDocumentsDirectory:
    case userMusicDirectory:
    case userMoviesDirectory:
    case userApplicationDataDirectory:
        return File ("~");

    case userDesktopDirectory:
        return File ("~/Desktop");

    case commonApplicationDataDirectory:
        return File ("/var");

    case globalApplicationsDirectory:
        return File ("/usr");

    case tempDirectory:
    {
        File tmp ("/var/tmp");

        if (! tmp.isDirectory())
        {
            tmp = "/tmp";

            if (! tmp.isDirectory())
                tmp = File::getCurrentWorkingDirectory();
        }

        return tmp;
    }

    case invokedExecutableFile:
        if (juce_Argv0 != nullptr)
            return File (CharPointer_UTF8 (juce_Argv0));
        // deliberate fall-through...

    case currentExecutableFile:
    case currentApplicationFile:
        return juce_getExecutableFile();

    case hostApplicationPath:
        return juce_readlink ("/proc/self/exe", juce_getExecutableFile());

    default:
        jassertfalse; // unknown type?
        break;
    }

    return File::nonexistent;
}
예제 #24
0
// ------------------------------------------------------------------------
void ImportDialog::slotImport()
{
  MsgText->clear();
  if (OutputEdit->text().isEmpty())
    return;

  ImportButt->setDisabled(true);
  AbortButt->setDisabled(false);

  QFile File(QucsWorkDir.filePath(OutputEdit->text()));
  if(File.exists())
    if(QMessageBox::information(this, tr("Info"),
          tr("Output file already exists!")+"\n"+tr("Overwrite it?"),
          tr("&Yes"), tr("&No"), 0,1,1))
      {
	ImportButt->setDisabled(false);
	AbortButt->setDisabled(true);
	return;
      }

  QFileInfo Info(ImportEdit->text());
  QString Suffix = Info.extension();
  QString Program;
  QStringList CommandLine;
  Program = QucsSettings.BinDir + "qucsconv";
  CommandLine  << "-if";
  
  if((Suffix == "citi") || (Suffix == "cit"))
    CommandLine << "citi";
  else if(Suffix == "vcd")
    CommandLine << "vcd";
  else if(Suffix == "asc")
    CommandLine << "zvr";
  else if(Suffix == "mdl")
    CommandLine << "mdl";
  else if(Suffix == "csv")
    CommandLine << "csv";
  else if(Suffix == "dat")
    CommandLine << "qucsdata";
  else if(Suffix == "cir")
    CommandLine << "spice";
  else for(;;) {
    if(Suffix.at(0) == 's')
      if(Suffix.at(2) == 'p')
        if(Suffix.length() == 3)
          if(Suffix.at(1).isDigit()) {
            CommandLine << "touchstone";
            break;
          }

    MsgText->append(tr("ERROR: Unknown file format! Please check file name extension!"));
    return;
  }

  CommandLine << "-of";
  switch(OutType->currentItem()) {
  case 0:
    CommandLine << "qucsdata";
    break;
  case 1:
    CommandLine << "touchstone";
    if (!OutputData->text().isEmpty())
      CommandLine << "-d" << OutputData->text();
    break;
  case 2:
    CommandLine << "csv";
    if (!OutputData->text().isEmpty())
      CommandLine << "-d" << OutputData->text();
    break;
  case 3:
    CommandLine << "qucslib";
    break;
  case 4:
    CommandLine << "qucs";
    break;
  case 5:
    CommandLine << "matlab";
    break;
  default:
    CommandLine << "qucsdata";
    break;
  }

  CommandLine << "-i" << ImportEdit->text()
              << "-o" << QucsWorkDir.filePath(OutputEdit->text());

  Process.blockSignals(false);

  disconnect(&Process, 0, 0, 0);
  connect(&Process, SIGNAL(readyReadStandardError()), SLOT(slotDisplayErr()));
  connect(&Process, SIGNAL(readyReadStandardOutput()), SLOT(slotDisplayMsg()));
  connect(&Process, SIGNAL(finished(int)), SLOT(slotProcessEnded(int)));

  MsgText->append(tr("Running command line:")+"\n");
  MsgText->append(Program + CommandLine.join(" "));
  MsgText->append("\n");

  Process.start(Program, CommandLine);
  
  if(!Process.Running)
    MsgText->append(tr("ERROR: Cannot start converter!"));
}
예제 #25
0
파일: optionsS.cpp 프로젝트: fduhia/Easy68k
void __fastcall TOptions::SaveSettings()
//saves editor settings to file, true  & false  settings are saved as 1 and 0
{
   maximizedEdit = false;
  //grab active mdi child
  TTextStuff *Active = (TTextStuff*)Main->ActiveMDIChild;
  if (Active) {
    if (Active->WindowState == wsMaximized)
      maximizedEdit = true;
  }

  try {
    AnsiString str;
    str = ExtractFilePath(Application->ExeName) + "settings.dat";
    char fileName[256];
    strcpy(fileName, str.c_str());        // fileName is path + settings.dat
    ofstream File(fileName);              //open settings file
    if (EditorOptionsForm->AssemblyTabs->Checked)
      tabType = Assembly;
    else
      tabType = Fixed;

    //save all assembler and editor flags
    File << "$Settings for " << TITLE << "  DO NOT EDIT THIS FILE!!!!\n"
         << listFlag                                    << "$generate list\n"
         << objFlag                                     << "$generate s-record\n"
         << bSave                                       << "$save then assemble\n"
         << chkShowWarnings->Checked                    << "$show warnings\n"
         << chkCrossRef->Checked                        << "$cross reference\n"
         << chkMacEx->Checked                           << "$macros expanded\n"
         << chkStrucEx->Checked                         << "$structured expand\n"
         << chkConstantsEx->Checked                     << "$constants expand\n"
         << EditorOptionsForm->cbFont->Text.c_str()     << "$font name\n"
         << EditorOptionsForm->cbSize->Text.c_str()     << "$font size\n"
         << tabType                                     << "$tab type\n"
         << EditorOptionsForm->FixedTabSize->Value      << "$fixed tab size\n"
         << maximizedEdit                               << "$maximized edit\n"
         << autoIndent                                  << "$auto indent\n"
         << realTabs                                    << "$real tabs\n"
         << chkBitfield->Checked                        << "$assemble bit field\n"
         << Main->Top                                   << "$main top\n"
         << Main->Left                                  << "$main left\n"
         << Main->Height                                << "$main height\n"
         << Main->Width                                 << "$main width\n"
         << codeStyle.color                             << "$code color\n"
         << codeStyle.bold                              << "$code bold\n"
         << codeStyle.italic                            << "$code italic\n"
         << codeStyle.underline                         << "$code underline\n"
         << unknownStyle.color                          << "$unknown color\n"
         << unknownStyle.bold                           << "$unknown bold\n"
         << unknownStyle.italic                         << "$unknown italic\n"
         << unknownStyle.underline                      << "$unknown underline\n"
         << directiveStyle.color                        << "$directive color\n"
         << directiveStyle.bold                         << "$directive bold\n"
         << directiveStyle.italic                       << "$directive italic\n"
         << directiveStyle.underline                    << "$directive underline\n"
         << commentStyle.color                          << "$comment color\n"
         << commentStyle.bold                           << "$comment bold\n"
         << commentStyle.italic                         << "$comment italic\n"
         << commentStyle.underline                      << "$comment underline\n"
         << labelStyle.color                            << "$label color\n"
         << labelStyle.bold                             << "$label bold\n"
         << labelStyle.italic                           << "$label italic\n"
         << labelStyle.underline                        << "$label underline\n"
         << structureStyle.color                        << "$structure color\n"
         << structureStyle.bold                         << "$structure bold\n"
         << structureStyle.italic                       << "$structure italic\n"
         << structureStyle.underline                    << "$structure underline\n"
         << errorStyle.color                            << "$error color\n"
         << errorStyle.bold                             << "$error bold\n"
         << errorStyle.italic                           << "$error italic\n"
         << errorStyle.underline                        << "$error underline\n"
         << textStyle.color                             << "$text color\n"
         << textStyle.bold                              << "$text bold\n"
         << textStyle.italic                            << "$text italic\n"
         << textStyle.underline                         << "$text underline\n"
         << highlightDisabled                           << "$highlight disabled\n"
         << EditorOptionsForm->PrintBlack->Checked      << "$print w/black\n"
         << backColor                                   << "$background color\n";

    File.close();
  }
  catch( ... ) {
    MessageDlg("Error saving editor settings",mtInformation, TMsgDlgButtons() << mbOK,0);
    return;
  }
}
예제 #26
0
파일: main.cpp 프로젝트: adobekan/qminer
	TQmParam(const TStr& FNm) {
		EAssertR(TFile::Exists(FNm), "Missing configuration file " + FNm);
		// load configuration file
		PJsonVal ConfigVal = TJsonVal::GetValFromSIn(TFIn::New(FNm));
		EAssertR(ConfigVal->IsObj(), "Invalid setting file - not valid JSON");
		// parse out common stuff
		RootFPath = TStr::GetNrFPath(ConfigVal->GetObjStr("directory", TDir::GetCurDir()));
		LockFNm = RootFPath + "./lock";
		DbFPath = ConfigVal->GetObjStr("database", "./db/");
		PortN = TFlt::Round(ConfigVal->GetObjNum("port"));
		// parse out unicode definition file
		TStr UnicodeFNm = ConfigVal->GetObjStr("unicode", TQm::TEnv::QMinerFPath + "./UnicodeDef.Bin");
		if (!TUnicodeDef::IsDef()) { TUnicodeDef::Load(UnicodeFNm); }

		// parse cache
		if (ConfigVal->IsObjKey("cache")) { 
			PJsonVal CacheVal = ConfigVal->GetObjKey("cache");
			// parse out index and default store cache sizes
			IndexCacheSize = int64(CacheVal->GetObjNum("index", 1024)) * int64(TInt::Mega);
			DefStoreCacheSize = int64(CacheVal->GetObjNum("store", 1024)) * int64(TInt::Mega);
			// prase out store specific sizes, when available
			if (CacheVal->IsObjKey("stores")) {
				PJsonVal StoreCacheVals = CacheVal->GetObjKey("stores");
				for (int StoreN = 0; StoreN < StoreCacheVals->GetArrVals(); StoreN++) {
					PJsonVal StoreCacheVal = StoreCacheVals->GetArrVal(StoreN);					
					TStr StoreName = StoreCacheVal->GetObjStr("name");
					uint64 StoreCacheSize = int64(StoreCacheVal->GetObjNum("size")) * int64(TInt::Mega);
					StoreNmCacheSizeH.AddDat(StoreName, StoreCacheSize);
				}
			}
		} else {
			// default sizes are set to 1GB for index and stores			
			IndexCacheSize = int64(1024) * int64(TInt::Mega);
			DefStoreCacheSize = int64(1024) * int64(TInt::Mega);
		}

		// load scripts
		if (ConfigVal->IsObjKey("script")) {
			// we have configuration file, read it
			PJsonVal JsVals = ConfigVal->GetObjKey("script");
			if (JsVals->IsArr()) {
				for (int JsValN = 0; JsValN < JsVals->GetArrVals(); JsValN++) {
					JsParamV.Add(TJsParam(RootFPath, JsVals->GetArrVal(JsValN)));
				}
			} else {
				JsParamV.Add(TJsParam(RootFPath, JsVals));
			}
		} else {
			// no settings for scripts, assume default setting
			TStr SrcFPath = TStr::GetNrAbsFPath("src", RootFPath);
			TFFile File(SrcFPath, ".js", false); TStr SrcFNm;
			while (File.Next(SrcFNm)) {
				JsParamV.Add(TJsParam(RootFPath, SrcFNm));
			}
		}

		// load serving folders
		//TODO: Add to qm config ability to edit this
		if (ConfigVal->IsObjKey("wwwroot")) {
			PJsonVal WwwVals = ConfigVal->GetObjKey("wwwroot");
			if (WwwVals->IsArr()) {
				for (int WwwValN = 0; WwwValN < WwwVals->GetArrVals(); WwwValN++) {
					AddWwwRoot(WwwVals->GetArrVal(WwwValN));
				}
			} else {
				AddWwwRoot(WwwVals);
			}			
		}
		// check for folder with admin GUI
		TStr GuiFPath = TStr::GetNrAbsFPath("gui", TQm::TEnv::QMinerFPath);
		if (TDir::Exists(GuiFPath)) {
			WwwRootV.Add(TStrPr("admin", GuiFPath));
		}
        // check for any default wwwroot
        TStr DefaultWwwRootFPath = TStr::GetNrAbsFPath("www", RootFPath);
        if (TDir::Exists(DefaultWwwRootFPath)) {
            WwwRootV.Add(TStrPr("www", DefaultWwwRootFPath));
        }
	}
예제 #27
0
파일: File.cpp 프로젝트: Felard/MoSync
static void callback ( const char *f )
{
	g_fileList->push_back( File( g_currentPath+f ) );
}
예제 #28
0
                        void LoggerUtil::configure(const char* xmlFilePath) {
#ifdef HAVE_LOG4CXX
                            PropertyConfigurator::configure(File(xmlFilePath));
#endif
                        }
예제 #29
0
void DoMuscle(CompositeVect*CVLocation)
	{
	SetOutputFileName(g_pstrOutFileName);
	SetInputFileName(g_pstrInFileName);

	SetMaxIters(g_uMaxIters);
	SetSeqWeightMethod(g_SeqWeight1);

	TextFile fileIn(g_pstrInFileName);
	SeqVect v;
	v.FromFASTAFile(fileIn);
	const unsigned uSeqCount = v.Length();

	if (0 == uSeqCount)
		Quit("No sequences in input file");

	ALPHA Alpha = ALPHA_Undefined;
	switch (g_SeqType)
		{
	case SEQTYPE_Auto:
		Alpha = v.GuessAlpha();
		break;

	case SEQTYPE_Protein:
		Alpha = ALPHA_Amino;
		break;

	case SEQTYPE_DNA:
		Alpha = ALPHA_DNA;
		break;

	case SEQTYPE_RNA:
		Alpha = ALPHA_RNA;
		break;

	default:
		Quit("Invalid seq type");
		}
	SetAlpha(Alpha);
	v.FixAlpha();

	PTR_SCOREMATRIX UserMatrix = 0;
	if (0 != g_pstrMatrixFileName)
		{
		const char *FileName = g_pstrMatrixFileName;
		const char *Path = getenv("MUSCLE_MXPATH");
		if (Path != 0)
			{
			size_t n = strlen(Path) + 1 + strlen(FileName) + 1;
			char *NewFileName = new char[n];
			sprintf(NewFileName, "%s/%s", Path, FileName);
			FileName = NewFileName;
			}
		TextFile File(FileName);
		UserMatrix = ReadMx(File);
		g_Alpha = ALPHA_Amino;
		g_PPScore = PPSCORE_SP;
		}

	SetPPScore();

	if (0 != UserMatrix)
		g_ptrScoreMatrix = UserMatrix;

	unsigned uMaxL = 0;
	unsigned uTotL = 0;
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		{
		unsigned L = v.GetSeq(uSeqIndex).Length();
		uTotL += L;
		if (L > uMaxL)
			uMaxL = L;
		}

	SetIter(1);
	g_bDiags = g_bDiags1;
	SetSeqStats(uSeqCount, uMaxL, uTotL/uSeqCount);

	SetMuscleSeqVect(v);

	MSA::SetIdCount(uSeqCount);

// Initialize sequence ids.
// From this point on, ids must somehow propogate from here.
	for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex)
		v.SetSeqId(uSeqIndex, uSeqIndex);

	if (0 == uSeqCount)
		Quit("Input file '%s' has no sequences", g_pstrInFileName);
	if (1 == uSeqCount)
		{
		TextFile fileOut(g_pstrOutFileName, true);
		v.ToFile(fileOut);
		return;
		}

	if (uSeqCount > 1)
		MHackStart(v);

// First iteration
	Tree GuideTree;
	if (0 != g_pstrUseTreeFileName)
	{
	// Discourage users...
		if (!g_bUseTreeNoWarn)
			fprintf(stderr, "%s", g_strUseTreeWarning);

	// Read tree from file
		TextFile TreeFile(g_pstrUseTreeFileName);
		GuideTree.FromFile(TreeFile);

	// Make sure tree is rooted
		if (!GuideTree.IsRooted())
			Quit("User tree must be rooted");

		if (GuideTree.GetLeafCount() != uSeqCount)
			Quit("User tree does not match input sequences");

		const unsigned uNodeCount = GuideTree.GetNodeCount();
		for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
			{
			if (!GuideTree.IsLeaf(uNodeIndex))
				continue;
			const char *LeafName = GuideTree.GetLeafName(uNodeIndex);
			unsigned uSeqIndex;
			bool SeqFound = v.FindName(LeafName, &uSeqIndex);
			if (!SeqFound)
				Quit("Label %s in tree does not match sequences", LeafName);
			unsigned uId = v.GetSeqIdFromName(LeafName);
			GuideTree.SetLeafId(uNodeIndex, uId);
			}
		}
	else
		TreeFromSeqVect(v, GuideTree, g_Cluster1, g_Distance1, g_Root1,
		  g_pstrDistMxFileName1);

	const char *Tree1 = ValueOpt("Tree1");
	if (0 != Tree1)
		{
		TextFile f(Tree1, true);
		GuideTree.ToFile(f);
		if (g_bClusterOnly)
			return;
		}

	SetMuscleTree(GuideTree);
	ValidateMuscleIds(GuideTree);

	MSA msa;
	msa.SetCompositeVector(CVLocation);
	ProgNode *ProgNodes = 0;
	if (g_bLow)
		ProgNodes = ProgressiveAlignE(v, GuideTree, msa);
	else
		ProgressiveAlign(v, GuideTree, msa);
	SetCurrentAlignment(msa);

	if (0 != g_pstrComputeWeightsFileName)
		{
		extern void OutWeights(const char *FileName, const MSA &msa);
		SetMSAWeightsMuscle(msa);
		OutWeights(g_pstrComputeWeightsFileName, msa);
		return;
		}

	ValidateMuscleIds(msa);

	if (1 == g_uMaxIters || 2 == uSeqCount)
		{
		//TextFile fileOut(g_pstrOutFileName, true);
		//MHackEnd(msa);
		//msa.ToFile(fileOut);
		MuscleOutput(msa);
		return;
		}

	if (0 == g_pstrUseTreeFileName)
		{
		g_bDiags = g_bDiags2;
		SetIter(2);

		if (g_bLow)
			{
			if (0 != g_uMaxTreeRefineIters)
				RefineTreeE(msa, v, GuideTree, ProgNodes);
			}
		else
			RefineTree(msa, GuideTree);

		const char *Tree2 = ValueOpt("Tree2");
		if (0 != Tree2)
			{
			TextFile f(Tree2, true);
			GuideTree.ToFile(f);
			}
		}

	SetSeqWeightMethod(g_SeqWeight2);
	SetMuscleTree(GuideTree);

	if (g_bAnchors)
		RefineVert(msa, GuideTree, g_uMaxIters - 2);
	else
		RefineHoriz(msa, GuideTree, g_uMaxIters - 2, false, false);

#if	0
// Refining by subfamilies is disabled as it didn't give better
// results. I tried doing this before and after RefineHoriz.
// Should get back to this as it seems like this should work.
	RefineSubfams(msa, GuideTree, g_uMaxIters - 2);
#endif

	ValidateMuscleIds(msa);
	ValidateMuscleIds(GuideTree);

	//TextFile fileOut(g_pstrOutFileName, true);
	//MHackEnd(msa);
	//msa.ToFile(fileOut);
	MuscleOutput(msa);
	}
예제 #30
0
void Statistics::createFile() {
	fstream File("files/statistics.dat", ios::in | ios::binary);
}