Have problem with lex - lex

My lex as follows:
LNUM [0-9]+
DNUM([0-9]*"."[0-9]+)|([0-9]+"."[0-9]*)
%%
{LNUM} {
printf("\t");ECHO;printf("\r\n");
}
{DNUM} {
printf("\t");ECHO;printf("\r\n");
}
But it turns out that it can only match numbers like 4.12 .2,not 42,45. etc.(those indented are matched)
Output:
1.
1.
.1
.1
12
12
My target is to match both integers and float numbers.
Can anyone here tell me what's wrong above?

Late answer to your question... but for what it's worth, I tried replacing the * you had in the original lex file (the second pattern for DNUM) with a + (because that ensures that you at least have one digit to the right of the decimal point in order for the number to be counted as a decimal...) and it seems to work for me, at least. Hope this helps someone in the future.
lex file:
%{
#include <iostream>
using namespace std;
%}
LNUM [0-9]+
DNUM ([0-9]*"."[0-9]+)|([0-9]+"."[0-9]+)
%option noyywrap
%%
{LNUM}* { cout << "lnum: " << yytext << endl; }
{DNUM}* { cout << "dnum: " << yytext << endl; }
%%
int main(int argc, char ** argv)
{
yylex();
return 0;
}
example input (on command line):
$ echo "4.12 .2 42 45. " | ./lexer
dnum: 4.12
dnum: .2
lnum: 42
lnum: 45.

Related

How can I solve "lex program for the pattern that starts with vowel, ends with consonant and might have digits too"

I have tried to solve this question "Write a lex program for the pattern that starts with vowel, ends with consonant and might have digits too."
Here is my code:
%{
#include<stdio.h>
#include<string.h>
int cno=0, wno=0, lno=o;
%}
character [a-zA-z]
digit [0-9]
word({character}|{digit})+
line\n
%%
{line}{cno++;lno++;}
{line}{wno++; cno+=strlen(yytext);}{cno++;}
%%
int main(void)
{
yylex();
print("Count alphanumeric pattern: %d;", cno);
print("Length of string: %d;", wno);
print("Line numbers: %d\n", lno);
return 0;
}
Here is the output:
line 23: unrecognized rule
line 23: fatal parse error
I think the following code will solve your problem.
%{
int valid_patterns = 0, invalid_patterns =0;
%}
PATTERN ([aeiouAEIOU][A-Za-z0-9]*[b-df-hj-np-tv-zB-DF-HJ-NP-TV-Z])*
%%
{PATTERN} {printf("\n\t Pattern Matched: %s", yytext); valid_patterns++;}
[A-Za-z0-9]+ {invalid_patterns++;}
"\n" {
printf("\n\n\t Total Matched Patterns : %d", valid_patterns);
printf("\n\t Total Unmatched Patterns: %d\n", invalid_patterns);
valid_patterns = 0; invalid_patterns = 0;
}
%%
/*** User code section***/
int yywrap(){}
int main(int argc, char **argv[])
{
printf("\n Enter your inputs: \n\n");
yylex();
return 0;
}
Explanation of the first rule for PATTERN as per your questions requirements:
[aeiouAEIOU] make sure a pattern starts with a vowel.
[A-Za-z0-9]* indicates that any alphanumeric character can occur in middle.
[b-df-hj-np-tv-zB-DF-HJ-NP-TV-Z] make sure a pattern ends with a consonant.
(...)* indicates there might be 0 or more occurrence of desire pattern.
The second rule [A-Za-z0-9]+ catches any other input that doesn't match the requirements. And the final rule "\n"takes action when you input a new line, it prints information about your inputs.
An I/O example---
Input: Hello amazing people around the world
Output:
Pattern Matched: amazing
Pattern Matched: around
Total Matched Patterns : 2
Total Unmatched Patterns: 4

How to run a simple openMP example using eclipse?

I already have intel basekit installed, and eclipse for C / C ++: (eclipse-inst-jre-linux64.tar.gz), but I can't find a way to run a simple example using openmp.
In the terminal I compile my example with:
icpx -fiopenmp -fopenmp-targets = spir64 random_openmp.cpp
but I can't do the same using eclipse.
Please find the example code below:
# include <iostream>
# include <iomanip>
# include <cmath>
# include <ctime>
# include <omp.h>
using namespace std;
int main ( );
void monte_carlo ( int n, int &seed );
double random_value ( int &seed );
void timestamp ( );
/******************************************************************************/
int main ( void )
/******************************************************************************/
/*
Purpose:
MAIN is the main program for RANDOM_OPENMP.
Discussion:
This program simply explores one issue in the generation of random
numbers in a parallel program. If the random number generator uses
an integer seed to determine the next entry, then it is not easy for
a parallel program to reproduce the same exact sequence.
But what is worse is that it might not be clear how the separate
OpenMP threads should handle the SEED value - as a shared or private
variable? It seems clear that each thread should have a private
seed that is initialized to a distinct value at the beginning of
the computation.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 September 2012
Author:
John Burkardt
*/
{
int n;
int seed;
timestamp ( );
cout << "\n";
cout << "RANDOM_OPENMP\n";
cout << " C++ version\n";
cout << " An OpenMP program using random numbers.\n";
cout << " The random numbers depend on a seed.\n";
cout << " We need to insure that each OpenMP thread\n";
cout << " starts with a different seed.\n";
cout << "\n";
cout << " Number of processors available = " << omp_get_num_procs ( ) << "\n";
cout << " Number of threads = " << omp_get_max_threads ( ) << "\n";
n = 100;
seed = 123456789;
monte_carlo ( n, seed );
/*
Terminate.
*/
cout << "\n";
cout << "RANDOM_OPENMP\n";
cout << " Normal end of execution.\n";
cout << "\n";
timestamp ( );
return 0;
}
/******************************************************************************/
void monte_carlo ( int n, int &seed )
/******************************************************************************/
/*
Purpose:
MONTE_CARLO carries out a Monte Carlo calculation with random values.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 September 2012
Author:
John Burkardt
Parameter:
Input, int N, the number of values to generate.
Input, int &SEED, a seed for the random number generator.
*/
{
int i;
int my_id;
int *my_id_vec;
int my_seed;
int *my_seed_vec;
double *x;
x = new double[n];
my_id_vec = new int[n];
my_seed_vec = new int[n];
# pragma omp master
{
cout << "\n";
cout << " Thread Seed I X(I)\n";
cout << "\n";
}
# pragma omp parallel private ( i, my_id, my_seed ) shared ( my_id_vec, my_seed_vec, n, x )
{
my_id = omp_get_thread_num ( );
my_seed = seed + my_id;
cout << " " << setw(6) << my_id
<< " " << setw(12) << my_seed << "\n";
# pragma omp for
for ( i = 0; i < n; i++ )
{
my_id_vec[i] = my_id;
x[i] = random_value ( my_seed );
my_seed_vec[i] = my_seed;
// cout << " " << setw(6) << my_id
// << " " << setw(12) << my_seed
// << " " << setw(6) << i
// << " " << setw(14) << x[i] << "\n";
}
}
//
// C++ OpenMP IO from multiple processors comes out chaotically.
// For this reason only, we'll save the data from the loop and
// print it in the sequential section!
//
for ( i = 0; i < n; i++ )
{
cout << " " << setw(6) << my_id_vec[i]
<< " " << setw(12) << my_seed_vec[i]
<< " " << setw(6) << i
<< " " << setw(14) << x[i] << "\n";
}
delete [] my_id_vec;
delete [] my_seed_vec;
delete [] x;
return;
}
/******************************************************************************/
double random_value ( int &seed )
/******************************************************************************/
/*
Purpose:
RANDOM_VALUE generates a random value R.
Discussion:
This is not a good random number generator. It is a SIMPLE one.
It illustrates a model which works by accepting an integer seed value
as input, performing some simple operation on the seed, and then
producing a "random" real value using some simple transformation.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 September 2012
Author:
John Burkardt
Parameters:
Input/output, int &SEED, a seed for the random
number generator.
Output, double RANDOM_VALUE, the random value.
*/
{
double r;
seed = ( seed % 65536 );
seed = ( ( 3125 * seed ) % 65536 );
r = ( double ) ( seed ) / 65536.0;
return r;
}
//****************************************************************************80
void timestamp ( )
//****************************************************************************80
//
// Purpose:
//
// TIMESTAMP prints the current YMDHMS date as a time stamp.
//
// Example:
//
// 31 May 2001 09:45:54 AM
//
// Modified:
//
// 24 September 2003
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// None
//
{
# define TIME_SIZE 40
static char time_buffer[TIME_SIZE];
const struct tm *tm;
time_t now;
now = time ( NULL );
tm = localtime ( &now );
strftime ( time_buffer, TIME_SIZE, "%d %B %Y %I:%M:%S %p", tm );
cout << time_buffer << "\n";
return;
# undef TIME_SIZE
}
There is an article explaining how to use Intel C++ compiler in Eclipse here: 
https://software.intel.com/content/www/us/en/develop/articles/intel-c-compiler-for-linux-using-intel...
, also one more recent documentation on running a sample program in Eclipse here:
https://software.intel.com/content/www/us/en/develop/documentation/get-started-with-intel-oneapi-base-linux/top/run-a-sample-project-using-an-ide.html
and
https://software.intel.com/content/www/us/en/develop/documentation/get-started-with-intel-oneapi-hpc-linux/top/run-a-sample-project-with-eclipse.html
The HPCKit Get Start used the matrix sample. It has an OpenMP version. So you need to launch Eclipse from terminal window where the env is set with "servars.sh".

How to fix the problem that I can't match the pattern I defined in Lex?

I'm writing a Lex code for scanning Verilog code, and I define a pattern that I want to match. But when I run the code, I find that the pattern I defined won't match. Where did I make a mistake?
I run the code on a Linux workstation. The flex version is 2.5.4.
%option c++
%option noyywrap
%{
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<string> input_vec; /*To remember which signal is input*/
int input_num = 0; /*To count the # of input signals*/
%}
%x INPUT
var_string [a-z]+
%%
input {
cout << "BEGIN INPUT" << endl;
BEGIN INPUT;
}
[ \n\t\r\f]+
.
<INPUT>{var_string} {
cout << "IN INPUT MATCHING var_string:" << yytext << endl;
input_num++;
input_vec.push_back(yytext);
}
<INPUT>; {BEGIN 0;}
<INPUT>,
<INPUT>[ \n\t\r\f]+
%%
int main(int argc, char* argv[])
{
ifstream input_file("test.v");
FlexLexer* lexer;
lexer = new yyFlexLexer(&input_file, &cout);
while(lexer->yylex()!=0);
cout << "Input Number: " << input_num << endl;
return 0;
}
Here is the Verilog code I want to scan.
module test(a, b, c, sum, carry);
input
a,
b,
c;
output
sum,
carry;
wire
d;
assign
d = (~b & a) | (b & ~a),
sum = (d & c) | (d & ~c),
carry= (a & b) | (b & c) | (a & c);
endmodule
I except that when the Lex code scan a, b, and c in input section, the output will be:
BEGIN INPUT
IN INPUT MATCHING var_string:a
IN INPUT MATCHING var_string:b
IN INPUT MATCHING var_string:c
Input Number: 3
However, the real output is:
BEGIN INPUT
Input Number: 0

How To Create and Verify Blind RSA Signatures With Crypto++?

I've read through the whitepapers and specifications relating to blind signatures which I've been able to come across, inclusive of the Wikipedia entries, but these tend to focus on the mathematical theory behind it.
Is there a concise practical implementation of RSA blind signatures within c++ using the Crypto++ library?
Is there a concise practical implementation of RSA blind signatures within c++ using the Crypto++ library?
Yes. The Crypto++ wiki has a section on blind signatures for RSA at Raw RSA | RSA Blind Signature. Below is the code taken from the wiki.
Crypto++ lacks blind signature classes. The method below follows the basic algorithm as detailed at Blind Signatures. However, it differs from Wikipedia by applying the s(s'(x)) = x cross-check. The cross-check was present in Chaum's original paper, but it is missing from the wiki article. A second difference from Chaum's paper and wikipedia is, the code below uses H(m) rather than m. That's due to Rabin in 1979.
As far as we know there is no standard covering the signature scheme. The lack of standardization will surely cause interop problems. For example, the code below uses SHA256 to hash the message to be signed, while RSA Blind Signature Scheme for golang uses full domain hashing. Also see Is there a standard padding/format for RSA Blind Signatures? on Crypto.SE.
You may want to apply a padding function first per Usability of padding scheme in blinded RSA signature? or RSA blind signatures in practice.
#include "cryptlib.h"
#include "integer.h"
#include "nbtheory.h"
#include "osrng.h"
#include "rsa.h"
#include "sha.h"
using namespace CryptoPP;
#include <iostream>
#include <stdexcept>
using std::cout;
using std::endl;
using std::runtime_error;
int main(int argc, char* argv[])
{
// Bob artificially small key pair
AutoSeededRandomPool prng;
RSA::PrivateKey privKey;
privKey.GenerateRandomWithKeySize(prng, 64);
RSA::PublicKey pubKey(privKey);
// Convenience
const Integer& n = pubKey.GetModulus();
const Integer& e = pubKey.GetPublicExponent();
const Integer& d = privKey.GetPrivateExponent();
// Print params
cout << "Pub mod: " << std::hex << pubKey.GetModulus() << endl;
cout << "Pub exp: " << std::hex << e << endl;
cout << "Priv mod: " << std::hex << privKey.GetModulus() << endl;
cout << "Priv exp: " << std::hex << d << endl;
// For sizing the hashed message buffer. This should be SHA256 size.
const size_t SIG_SIZE = UnsignedMin(SHA256::BLOCKSIZE, n.ByteCount());
// Scratch
SecByteBlock buff1, buff2, buff3;
// Alice original message to be signed by Bob
SecByteBlock orig((const byte*)"secret", 6);
Integer m(orig.data(), orig.size());
cout << "Message: " << std::hex << m << endl;
// Hash message per Rabin (1979)
buff1.resize(SIG_SIZE);
SHA256 hash1;
hash1.CalculateTruncatedDigest(buff1, buff1.size(), orig, orig.size());
// H(m) as Integer
Integer hm(buff1.data(), buff1.size());
cout << "H(m): " << std::hex << hm << endl;
// Alice blinding
Integer r;
do {
r.Randomize(prng, Integer::One(), n - Integer::One());
} while (!RelativelyPrime(r, n));
// Blinding factor
Integer b = a_exp_b_mod_c(r, e, n);
cout << "Random: " << std::hex << b << endl;
// Alice blinded message
Integer mm = a_times_b_mod_c(hm, b, n);
cout << "Blind msg: " << std::hex << mm << endl;
// Bob sign
Integer ss = privKey.CalculateInverse(prng, mm);
cout << "Blind sign: " << ss << endl;
// Alice checks s(s'(x)) = x. This is from Chaum's paper
Integer c = pubKey.ApplyFunction(ss);
cout << "Check sign: " << c << endl;
if (c != mm)
throw runtime_error("Alice cross-check failed");
// Alice remove blinding
Integer s = a_times_b_mod_c(ss, r.InverseMod(n), n);
cout << "Unblind sign: " << s << endl;
// Eve verifies
Integer v = pubKey.ApplyFunction(s);
cout << "Verify: " << std::hex << v << endl;
// Convert to a string
size_t req = v.MinEncodedSize();
buff2.resize(req);
v.Encode(&buff2[0], buff2.size());
// Hash message per Rabin (1979)
buff3.resize(SIG_SIZE);
SHA256 hash2;
hash2.CalculateTruncatedDigest(buff3, buff3.size(), orig, orig.size());
// Constant time compare
bool equal = buff2.size() == buff3.size() && VerifyBufsEqual(
buff2.data(), buff3.data(), buff3.size());
if (!equal)
throw runtime_error("Eve verified failed");
cout << "Verified signature" << endl;
return 0;
}
Here is the result of building and running the program:
$ g++ blind.cxx ./libcryptopp.a -o blind.exe
$ ./blind.exe
Pub mod: b55dc5e79993680fh
Pub exp: 11h
Priv mod: b55dc5e79993680fh
Priv exp: 1b4fc70ff2e97f1h
Message: 736563726574h
H(m): 2bb80d537b1da3e3h
Random: 72dd6819f0fc5e5fh
Blinded msg: 27a2e2e5e6f4fbfh
Blind sign: 84e7039495bf0570h
Check sign: 27a2e2e5e6f4fbfh
Unblind sign: 61054203e843f380h
Verify: 2bb80d537b1da3e3h
Verified signature

How to animate the command line?

I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar of sorts that looks like this:
[======> ] 37%
and of course the loading bar moves and the percent changes, But it doesn't make a new line. I cannot figure out how to do this. Can someone point me in the right direction?
One way to do this is to repeatedly update the line of text with the current progress. For example:
def status(percent):
sys.stdout.write("%3d%%\r" % percent)
sys.stdout.flush()
Note that I used sys.stdout.write instead of print (this is Python) because print automatically prints "\r\n" (carriage-return new-line) at the end of each line. I just want the carriage-return which returns the cursor to the start of the line. Also, the flush() is necessary because by default, sys.stdout only flushes its output after a newline (or after its buffer gets full).
There are two ways I know of to do this:
Use the backspace escape character ('\b') to erase your line
Use the curses package, if your programming language of choice has bindings for it.
And a Google revealed ANSI Escape Codes, which appear to be a good way. For reference, here is a function in C++ to do this:
void DrawProgressBar(int len, double percent) {
cout << "\x1B[2K"; // Erase the entire current line.
cout << "\x1B[0E"; // Move to the beginning of the current line.
string progress;
for (int i = 0; i < len; ++i) {
if (i < static_cast<int>(len * percent)) {
progress += "=";
} else {
progress += " ";
}
}
cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%";
flush(cout); // Required.
}
The secret is to print only \r instead of \n or \r\n at the and of the line.
\r is called carriage return and it moves the cursor at the start of the line
\n is called line feed and it moves the cursor on the next line
In the console. If you only use \r you overwrite the previously written line.
So first write a line like the following:
[ ]
then add a sign for each tick
\r[= ]
\r[== ]
...
\r[==========]
and so on.
You can use 10 chars, each representing a 10%.
Also, if you want to display a message when finished, don't forget to also add enough white chars so that you overwrite the previously written equal signs like so:
\r[done ]
below is my answer,use the windows APIConsoles(Windows), coding of C.
/*
* file: ProgressBarConsole.cpp
* description: a console progress bar Demo
* author: lijian <hustlijian#gmail.com>
* version: 1.0
* date: 2012-12-06
*/
#include <stdio.h>
#include <windows.h>
HANDLE hOut;
CONSOLE_SCREEN_BUFFER_INFO bInfo;
char charProgress[80] =
{"================================================================"};
char spaceProgress = ' ';
/*
* show a progress in the [row] line
* row start from 0 to the end
*/
int ProgressBar(char *task, int row, int progress)
{
char str[100];
int len, barLen,progressLen;
COORD crStart, crCurr;
GetConsoleScreenBufferInfo(hOut, &bInfo);
crCurr = bInfo.dwCursorPosition; //the old position
len = bInfo.dwMaximumWindowSize.X;
barLen = len - 17;//minus the extra char
progressLen = (int)((progress/100.0)*barLen);
crStart.X = 0;
crStart.Y = row;
sprintf(str,"%-10s[%-.*s>%*c]%3d%%", task,progressLen,charProgress, barLen-progressLen,spaceProgress,50);
#if 0 //use stdand libary
SetConsoleCursorPosition(hOut, crStart);
printf("%s\n", str);
#else
WriteConsoleOutputCharacter(hOut, str, len,crStart,NULL);
#endif
SetConsoleCursorPosition(hOut, crCurr);
return 0;
}
int main(int argc, char* argv[])
{
int i;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hOut, &bInfo);
for (i=0;i<100;i++)
{
ProgressBar("test", 0, i);
Sleep(50);
}
return 0;
}
PowerShell has a Write-Progress cmdlet that creates an in-console progress bar that you can update and modify as your script runs.
Here is the answer for your question... (python)
def disp_status(timelapse, timeout):
if timelapse and timeout:
percent = 100 * (float(timelapse)/float(timeout))
sys.stdout.write("progress : ["+"*"*int(percent)+" "*(100-int(percent-1))+"]"+str(percent)+" %")
sys.stdout.flush()
stdout.write("\r \r")
As a follow up to Greg's answer, here is an extended version of his function that allows you to display multi-line messages; just pass in a list or tuple of the strings you want to display/refresh.
def status(msgs):
assert isinstance(msgs, (list, tuple))
sys.stdout.write(''.join(msg + '\n' for msg in msgs[:-1]) + msgs[-1] + ('\x1b[A' * (len(msgs) - 1)) + '\r')
sys.stdout.flush()
Note: I have only tested this using a linux terminal, so your mileage may vary on Windows-based systems.
If your using a scripting language you could use the "tput cup" command to get this done...
P.S. This is a Linux/Unix thing only as far as I know...