void QuantitySpinBox::selectNumber()
{
    QString str = lineEdit()->text();
    unsigned int i = 0;

    QChar d = locale().decimalPoint();
    QChar g = locale().groupSeparator();
    QChar n = locale().negativeSign();

    for (QString::iterator it = str.begin(); it != str.end(); ++it) {
        if (it->isDigit())
            i++;
        else if (*it == d)
            i++;
        else if (*it == g)
            i++;
        else if (*it == n)
            i++;
        else // any non-number character
            break;
    }

    lineEdit()->setSelection(0, i);
}
bool ICompletionCollector::lessThan(const QString &l, const QString &r)
{
    return std::lexicographical_compare(l.begin(), l.end(),
                                        r.begin(), r.end(),
                                        compareChar);
}
Example #3
0
void MainWindow::on_m_proccessing_triggered()
{
    if (show_results)
        table_show_task();
    delete_task_data();

    if (!ui->m_add_rus->isChecked())
    {
        for (size_t i=0; i<founded_words.size(); i++)
            if (ui->tableWidget->item(founded_words[i].first,founded_words[i].second))
                ui->tableWidget->item(founded_words[i].first,founded_words[i].second)->setText("");
        founded_words.clear();
    }

    words_count = 0;
    int broken =0;
    m_k = new mini_task*[ui->tableWidget->rowCount()];

    for (int row_c =0; row_c<ui->tableWidget->rowCount(); row_c++)
    {
        if (!ui->tableWidget->item(row_c,0) || ui->tableWidget->item(row_c,0)->text()=="")
        {
            broken++;
            continue;
        }
        mini_task* new_task = new mini_task;
        words_count++;
        new_task->main_word = ui->tableWidget->item(row_c,0)->text().toLower();
        new_task->met=0;
        new_task->low_met=0;
        bool first = true;
        new_task->head=NULL;
        for (int col_c = 3; ui->tableWidget->item(row_c,col_c); col_c++)
        {
            if (ui->tableWidget->item(row_c,col_c)->text()=="")
                continue;
            low_task* new_low_task = new low_task;
            new_low_task->word = ui->tableWidget->item(row_c,col_c)->text().toLower();
            new_low_task->met = 0;
            if (std::find(founded_words.begin(),founded_words.end(),std::make_pair(row_c,col_c))!=founded_words.end())
                new_low_task->founded=true;
            if (first)
            {
                first=false;
                new_low_task->next = NULL;
                new_task->head = new_low_task;
            }
            else
            {
                low_task* iter = new_task->head;
                new_low_task->next=NULL;
                while (iter->next!=NULL)
                    iter = iter->next;
                iter->next = new_low_task;
            }
        }
        m_k[row_c-broken] = new_task;
    }
    if (words_count==0)
        return;

    count_mas = new int[ui->tableWidget->rowCount()];
    count_mas2 = new int[ui->tableWidget->rowCount()];

    for (int i=0; i<ui->tableWidget->rowCount(); i++)
    {
        if (ui->tableWidget->item(i,1))
            count_mas[i]=ui->tableWidget->item(i,1)->text().toInt();
        else
            count_mas[i]=0;
        if (ui->tableWidget->item(i,2))
            count_mas2[i]=ui->tableWidget->item(i,2)->text().toInt();
        else
            count_mas2[i]=0;
    }

    off_cch = true;
    progress->setValue(0);
    bool found=false;
    int rus_f;
    QString wrong_char = "?!., ;:\'\"\\/+><@#~`$%^&*(){}|\n\r\t\a\?";
    QString word = "";

    if (!ui->m_stress->isChecked())
    {
        const QString widget_text = ui->textEdit->toPlainText().toLower();
        QString::const_iterator iter = widget_text.begin();
        progress->setMaximum(widget_text.length());
        while (iter!=widget_text.end())
        {
            progress->setValue(progress->value()+1);
            if (wrong_char.contains((*(iter))))
            {
                if (word!="")
                {
                    found=false;
                    for (unsigned int row_c =0; row_c < words_count; row_c++)
                        if ((m_k[row_c])->main_word==word)
                        {
                            (m_k[row_c])->met++;
                            found=true;
                            break;
                        }
                        else
                        {
                            low_task* iter_l=(m_k[row_c])->head;
                            while (iter_l!=NULL)
                            {
                                if (iter_l->word==word)
                                {
                                    (m_k[row_c])->low_met++;
                                    iter_l->met++;
                                    found=true;
                                    break;
                                }
                                iter_l=iter_l->next;
                            }
                        }
                }
                if (ui->m_add_rus->isChecked()==true && !found && word!="" && (rus_f=russian_test(word))!=-1)
                {
                    low_task* iter = (m_k[rus_f])->head;
                    low_task* new_low_task = new low_task;
                    low_task* help_fiter = iter;
                    int su=1;
                    while (iter!=NULL)
                    {
                        su++;
                        if (!iter->next)
                        {
                            help_fiter = iter;
                            break;
                        }
                        iter=iter->next;
                    }
                    if (help_fiter == NULL)
                    {
                        (m_k[rus_f])->head = new_low_task;
                    }
                    else
                        help_fiter->next = new_low_task;
                    new_low_task->word = word;
                    new_low_task->met=1;
                    new_low_task->next = NULL;
                    new_low_task->founded=true;
                    founded_words.push_back(std::make_pair(rus_f,su+2));
                    (m_k[rus_f])->low_met++;
                    if (ui->tableWidget->columnCount()<su+3)
                    {
                        ui->tableWidget->setColumnCount(su+3);
                        char buf_int[15];
                        sprintf(buf_int, "%d", ui->tableWidget->columnCount()-3);
                        ui->tableWidget->setHorizontalHeaderItem(ui->tableWidget->columnCount()-1,new QTableWidgetItem(tr("Словоформа ") + buf_int));
                    }
                    ui->tableWidget->setItem(rus_f,su+2,new QTableWidgetItem(word));
                }
                word="";
            }
            else
                word+=(*(iter));
            iter++;
        }
        found = false;
        if (word!="")
        {
            for (unsigned int row_c =0; row_c < words_count; row_c++)
                if ((m_k[row_c])->main_word==word)
                {
                    (m_k[row_c])->met++;
                    found = true;
                    break;
                }
                else
                {
                    low_task* iter_l=(m_k[row_c])->head;
                    while (iter_l!=NULL)
                    {
                        if (iter_l->word==word)
                        {
                            (m_k[row_c])->low_met++;
                            iter_l->met++;
                            found = true;
                            break;
                        }
                        iter_l=iter_l->next;
                    }
                }
            if (ui->m_add_rus->isChecked()==true && !found && (rus_f=russian_test(word))!=-1)
            {
                low_task* iter = (m_k[rus_f])->head;
                low_task* new_low_task = new low_task;
                low_task* help_fiter = iter;
                int su=1;
                while (iter!=NULL)
                {
                    su++;
                    if (!iter->next)
                    {
                        help_fiter = iter;
                        break;
                    }
                    iter=iter->next;
                }
                if (help_fiter == NULL)
                {
                    (m_k[rus_f])->head = new_low_task;
                }
                else
                    help_fiter->next = new_low_task;
                new_low_task->word = word;
                new_low_task->met=1;
                new_low_task->next = NULL;
                new_low_task->founded=true;
                (m_k[rus_f])->low_met++;
                if (ui->tableWidget->columnCount()<su+3)
                {
                    ui->tableWidget->setColumnCount(su+3);
                    char buf_int[15];
                    sprintf(buf_int, "%d", ui->tableWidget->columnCount()-3);
                    ui->tableWidget->setHorizontalHeaderItem(ui->tableWidget->columnCount()-1,new QTableWidgetItem(tr("Словоформа ") + buf_int));
                }
                ui->tableWidget->setItem(rus_f,su+2,new QTableWidgetItem(word));
            }
        }
    }
    else
    {
        QTextCursor cur(ui->textEdit->document());
        QChar end_of_buf;
        fake_text = ui->textEdit->toHtml();
        progress->setMaximum(ui->textEdit->toPlainText().length());
        off_ct = true;
        QTextCharFormat format;
        QFont font_format;
        QString nature_word;
        while (cur.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor))
        {
            progress->setValue(progress->value()+1);
            word = cur.selectedText();
            end_of_buf = word[word.length()-1];
            if (wrong_char.contains(end_of_buf) || end_of_buf.unicode()==8233)
            {
                word.remove(word.length()-1,1);
                nature_word = word;
                word = word.toLower();
                found = false;
                for (unsigned int row_c =0; row_c < words_count; row_c++)
                    if ((m_k[row_c])->main_word==word)
                    {
                        cur.removeSelectedText();
                        format.setForeground(QBrush(QColor("red")));
                        font_format.setBold(true);
                        font_format.setUnderline(true);
                        format.setFont(font_format);
                        cur.insertText(nature_word,format);
                        cur.insertText(end_of_buf);
                        (m_k[row_c])->met++;
                        found = true;
                        break;
                    }
                    else
                    {
                        low_task* iter_l=(m_k[row_c])->head;
                        while (iter_l!=NULL)
                        {
                            if (iter_l->word==word)
                            {
                                cur.removeSelectedText();
                                format.setForeground(QBrush(QColor("blue")));
                                font_format.setBold(true);
                                font_format.setUnderline(false);
                                format.setFont(font_format);
                                cur.insertText(nature_word,format);
                                cur.insertText(end_of_buf);
                                found = true;
                                (m_k[row_c])->low_met++;
                                iter_l->met++;
                                break;
                            }
                            iter_l=iter_l->next;
                        }
                    }
                if (ui->m_add_rus->isChecked()==true && !found && word!="" && (rus_f=russian_test(word))!=-1)
                {
                    low_task* iter = (m_k[rus_f])->head;
                    low_task* new_low_task = new low_task;
                    low_task* help_fiter = iter;
                    int su=1;
                    while (iter!=NULL)
                    {
                        su++;
                        if (!iter->next)
                        {
                            help_fiter = iter;
                            break;
                        }
                        iter=iter->next;
                    }
                    if (help_fiter == NULL)
                    {
                        (m_k[rus_f])->head = new_low_task;
                    }
                    else
                        help_fiter->next = new_low_task;
                    new_low_task->word = word;
                    new_low_task->met=1;
                    new_low_task->next = NULL;
                    new_low_task->founded=true;
                    founded_words.push_back(std::make_pair(rus_f,su+2));
                    (m_k[rus_f])->low_met++;
                    if (ui->tableWidget->columnCount()<su+3)
                    {
                        ui->tableWidget->setColumnCount(su+3);
                        char buf_int[15];
                        sprintf(buf_int, "%d", ui->tableWidget->columnCount()-3);
                        ui->tableWidget->setHorizontalHeaderItem(ui->tableWidget->columnCount()-1,new QTableWidgetItem(tr("Словоформа ") + buf_int));
                    }
                    ui->tableWidget->setItem(rus_f,su+2,new QTableWidgetItem(word));
                }
                cur.clearSelection();
            }
        }
        word = cur.selectedText().toLower();
        found = false;
        for (unsigned int row_c =0; row_c < words_count; row_c++)
            if ((m_k[row_c])->main_word==word.toLower())
            {
                cur.removeSelectedText();
                cur.insertHtml("<b><u><font color='red'>" + word + "</font></b></u>" + end_of_buf);
                (m_k[row_c])->met++;
                found = true;
                break;
            }
            else
            {
                low_task* iter_l=(m_k[row_c])->head;
                while (iter_l!=NULL)
                {
                    if (iter_l->word==word.toLower())
                    {
                        cur.removeSelectedText();
                        cur.insertHtml("<b><font color='blue'>" + word + "</font></b>" + end_of_buf);
                        found = true;
                        (m_k[row_c])->low_met++;
                        iter_l->met++;
                        break;
                    }
                    iter_l=iter_l->next;
                }
            }
        if (ui->m_add_rus->isChecked()==true && !found && word!="" && (rus_f=russian_test(word))!=-1)
        {
            low_task* iter = (m_k[rus_f])->head;
            low_task* new_low_task = new low_task;
            low_task* help_fiter = iter;
            int su=1;
            while (iter!=NULL)
            {
                su++;
                if (!iter->next)
                {
                    help_fiter = iter;
                    break;
                }
                iter=iter->next;
            }
            if (help_fiter == NULL)
            {
                (m_k[rus_f])->head = new_low_task;
            }
            else
                help_fiter->next = new_low_task;
            new_low_task->word = word;
            new_low_task->met=1;
            new_low_task->next = NULL;
            new_low_task->founded=true;
            founded_words.push_back(std::make_pair(rus_f,su+2));
            (m_k[rus_f])->low_met++;
            if (ui->tableWidget->columnCount()<su+3)
            {
                ui->tableWidget->setColumnCount(su+3);
                char buf_int[15];
                sprintf(buf_int, "%d", ui->tableWidget->columnCount()-3);
                ui->tableWidget->setHorizontalHeaderItem(ui->tableWidget->columnCount()-1,new QTableWidgetItem(tr("Словоформа ") + buf_int));
            }
            ui->tableWidget->setItem(rus_f,su+2,new QTableWidgetItem(word));
        }
        tpl = ui->textEdit->toPlainText().length();
        refresh_ur(false);
        oper_stack.insert(oper_stack.begin(),1,
                  oper_info(1,1,1,
                  fake_text,ui->textEdit->toHtml()  ));
        fake_text = ui->textEdit->toHtml();
    }
    off_ct = false;
    table_show_results();
    off_cch = false;
    ui->m_show_results->setEnabled(true);
    ui->m_show_task->setEnabled(true);
    setWindowTitle(pr_name+'*');
    is_pr_saved = false;
    ui->m_Save_pr_as->setEnabled(true);
    is_job_done = true;
    ui->m_proccessing->setChecked(true);
}
Example #4
0
void MainWindow::btnExportClicked()
{
    QList<QChar> charset;

    if (chkLowerAZ->isChecked())
        for (char c = 'a'; c <= 'z'; c++)
            charset.append(c);

    if (chkUpperAZ->isChecked())
        for (char c = 'A'; c <= 'Z'; c++)
            charset.append(c);

    if (chkNumbers->isChecked())
        for (char c = '0'; c <= '9'; c++)
            charset.append(c);

    QString str = ldtCharacters->text();
    for (QString::const_iterator itr(str.begin()); itr != str.end(); itr++)
        if (!charset.contains(*itr))
            charset.append(*itr);

    qSort(charset);

    // Render characters
    QFont font = fontSelector->currentFont();
    font.setPixelSize(font.pointSize());

    QFontMetrics metrics = QFontMetrics(font);
    QTextCodec *codec = QTextCodec::codecForName("utf-8");

    QString glyphs;

    QString fontName = QString("font_%1%2")
            .arg(font.family().toLower())
            .arg(font.pixelSize())
            .replace(' ', '_');

    QString fontstruct = QString(
            "const struct glib_font %1 = {\n"
            "    .charcount = %2,\n"
            "    .size = %3,\n"
            "    .glyphs    = {\n        ")
            .arg(fontName)
            .arg(charset.size())
            .arg(font.pixelSize());

    QListIterator<QChar> itr(charset);
    while (itr.hasNext()) {
        QChar c = itr.next();

        if (c == ' ') {
            // Add space character
            fontstruct += QString("{.utf8 = 0x20, .x = %1, .y = 0, .bitmap = NULL}")
                    .arg(metrics.width(' '));

        } else {
            QRect boundingRect = metrics.boundingRect(c);

            QImage image = QImage(boundingRect.width(), boundingRect.height(),
                    QImage::Format_Mono);

            image.fill(Qt::color1);

            QPainter p;
            p.begin(&image);
            p.setFont(font);
            p.setWindow(metrics.boundingRect(c));
            p.drawText(0, 0, c);
            p.end();

            QString utf8 = codec->fromUnicode(c).toHex();

            glyphs += renderGlyph(utf8, image);
            fontstruct += QString("{.utf8 = 0x%1, .x = %2, .y = %3, .bitmap = &glyph_%1}")
                    .arg(utf8)
                    .arg(boundingRect.x() + 1)
                    .arg(boundingRect.y() - metrics.descent() + 1); // +1 for the base line
        }

        if (itr.hasNext())
            fontstruct += ",\n        ";
    }

    fontstruct += "\n    }\n};\n";

    glyphs = "#include <liblcd/glib.h>\n\n" + glyphs + "\n" + fontstruct;


    QString filename = QFileDialog::getSaveFileName(this,
            tr("Save Font"), fontName + ".c", tr("Source Files (*.c *.cpp)"));

    if (!filename.isEmpty()) {
        if (!(filename.endsWith(".c") || filename.endsWith(".cpp")))
            filename += ".c";

        QFile file(filename);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
            return;

        QTextStream out(&file);
        out << glyphs;
        file.close();
    }
}
Example #5
0
bool CSVParser::parse(QTextStream& stream, qint64 nMaxRecords)
{
    m_vCSVData.clear();
    m_nColumns = 0;
    ParseStates state = StateNormal;
    QString fieldbuf;
    QStringList record;

    if(m_pCSVProgress)
        m_pCSVProgress->start();

    while(!stream.atEnd())
    {
        QString sBuffer = stream.read(m_nBufferSize);

        for(QString::iterator it = sBuffer.begin(); it != sBuffer.end(); ++it)
        {
            QChar c = *it;
            switch(state)
            {
            case StateNormal:
            {
                if(c == m_cFieldSeparator)
                {
                    addColumn(record, fieldbuf, m_bTrimFields);
                }
                else if(c == m_cQuoteChar)
                {
                    state = StateInQuote;
                }
                else if(c == '\r')
                {
                    // look ahead to check for linefeed
                    QString::iterator nit = it + 1;

                    // In order to check what the next byte is we must make sure that that byte is already loaded. Assume we're at an m_nBufferSize
                    // boundary but not at the end of the file when we hit a \r character. Now we're going to be at the end of the sBuffer string
                    // because of the m_nBufferSize boundary. But this means that the following check won't work properly because we can't check the
                    // next byte when we really should be able to do so because there's more data coming. To fix this we'll check for this particular
                    // case and, if this is what's happening, we'll just load an extra byte.
                    if(nit == sBuffer.end() && !stream.atEnd())
                    {
                        // Load one more byte
                        sBuffer.append(stream.read(1));

                        // Restore both iterators. sBuffer.end() points to the imagined char after the last one in the string. So the extra byte we've
                        // just loaded is the one before that, i.e. the actual last one, and the original last char is the one before that.
                        it = sBuffer.end() - 2;
                        nit = sBuffer.end() - 1;
                    }

                    // no linefeed, so assume that CR represents a newline
                    if(nit != sBuffer.end() && *nit != '\n')
                    {
                        addColumn(record, fieldbuf, m_bTrimFields);

                        addRow(record);
                    }
                }
                else if(c == '\n')
                {
                    addColumn(record, fieldbuf, m_bTrimFields);

                    addRow(record);
                }
                else
                {
                    fieldbuf.append(c);
                }
            }
            break;
            case StateInQuote:
            {
                if(c == m_cQuoteChar)
                {
                    state = StateEndQuote;
                }
                else
                {
                    fieldbuf.append(c);
                }
            }
            break;
            case StateEndQuote:
            {
                if(c == m_cQuoteChar)
                {
                    state = StateInQuote;
                    fieldbuf.append(c);
                }
                else if(c == m_cFieldSeparator)
                {
                    state = StateNormal;
                    addColumn(record, fieldbuf, m_bTrimFields);
                }
                else if(c == '\n')
                {
                    state = StateNormal;
                    addColumn(record, fieldbuf, m_bTrimFields);

                    addRow(record);
                }
                else if(c == '\r')
                {
                    // look ahead to check for linefeed
                    QString::iterator nit = it + 1;

                    // See above for details on this.
                    if(nit == sBuffer.end() && !stream.atEnd())
                    {
                        sBuffer.append(stream.read(1));
                        it = sBuffer.end() - 2;
                        nit = sBuffer.end() - 1;
                    }

                    // no linefeed, so assume that CR represents a newline
                    if(nit != sBuffer.end() && *nit != '\n')
                    {
                        addColumn(record, fieldbuf, m_bTrimFields);

                        addRow(record);
                    }
                }
                else
                {
                    state = StateNormal;
                    fieldbuf.append(c);
                }
            }
            break;
            }

            if(nMaxRecords != -1 && m_vCSVData.size() >= nMaxRecords)
                return true;
        }

        if(m_pCSVProgress && m_vCSVData.size() % 100 == 0)
        {
            if(!m_pCSVProgress->update(stream.pos()))
                return false;
        }
    }

    if(!record.isEmpty())
    {
        addColumn(record, fieldbuf, m_bTrimFields);

        addRow(record);
    }

    if(m_pCSVProgress)
        m_pCSVProgress->end();

    return state == StateNormal;
}
Litterale* Expression::evaluer() const{
    QString s = value;
    //On vire les '
    s=s.remove(0,1);
    s=s.remove(s.length()-1,s.length());
    QString::iterator it = s.begin();
    //QString contenant le résultat
    QString postfix;

    //Stack d'opérations
    QStack<QString> stack;

    //Map des opérateurs
    const QMap<QString, Operateur*> op_map = OperateurFactory::getMap();

    //Map de tous les symboles
    const QMap<QString,WordIdentifier*>& interpretation_map = Controleur::getInterpretationMap();

    //Traduction de Infix vers Postfix

    QString tmp;
    bool found;

    while(it!=s.end()){
        found=false;

        if(*it==' ' || *it==','){
            it++;
            continue;
        }

        //Verification que ce n'est pas une litterale avec 2 symboles exemple : Expression ou Programme
        if(tmp == "" && interpretation_map.find(*it)!=interpretation_map.end()){
            WordIdentifier *identifier = interpretation_map.find(*it).value();
            WordIdentifier *try1;
            WordIdentifier *try2;

            try1=dynamic_cast<RecursiveEncapsulatorIdentifier*>(identifier);
            try2=dynamic_cast<EncapsulatorIdentifier*>(identifier);
            if(try1 || try2)
            {
                    throw LitteraleException("Litterale "+ QString(*it) +" non permise","Inconnu");
            }
        }

        //On tombe dans le cas ou on a une valeur
        while(it!=s.end() && ((*it<='9' && *it>='0') || (interpretation_map.find(*it)!=interpretation_map.end()))){
              tmp+=*it;
              if(it!=s.end())
                  it++;
        }
        //Pour vider ce qu'on a trouvé
        if(tmp!=""){
            postfix+=tmp+" ";
            tmp.clear();
            found=true;

        }

        //On tombe dans le cas d'un morçeau de texte
        if((*it<='Z' && *it>='A')){
            while(it!=s.end() && ((*it<='Z' && *it>='A') || (*it<='9' && *it>='0'))){
                tmp+=* it;
                if(it!=s.end())
                    it++;
            }
            if(isOperator(tmp)){
                found=true;
                while(!stack.empty() && stack.top() != "(" && CompareOperators(stack.top(),tmp)<=0){
                    postfix += stack.top()+" ";
                    stack.pop();
                }
            stack.push(tmp);
            tmp.clear();
            }
            else if(isVariable(tmp)){
                found=true;
                Litterale* l = VariablesManager::getVariable(tmp);
                if(estdeType<Programme>(l))
                    throw OperateurException("Un programme est dans l'expression !");

                QString rep = l->toString();
                int length_it = s.indexOf(tmp);
                s.replace(tmp,rep);
                it = s.begin();
                for(int i=0; i<length_it;i++,it++);
                tmp.clear();

            }
            else
                throw(LitteraleException("Le mot "+tmp+" est inconnu","Inconnu"));

        }

        if(*it=='('){
            stack.push(*it);
            if(it!=s.end())
                it++;
            found=true;
        }
        if(*it==')'){
            while(stack.top()!="("){
                postfix+= stack.top()+" ";
                stack.pop();
            }
            stack.pop();
            if(it!=s.end())
            it++;
            found=true;
        }
        //On tombe dans le cas d'un opérateur à caractère
        if(!found){
            while(it!=s.end() && !op_map.contains(tmp)){
                tmp+=*it++;
            }
            if(it==s.end() && !op_map.contains(tmp))
                throw LitteraleException("Expression non valide dès "+tmp,"Expression");
            while(!stack.empty() && stack.top() != "(" && CompareOperators(stack.top(),tmp)<=0){
                postfix += stack.top()+" ";
                stack.pop();
            }
        stack.push(tmp);
        tmp.clear();
        }
    }

    while(!stack.empty()){
        postfix+= stack.top() + " ";
        stack.pop();
    }

    MainWindow::getInstanceMainWindow()->getNextCommande(postfix,"INFIX");
    return nullptr;
}
Example #7
0
void Global::generatePDFs(QString dirname)
{
  size_t pageCount = 0;

  for (size_t s = 0; s < getNumStudents(); s++)
  {
    Student& student = db()->getStudent(s);
    // Use the student name to form the file name for the repot
    QString clean = student.getStudentName();
    // Convert all non alpha/num chars into an underscore
    for (QString::iterator i = clean.begin(); i != clean.end(); i++)
    {
      if (!i->isLetterOrNumber())
        *i = '_';
    }
    if (clean.length() == 0)
    {
      GINFODIALOG(QString("Cannot render PDF because student %1 does not have a name assigned").arg(s+1));
      return;
    }
    QString pdfname (dirname + "/report-" + clean + ".pdf");
    GDEBUG ("Generating PDF [%s] for student [%s]", qPrintable(pdfname), qPrintable(student.getStudentId()));

    QPrinter printer (QPrinter::HighResolution);
    printer.setOutputFormat (QPrinter::PdfFormat);
    printer.setOutputFileName (pdfname);
    printer.setPageSize(QPrinter::Letter);
    printer.setResolution(150); // DPI for the printing
    printer.setColorMode(QPrinter::GrayScale);

    QPainter painter;
    if (!painter.begin(&printer)) // Check for errors here
      GFATAL("Failed to do QPainter begin()");

    // Can use this code to change the text color, but causes larger PDF files
    // since it must use a color output format instead.
    //QPen penColor(QColor("#000090")); // Change text to dark blue
    //painter.setPen(penColor);

    for (size_t p = 0; p < getNumPagesPerStudent(); p++)
    {
      pageCount++;
      // Add spaces at the end so the widget can resize into the reserved space without a re-layout
      Global::getStatusLabel()->setText(QString("Generating PDF for student %1 of %2, page %3 of %4 (%5 percent)     ").
                                        arg(s+1).arg(getNumStudents()).arg(p+1).arg(getNumPagesPerStudent()).arg(rint(0.5+100.0*pageCount/(1.0*getNumPages()))));
      // Flush out Qt events so that the UI update occurs inside this handler
      Global::getQApplication()->processEvents();

      GDEBUG ("Printing page %zu of %zu for report [%s]", p+1, getNumPagesPerStudent(), qPrintable(pdfname));
      QPixmap pix = getPages()->getQPixmap(p+s*getNumPagesPerStudent());
      // Scale the pixmap to fit the printer
      pix = pix.scaled(printer.pageRect().width(), printer.pageRect().height(), Qt::KeepAspectRatio);
      // Draw the pixmap to the printer
      painter.drawPixmap (0, 0, pix);

      // Print out the student details at the top of the page
      QString title = QString("Name: %1  ID: %2  Page: %3 of %4  Final Grade: %5 of %6").arg(student.getStudentName()).arg(student.getStudentId()).arg(p+1).arg(getNumPagesPerStudent()).arg(student.getTotal()).arg(db()->getTotalMaximum());
      painter.drawText(0, 0, title);

      // Build up a results string to print onto the page
      QString grades ("Results:");
      size_t pageTotal = 0;
      size_t pageMax = 0;
      for (size_t q = 0; q < getNumQuestions(); q++)
      {
        // See if the question is on this page
        GASSERT(Global::db()->getQuestionPage(q) != 0, "Cannot have page 0 assigned for question %zu", q);
        if (Global::db()->getQuestionPage(q) < 0)
        {
          GINFODIALOG(QString("Cannot render PDF because question %1 does not have a page assigned").arg(q+1));
          return;
        }
        if (Global::db()->getQuestionPage(q) == ((int)p+1))
        {
          if (student.getGrade(q) < 0)
          {
            GINFODIALOG(QString("Cannot render PDF for student [%1] because question %2 has no grade assigned").arg(student.getStudentName()).arg(q+1));
            return;
          }
          pageTotal += student.getGrade(q);
          pageMax += Global::db()->getQuestionMaximum(q);
          grades += QString("  Q%1 = %2/%3").arg(q+1).arg(student.getGrade(q)).arg(Global::db()->getQuestionMaximum(q));
          if (student.getFeedback(q) != "")
            grades += QString(" [%1]").arg(student.getFeedback(q));
        }
      }
      grades += QString("  Totals = %1/%2").arg(pageTotal).arg(pageMax);
      if (pageMax == 0)
          grades = QString("No Results For This Page");
      // Wrap the text to fit a bounding box that is the width of the page, align to the bottom of the page
      painter.drawText(0, 30, printer.pageRect().width(), printer.pageRect().height()-30, Qt::TextWordWrap | Qt::AlignBottom, grades);

      // Insert a new page except on the last one
      if (p < getNumPagesPerStudent()-1)
        if (!printer.newPage()) // Check for errors here
          GFATAL("Failed to do newPage() call");
    }

    painter.end();
  }
  Global::getStatusLabel()->setText("");
}
Example #8
0
QVector<ushort> CryptXOR::toVector(QString input) {
    QVector<ushort> result;
    for (QString::iterator i = input.begin(); i != input.end(); ++i)
        result  <<  (*i).cell();
    return result;
}
Example #9
0
QString VisualLog::MessageInfo::expand(const QString &pattern) const{

    QString base = "";
    QDateTime dt = stamp();

    QString::const_iterator it = pattern.begin();
    while ( it != pattern.end() ){
        if ( *it == QChar('%') ){
            ++it;
            if ( it != pattern.end() ){
                char c = it->toLatin1();
                switch(c){
                case 'p': {
                    if ( m_location && !m_location->remote.isEmpty() )
                        base += m_location->remote + "> ";
                    base += QString().sprintf(
                        "%0*d-%0*d-%0*d %0*d:%0*d:%0*d.%0*d %s %s@%d: ",
                        4, dt.date().year(),
                        2, dt.date().month(),
                        2, dt.date().day(),
                        2, dt.time().hour(),
                        2, dt.time().minute(),
                        2, dt.time().second(),
                        3, dt.time().msec(),
                        qPrintable(levelToString(m_level).toLower()),
                        qPrintable(sourceFunctionName()),
                        sourceLineNumber()
                    );
                    break;
                }
                case 'r': base += sourceRemoteLocation(); break;
                case 'F': base += sourceFileName(); break;
                case 'N': base += extractFileNameSegment(sourceFileName()); break;
                case 'U': base += sourceFunctionName(); break;
                case 'L': base += QString::number(sourceLineNumber()); break;
                case 'V': base += levelToString(m_level); break;
                case 'v': base += levelToString(m_level).toLower(); break;
                case 'w': base += QDate::shortDayName(dt.date().dayOfWeek()); break;
                case 'W': base += QDate::longDayName(dt.date().dayOfWeek()); break;
                case 'b': base += QDate::shortMonthName(dt.date().month()); break;
                case 'B': base += QDate::longMonthName(dt.date().month()); break;
                case 'd': base += QString().sprintf("%0*d", 2, dt.date().day() ); break;
                case 'e': base += QString().sprintf("%d",      dt.date().day() ); break;
                case 'f': base += QString().sprintf("%*d",  2, dt.date().day() ); break;
                case 'm': base += QString().sprintf("%0*d", 2, dt.date().month() ); break;
                case 'n': base += QString().sprintf("%d",      dt.date().month() ); break;
                case 'o': base += QString().sprintf("%*d",  2, dt.date().month() ); break;
                case 'y': base += QString().sprintf("%0*d", 2, dt.date().year() % 100 ); break;
                case 'Y': base += QString().sprintf("%0*d", 4, dt.date().year() ); break;
                case 'H': base += QString().sprintf("%0*d", 2, dt.time().hour() ); break;
                case 'I': {
                    int hour = dt.time().hour();
                    base += QString().sprintf("%0*d", 2, (hour < 1 ? 12 : (hour > 12 ? hour - 12  : hour)));
                    break;
                }
                case 'a': base += QString().sprintf(dt.time().hour() < 12  ? "am" : "pm" ); break;
                case 'A': base += QString().sprintf(dt.time().hour() < 12  ? "AM" : "PM" ); break;
                case 'M': base += QString().sprintf("%0*d", 2, dt.time().minute()); break;
                case 'S': base += QString().sprintf("%0*d", 2, dt.time().second() ); break;
                case 's': base += QString().sprintf("%0*d.%0*d", 2, dt.time().second(), 3, dt.time().msec() ); break;
                case 'i': base += QString().sprintf("%0*d", 3, dt.time().msec() ); break;
                case 'c': base += QString().sprintf("%d",      dt.time().msec() / 100 ); break;
                default: base += *it;
                }
            }
        } else {
            base += *it;
        }
        ++it;
    }

    return base;
}
Example #10
0
void SecureErase(QString str)
{
  for (QString::iterator i = str.begin(); i != str.end(); ++i)
    *i = 0;
  str.clear();
}
Example #11
0
void Changecase::sentenceCase()
{
    QTextBlock block = m_document->findBlock(m_startPosition);
    QTextCursor backCursor(m_cursor);
    int pos = block.position() + block.length() - 1;

    // TODO
    // * Exception?
    while (true) {
        QString text = block.text();
        int prevLetterIndex = -1;
        QChar currentWord;
        pos = block.position() + block.length() - 1;

        QString::Iterator iter = text.end();

        if (text.isEmpty()) { // empty block, go to next block
            if (!(block.isValid() && block.position() + block.length() < m_endPosition))
                break;
            block = block.next();
            continue;
        }

        iter--;
        while (iter != text.begin()) {
            while (iter != text.begin() && !iter->isSpace()) {
                iter--;
                pos--;
            }

            prevLetterIndex = pos;
            currentWord = QChar(*(iter + 1));
            while (iter != text.begin() && iter->isSpace()) {
                iter--;
                pos--;
            }

            // found end of sentence, go back to last found letter (indicating start of a word)
            if (iter != text.begin() && (*iter == QChar('.') || *iter == QChar('!') || *iter == QChar('?'))) {
                if (prevLetterIndex >= m_startPosition && prevLetterIndex <= m_endPosition && currentWord.isLower()) {
                    // kDebug() <<"Found end of sentence" << *iter <<" :" << currentWord;
                    m_cursor.setPosition(prevLetterIndex);
                    m_cursor.deleteChar();
                    m_cursor.insertText(currentWord.toUpper());
                    iter--;
                    pos--;
                }
                else if (prevLetterIndex < m_startPosition)
                    break;
            }
        }

        if (iter == text.begin() && --pos >= m_startPosition) { // start of paragraph, must be start of a sentence also
            if (pos + 1 == prevLetterIndex && (*iter).isLower()) {
                m_cursor.setPosition(pos);
                m_cursor.deleteChar();
                m_cursor.insertText((*iter).toUpper());
            }
            else if (!(*iter).isLetter() && currentWord.isLower()) {
                m_cursor.setPosition(prevLetterIndex);
                m_cursor.deleteChar();
                m_cursor.insertText(currentWord.toUpper());
            }
        }

        if (!(block.isValid() && block.position() + block.length() < m_endPosition))
            break;
        block = block.next();
    }
}
Example #12
0
OAF::URef<OAF::IMoniker>
OAF::parseName (const QString& _name)
{
	//
	// Последний моникер цепочки
	//
	OAF::URef<OAF::IMoniker> last;

	//
	// Текущие префикс и суффикс
	//
	QString prefix;
	QString suffix;

	//
	// Где мы находимся
	//
	enum
	{
		IN_PREFIX, // Обрабатывается префикс
		IN_SUFFIX  // Обрабатывается суффикс
	} state = IN_PREFIX;

	//
	// По всем символам имени
	//
	for (QString::const_iterator c = _name.begin (); c != _name.end (); ++c)
	{
		//
		// Если это экранирующий символ, то следующий символ добавляем
		// вне зависимости от его специального значения
		//
		if (*c == '\\')
		{
			if (++c == _name.end ())
				break;

			if (state == IN_PREFIX)
				prefix += *c;
			else
				suffix += *c;
		}

		//
		// Если это разделитель моникеров
		//
		else if (*c == '#')
		{
			//
			// Моникеры без префиксов просто игнорируем
			//
			if ((state == IN_SUFFIX) && !prefix.isEmpty ())
				last = OAF::createMoniker (last, prefix, suffix);

			prefix.clear ();
			suffix.clear ();

			state = IN_PREFIX;
		}

		//
		// Если это моникер '!'
		//
		else if (*c == '!')
		{
			//
			// Моникеры без префиксов просто игнорируем
			//
			if ((state == IN_SUFFIX) && !prefix.isEmpty ())
				last = OAF::createMoniker (last, prefix, suffix);

			prefix = '!';
			suffix.clear ();

			state = IN_SUFFIX;
		}

		//
		// Если это разделитель префикса
		//
		else if (*c == ':')
		{
			//
			// Если мы обрабатываем префикс, то переходим к
			// обработке суффикса
			//
			if (state == IN_PREFIX)
			{
				//
				// Если префикс пуст, то и оставляем его пустым.
				// Моникер с таким префиксом будет проигнорирован.
				// Если префикс не пуст, то ':' считается частью
				// префикса
				//
				if (!prefix.isEmpty ())
					prefix += *c;

				state = IN_SUFFIX;
			}
			//
			// Если мы обрабатываем суффикс, то так и продолжаем.
			// То есть в суффиксе символ ':' не имеет никакого
			// специального значения и может использоваться как
			// есть без экранировки
			//
			else
				suffix += *c;
		}

		//
		// Для всех остальных символов
		//
		else
		{
			if (state == IN_PREFIX)
				prefix += *c;
			else
				suffix += *c;
		}
	}

	//
	// Моникеры без префиксов просто игнорируем
	//
	if ((state == IN_SUFFIX) && !prefix.isEmpty ())
		last = OAF::createMoniker (last, prefix, suffix);

	return last;
}
  //----------------------------------------------------------------------------
  QString substituteVars(const QString& path)
  {
    QString buf;
    bool varStarted = false; // indicates we are processing a var subtitute
    QString var; // the current var key
    for (QString::const_iterator iter = path.begin(); iter != path.end(); ++iter)
    {
      QChar tok = *iter;
      if (tok == '$')
      {
        if (!varStarted)
        {
          varStarted = true; // we found the start of a var
          var.clear();
        }
        else
        {
          // we have found the end of a var
          QVariant prop;
          // get the value of the var from system properties
          if (!var.isEmpty())
          {
            prop = ctkPluginFrameworkProperties::getProperty(var);
          }
          if (prop.isNull() && processEnv.contains(var))
          {
            prop = processEnv.value(var);
          }
          if (!prop.isNull())
          {
            // found a value; use it
            buf.append(prop.toString());
          }
          else
          {
            // could not find a value append the var name w/o delims
            buf.append(var);
          }
          varStarted = false;
          var.clear();
        }
      }
      else
      {
        if (!varStarted)
        {
          buf.append(tok); // the token is not part of a var
        }
        else
        {
          var.append(tok); // the token is part of the var key; save the key to process when we find the end token
        }
      }
    }

    if (!var.isEmpty())
    {
      // found a case of $var at the end of the path with no trailing $; just append it as is.
      buf.append('$').append(var);
    }
    return buf;
  }
Example #14
0
Arguments::Arguments( const QString &a ) 
{
    _arguments.clear();
    QString current_arg;
    bool between_arguments = false;
    bool quoted_argument = false;
    bool escape = false;
    for( QString::const_iterator itChar = a.begin(); itChar != a.end(); ++itChar )
    {
        if ( between_arguments )
        {
            switch ( itChar->toLatin1() )
            {
                case '"':
                    quoted_argument = true;
                    between_arguments = false;
                    current_arg.clear();
                    break;
                case ' ':
                case '\r':
                case '\n':
                case '\t':
                    break;
                default:
                    quoted_argument = false;
                    between_arguments = false;
                    current_arg = *itChar;
                    break;
            }
        }
        else
        {
            if ( escape )
            {
                escape = false;
                current_arg += *itChar;
            }
            else
            {
                switch ( itChar->toLatin1() )
                {
                    case '"':
                        quoted_argument = !quoted_argument;
                        break;
                    case ' ':
                    case '\r':
                    case '\n':
                    case '\t':
                        if ( quoted_argument )
                            current_arg += *itChar;
                        else
                        {
                            _arguments << current_arg;
                            between_arguments = true;
                        }
                        break;
                    case '\\':
                        escape = true ;
                        break;
                    default:
                        current_arg += *itChar;
                        break;
                }

            }
        }
    }
    if ( !between_arguments )
        _arguments << current_arg;
    calcArguments();
}
Example #15
0
QValidator::State CSVWorld::IdValidator::validate (QString& input, int& pos) const
{
    mError.clear();

    if (mRelaxed)
    {
        if (input.indexOf ('"')!=-1 || input.indexOf ("::")!=-1 || input.indexOf ("#")!=-1)
            return QValidator::Invalid;
    }
    else
    {
        if (input.isEmpty())
        {
            mError = "Missing ID";
            return QValidator::Intermediate;
        }

        bool first = true;
        bool scope = false;
        bool prevScope = false;

        QString::const_iterator iter = input.begin();

        if (!mNamespace.empty())
        {
            std::string namespace_ = input.left (mNamespace.size()).toUtf8().constData();

            if (Misc::StringUtils::lowerCase (namespace_)!=mNamespace)
                return QValidator::Invalid; // incorrect namespace

            iter += namespace_.size();
            first = false;
            prevScope = true;
        }
        else
        {
            int index = input.indexOf (":");

            if (index!=-1)
            {
                QString namespace_ = input.left (index);

                if (namespace_=="project" || namespace_=="session")
                    return QValidator::Invalid; // reserved namespace
            }
        }

        for (; iter!=input.end(); ++iter, first = false)
        {
            if (*iter==':')
            {
                if (first)
                    return QValidator::Invalid; // scope operator at the beginning

                if (scope)
                {
                    scope = false;
                    prevScope = true;
                }
                else
                {
                    if (prevScope)
                        return QValidator::Invalid; // sequence of two scope operators

                    scope = true;
                }
            }
            else if (scope)
                return QValidator::Invalid; // incomplete scope operator
            else
            {
                prevScope = false;

                if (!isValid (*iter, first))
                    return QValidator::Invalid;
            }
        }

        if (scope)
        {
            mError = "ID ending with incomplete scope operator";
            return QValidator::Intermediate;
        }

        if (prevScope)
        {
            mError = "ID ending with scope operator";
            return QValidator::Intermediate;
        }
    }

    return QValidator::Acceptable;
}
Example #16
0
QStringList DBBrowserDB::decodeCSV(const QString & csvfilename, char sep, char quote, int maxrecords, int * numfields)
{
    QFile file(csvfilename);
    QStringList result;
    *numfields = 0;
    int recs = 0;

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return result;
    }

    //Other than QFile, the QTextStream-class properly detects 2-Byte QChars and converts them accordingly (UTF-8)
    QTextStream inStream(&file);

    QProgressDialog progress(QObject::tr("Decoding CSV file..."), QObject::tr("Cancel"), 0, file.size());
    progress.setWindowModality(Qt::ApplicationModal);



    while (!inStream.atEnd()) {

        bool inquotemode = false;
        bool inescapemode = false;
        QString line = "";
        QString current = "";

        line = inStream.readLine();

        //For every Line, we iterate over the single QChars
        QString::ConstIterator i = line.begin();

        while (i != line.end()) {

            QChar c = *i;

            if (c==quote){
                if (inquotemode){
                    if (inescapemode){
                        inescapemode = false;
                        //add the escaped char here
                        current.append(c);
                    } else {
                        //are we escaping, or just finishing the quote?
                        i++; //Performing lookahead using the iterator
                        QChar d = *i;

                        if (d==quote) {
                            inescapemode = true;
                        } else {
                            inquotemode = false;
                        }
                        i--;
                    }
                } else {
                    inquotemode = true;
                }
            } else if (c==sep) {
                if (inquotemode){
                    //add the sep here
                    current.append(c);
                } else {
                    //not quoting, start new record
                    result << current;
                    current = "";
                }
            } else if (c==10 || c==13) {
                if (inquotemode){
                    //add the newline/carrier return
                    current.append(c);
                }
            } else if (c==32) {
              
              // Only append blanks if we are inside of quotes
              if (inquotemode || quote == 0) {
                current.append(c);
              }

            } else {//another character type
                current.append(c);
            }

            i++;
        }

        //Moved this block from (c==10), as line-separation is now handeled by the outer-loop
        result << current;

        if (*numfields == 0){
            *numfields = result.count();
        }
        recs++;
        progress.setValue(file.pos());
        qApp->processEvents();

        if ( (progress.wasCanceled() || recs>maxrecords) && maxrecords!=-1) {
            break;
        }
    }

    file.close();

    return result;

}
Example #17
0
// static
ChromaticKey KeyUtils::guessKeyFromText(const QString& text) {
    QString trimmed = text.trimmed();

    // Try using the user's custom notation.
    {
        QMutexLocker locker(&s_notationMutex);
        QMap<QString, ChromaticKey>::const_iterator it = s_reverseNotation.find(text);
        if (it != s_reverseNotation.end()) {
            return it.value();
        }
    }

    QRegExp openKeyMatcher(s_openKeyPattern, Qt::CaseInsensitive);
    if (openKeyMatcher.exactMatch(trimmed)) {
        bool ok = false;
        int openKeyNumber = openKeyMatcher.cap(1).toInt(&ok);

        // Regex should mean this never happens.
        if (!ok || openKeyNumber < 1 || openKeyNumber > 12) {
            return mixxx::track::io::key::INVALID;
        }

        bool major = openKeyMatcher.cap(2)
                .compare("d", Qt::CaseInsensitive) == 0;

        return openKeyNumberToKey(openKeyNumber, major);
    }

    QRegExp lancelotKeyMatcher(s_lancelotKeyPattern, Qt::CaseInsensitive);
    if (lancelotKeyMatcher.exactMatch(trimmed)) {
        bool ok = false;
        int lancelotNumber = lancelotKeyMatcher.cap(1).toInt(&ok);

        // Regex should mean this never happens.
        if (!ok || lancelotNumber < 1 || lancelotNumber > 12) {
            return mixxx::track::io::key::INVALID;
        }

        int openKeyNumber = lancelotNumberToOpenKeyNumber(lancelotNumber);

        bool major = lancelotKeyMatcher.cap(2)
                .compare("b", Qt::CaseInsensitive) == 0;

        return openKeyNumberToKey(openKeyNumber, major);
    }

    QRegExp keyMatcher(s_keyPattern, Qt::CaseInsensitive);
    if (keyMatcher.exactMatch(trimmed)) {
        // Take the first letter, lowercase it and subtract 'a' and we get a
        // number between 0-6. Look up the major key associated with that letter
        // from s_letterToMajorKey. Upper-case means major, lower-case means
        // minor. Then apply the sharps or flats to the key.
        QChar letter = keyMatcher.cap(1).at(0);
        int letterIndex = letter.toLower().toAscii() - 'a';
        bool major = letter.isUpper();

        // Now apply sharps and flats to the letter key.
        QString adjustments = keyMatcher.cap(2);
        int steps = 0;
        for (QString::const_iterator it = adjustments.begin();
             it != adjustments.end(); ++it) {
            steps += (*it == '#' || *it == s_sharpSymbol[0]) ? 1 : -1;
        }

        QString scale = keyMatcher.cap(3);
        // we override major if a scale definition exists
        if (! scale.isEmpty()) {
            if (scale.compare("m", Qt::CaseInsensitive) == 0) {
                major = false;
            } else if (scale.startsWith("min", Qt::CaseInsensitive)) {
                major = false;
            } else if (scale.startsWith("maj", Qt::CaseInsensitive)) {
                major = true;
            } else {
                qDebug() << "WARNING: scale from regexp has unexpected value."
                  " should never happen";
            }
        }

        ChromaticKey letterKey = static_cast<ChromaticKey>(
            s_letterToMajorKey[letterIndex] + (major ? 0 : 12));
        return scaleKeySteps(letterKey, steps);
    }

    // We didn't figure out the key. Womp womp.
    return mixxx::track::io::key::INVALID;
}
QString CharactersFrame::sortChars(const QString& text) const {
    QString res = text;
    qSort(res.begin(),res.end());
    return res;
}