can somebody give an example usage of pcrecpp "DoMatch" routine? - pcre

Can somebody give an example usage of pcrecpp DoMatch routine? Basically my requirement is to capture all the matches into a vector. I don't want to use FullMatch or PartialMatch because they record the matches in the arguments passed to them.

I had found this example on the web a while ago. I can't seem to find the link now.
vector<string> regex_tools::regex_matches(const string& str
, const string& regex
, bool ignorecase
, bool submatches)
{
vector<string> svec;
pcrecpp::RE_Options opt(PCRE_DEF_FLAGS);
opt.set_caseless(ignorecase);
pcrecpp::RE re(regex, opt);
int n = re.NumberOfCapturingGroups();
if (n <=0)
return svec;
else if(n > 10){
fprintf(stderr, "Overflow: There are too many capturing groups\n");
return svec;
}
/* sigh */
string matches[10];
const pcrecpp::Arg *args[10];
int z = 0;
pcrecpp::Arg arg0 = &matches[z];
args[z++] = &arg0;
pcrecpp::Arg arg1 = &matches[z];
args[z++] = &arg1;
pcrecpp::Arg arg2 = &matches[z];
args[z++] = &arg2;
pcrecpp::Arg arg3 = &matches[z];
args[z++] = &arg3;
pcrecpp::Arg arg4 = &matches[z];
args[z++] = &arg4;
pcrecpp::Arg arg5 = &matches[z];
args[z++] = &arg5;
pcrecpp::Arg arg6 = &matches[z];
args[z++] = &arg6;
pcrecpp::Arg arg7 = &matches[z];
args[z++] = &arg7;
pcrecpp::Arg arg8 = &matches[z];
args[z++] = &arg8;
pcrecpp::Arg arg9 = &matches[z];
args[z++] = &arg9;
pcrecpp::StringPiece input(str);
int consumed;
do {
if (re.DoMatch(input, RE::UNANCHORED, &consumed, args, n)) {
input.remove_prefix(consumed);
for (int t = 0; t < n; t++){
svec.push_back(matches[t]);
}
}
else
break;
} while (submatches);
return svec;
}

Related

recvfrom() socket is not working after this function

I am facing issue with calling to recvfrom function:
recvfrom(sock, dat, sizeof(dat), 0, (void *)&peername, &peernamelen);
Until this all functions are working.
Please let me know where I am making mistake. Should I use bind or not, or any mistake from this.
Output:
before sockname
after sockname
after sock
after setsockopt
after Bind
before recvfrom
My code:
struct sockaddr_can sockname = {
.can_family = AF_CAN,
.can_addr.j1939 = {
.addr = J1939_NO_ADDR,
.name = J1939_NO_NAME,
.pgn = J1939_NO_PGN,
},
}, peername = {
.can_family = AF_CAN,
.can_addr.j1939 = {
.addr = J1939_NO_ADDR,
.name = J1939_NO_NAME,
.pgn = J1939_NO_PGN,
},
};
uint8_t dat[128];
int valid_peername = 0;
unsigned int todo_send = 0;
int todo_recv = 0, todo_echo = 0, todo_prio = -1;
int todo_connect = 0, todo_names = 0, todo_wait = 0, todo_rebind = 0;
int todo_broadcast = 0, todo_promisc = 0;
int no_bind = 0,i;
printf("before sockname\n");
sockname.can_ifindex = if_nametoindex(CAN_SOCKET_NAME);
printf("after sockname\n");
sock = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);
printf("after sock\n");
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &todo_broadcast, sizeof(todo_broadcast));
printf("after setsockopt\n");
ret = bind(sock, (void *)&sockname, sizeof(sockname));
if (ret < 0)
err(1, "bind()");
printf("after Bind\n");
while(1){
peernamelen = sizeof(peername);
printf("before recvfrom\n");
recvfrom(sock, dat, sizeof(dat), 0, (void *)&peername, &peernamelen);
printf("%02x %05x:", peername.can_addr.j1939.addr, peername.can_addr.j1939.pgn);
for (i = 0, j = 0; i < ret; ++i, j++) {
if (j == 8) {
printf("\n%05x ", i);
j = 0;
}
printf(" %02x", dat[i]);
}
printf("\n");
}
Please help me to solve this issue.

Convert std::string from UTF8, UTF16, ISO88591 to Hexadecimal

I try to Encoding the std::string from UTF8,... to Hexadecimal. What I can't do right now is that I can't get the decimal value of each character of the input string to convert it if the input string contains special character which is from the Code Page Identifiers(windows-1258) include Vietnamese character.
At first, I will get the decimal value and then convert it to Binary and then to Hexadecimal. s is my input string. s = "Ồ".
void StringUtils::strToBinary(wstring s, string* result)
{
int n = s.length();
for (int i = 0; i < n; i++)
{
wchar_t c = s[i];
long val = long(c);
std::string bin = "";
while (val > 0)
{
(val % 2) ? bin.push_back('1') :
bin.push_back('0');
val /= 2;
}
reverse(bin.begin(), bin.end());
result->append(convertBinToHex(bin));
}
}
std::string StringUtils::convertBinToHex(std::string temp) {
long long binaryValue = atoll(temp.c_str());
long long dec_value = 0;
int base = 1;
int i = 0;
while (binaryValue) {
long long last_digit = binaryValue % 10;
binaryValue = binaryValue / 10;
dec_value += last_digit * base;
base = base * 2;
}
char hexaDeciNum[10];
while (dec_value != 0)
{
int temp = 0;
temp = dec_value % 16;
if (temp < 10)
{
hexaDeciNum[i] = temp + 48;
i++;
}
else
{
hexaDeciNum[i] = temp + 55;
i++;
}
dec_value = dec_value / 16;
}
std::string str;
for (int j = i - 1; j >= 0; j--) {
str = str + hexaDeciNum[j];
}
return str;
}
If my input only contain "Ồ" this is what my expected output
UTF8 : E1BB92
UTF16 : FEFF 1ED2
UTF16BE : 1ED2
UTF16LE : D21E
This how I do it in Java
Charset charset = Charset.forName(Enum.valueOf(Encoding.class, encodingType).toString());
ByteBuffer buffer = charset.newEncoder().encode(CharBuffer.wrap(inputString.toCharArray()));
byte[] bytes = new byte[buffer.limit()];
buffer.get(bytes, 0, buffer.limit());
result = new ByteField(bytes);
return result;
}

Binary addition in java

I wrote a program for a binary addition in java. But the result is sometimes not right.
For example if i add 1110+111. The result should be 10101.
But my program throws out 10001.
Maybe one of you find the mistake.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First: ");
String input1 = scan.next("(0|1)*");
System.out.print("Second: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
this function is much simpler :
public static String binaryAdd(String binary1,String binary2){
return Long.toBinaryString(Long.parseLong(binary1,2)+Long.parseLong(binary2,2));
}
you can change Long.parseLong into Integer.parseInt if you don't expect very large numbers, you can also replace parse(Long/Int) with parseUnsigned(Long/Int) since you don't expect your strings to have a minus sign do you ?
You are not considering the case when
help1 + help2 = 3
So your method String add(String binary1, String binary2) should be like this:
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if (sum == 3){
sb.append("1");
carry = 1;
}
else if(sum ==2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
I hope this could help you!
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
If sum is 2 then append "0" and carry = 1
What about when the sum is 3, append "1" and carry = 1
Will never be 4 or greater
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
System.out.println("Enter the value you want to be converted");
Scanner inp = new Scanner(System.in);
int num = inp.nextInt();
String result = "";
while(num > 0) {
result = result + Math.floorMod(num, 2);
num = Math.round(num/2);
}
String flippedresult = "";
for(int i = 0; i < result.length(); i++) {
flippedresult = result.charAt(i) + flippedresult;
}
System.out.println(flippedresult);
}
}
This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
String decimalToBinaryString = new String();
System.out.println("First decimal number to be added");
int num1 = inp.nextInt();
String binary1 = decimalToBinaryString(num1);
System.out.println("Input decimal number 2");
int num2 = inp.nextInt();
String binary2 = decimalToBinaryString(num2);
int patternlength = Math.max[binary1.length[], binary2.length[]];
while(binary1.length() < patternlength) {
binary1 = "0" + binary2;
}
System.out.println(binary1);
System.out.println(binary2);
int carry = 0;
int frequency_of_one;
String result = "";
for(int i = patternlength -i; i >= 0; i--) {
frequency_of_one = carry;
if(binary1.charAt(i) == '1') {
frequency_of_one++;
}
if(binary2.charAt(i) == '1') {
frequency_of_one++;
}
switch(frequency_of_one) {
case 0 ;
carry = 0;
result = "1" + result;
break;
case 1 ;
carry = 0;
result = "1" + result;
break;
case 2;
carry = 1;
result = "0" + result;
breake;
case 3;
carry = 1;
result = "1" + result;
breake;
}
}
if(carry == 1) {
result = "1" + result;
}
System.out.println(result);
}
public static String decimalToBinaryString(int decimal1) {
String result = "";
while(decimal1 > 0) {
result = result + Math.floorMod(decimal1, 2);
decimal = Math.round(decimal1/2);
}
String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}
}

can't access static method of a simple cs file in xaml.cs file

I'm creating an app for my semester project. In this project I have a simple class file and a few xaml pages. In one xaml page the code checks the value of a string and depending on that value runs a countdown timer. If the value of string is equal to a certain string then it should call a method from simple class where the value of string is changed and then it should navigate to the next xaml page.
When I call the function the application breaks. No error or anything, it just breaks. I don't know why. I have called other functions of same class file in other xaml files and they work perfect but here I'm having trouble. I guess it has something to do with timer.
xaml.cs:
namespace TrafficGuru
{
public partial class Page2 : PhoneApplicationPage
{
DispatcherTimer countDownTimer;
int check;
public Page2()
{
InitializeComponent();
tbl.Text = global.str;
if (global.str == "YOUR LIGHT IS ON FOR : ")
{
check = 0;
}
if (global.str == "YOUR LIGHT WILL BE ON IN:")
{
check = 1;
}
if (global.str == "YOUR LIGHT WILL NOT BE ON FOR UNTIL ATLEAST " + global.x * 15 + " MORE SECS.YOU WILL GET AN UPDATE IN:")
{
check = 2;
}
countDownTimer = new DispatcherTimer();
countDownTimer.Interval = new TimeSpan(0, 0, 0, 1);
countDownTimer.Tick += new EventHandler(countDownTimerEvent);
countDownTimer.Start();
test.Content = "" + "seconds remaining";
}
int count = global.cdt;
void test_Click(object sender, EventArgs e) { }
void countDownTimerEvent(object sender, EventArgs e)
{
test.Content = count + " Seconds";
if (count > 0)
{
count--;
}
else if (count == 0)
{
if (check == 0)
{
test.Content = "STOP!!";
}
else if (check == 1)
{
test.Content = "GO!!!";
}
if(check==2)
{
string x= global.rego();//the method i m trying to call its public and static
NavigationService.Navigate(new Uri("/Page3.xaml", UriKind.RelativeOrAbsolute));*/
}
}
}
}
}
globalx class code::
if (x == 1)
{
str = "YOUR LIGHT WILL BE ON IN:";
}
cdt = x*15;
l[m].resetcount();
a[m] = 0;
l[m].setlight("RED");
c = 9;
}
if (l[0].getcount() == 0 || s > 0)
{
l[0].Createcar();
}
a[0] += l[0].getcount();
t[0] = l[0].gettime();
if (l[1].getcount() == 0 || s > 0)
{
l[1].Createcar();
}
a[1] += l[1].getcount();
t[1] = l[1].gettime();
if (l[2].getcount() == 0 || s > 0)
{
l[2].Createcar();
}
a[2] = l[2].getcount();
t[2] = l[2].gettime();
if (l[3].getcount() == 0 || s > 0)
{
l[3].Createcar();
}
a[3] += l[3].getcount();
t[3] = l[3].gettime();
s++;
if (s % 2 != 0)
{
var now1 = DateTime.Now;
tv = (now1 - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
int[] pkl = { 0, 0 };
maxi(a, t, s, tym, ref pkl);
m = pkl[0];
}
else
{
var now1 = DateTime.Now;
tv = (now1 - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
int[] pkj = { 0, 0 };
maxi(a, t, s, tym, ref pkj);
q = pkj[0];
}
return str;
}
COMPLETE GLOBAL CLASS WITH GO AND REGO
public static class globalx
{
public static int n;
public static int s;
public static int m;
public static int q;
public static int c;
public static int f;
public static lane[] l = new lane[4];
public static double tv;
public static int tym;
public static int[] a = { 0, 0, 0, 0 };
public static int[] t = new int[4];
public static string str="asdf";
public static int cdt; //countdowntime
public static int x;
public static DateTime begin;
public static void start()
{
begin = DateTime.Now;
for (int i = 0; i < 4; i++)
{ l[i] = new lane(); }
var now = DateTime.Now;
tv = (now - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
l[0].Createcar();
a[0] += l[0].getcount();
t[0] = l[0].gettime();
l[1].Createcar();
a[1] += l[1].getcount();
t[1] = l[1].gettime();
l[2].Createcar();
a[2] += l[2].getcount();
t[2] = l[2].gettime();
l[3].Createcar();
a[3] += l[3].getcount();
t[3] = l[3].gettime();
now = DateTime.Now;
tv = (now - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
int[] r = { 88, 99 };
maxi(a, t, s, tym, ref r);
m = r[0];
q = r[1];
c = 0;
f = 9;
}
public static string go()
{
l[m].setlight("GREEN");
var now = DateTime.Now;
tv = (now - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
l[m].settime(tym);
if (n == m + 1)
{
c = 0;
str = "YOUR LIGHT IS ON FOR : ";
cdt = 15;
l[m].resetcount();
a[m] = 0;
l[m].setlight("RED");
}
if (n == q + 1)
{
c = 9;
str = "YOUR LIGHT WILL BE ON IN:";
cdt = 15;
l[m].resetcount();
a[m] = 0;
l[m].setlight("RED");
}
if (n != m + 1 && n != q + 1)
{
x = m + 1 - n;
if (x < 0)
{
x = 0 - x;
}
str = "YOUR LIGHT WILL NOT BE ON FOR UNTIL ATLEAST " + x * 15 + " MORE SECS.YOU WILL GET AN UPDATE IN:";
if (x == 1)
{
str = "YOUR LIGHT WILL BE ON IN:";
}
cdt = x*15;
a[m] = 0;
l[m].setlight("RED");
c = 9;
}
if (l[0].getcount() == 0 || s > 0)
{
l[0].Createcar();
}
a[0] += l[0].getcount();
t[0] = l[0].gettime();
if (l[1].getcount() == 0 || s > 0)
{
l[1].Createcar();
}
a[1] += l[1].getcount();
t[1] = l[1].gettime();
if (l[2].getcount() == 0 || s > 0)
{
l[2].Createcar();
}
a[2] = l[2].getcount();
t[2] = l[2].gettime();
if (l[3].getcount() == 0 || s > 0)
{
l[3].Createcar();
}
a[3] += l[3].getcount();
t[3] = l[3].gettime();
s++;
if (s % 2 != 0)
{
var now1 = DateTime.Now;
tv = (now1 - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
int[] pkl = { 0, 0 };
maxi(a, t, s, tym, ref pkl);
m = pkl[0];
}
else
{
var now1 = DateTime.Now;
tv = (now1 - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
int[] pkj = { 0, 0 };
maxi(a, t, s, tym, ref pkj);
q = pkj[0];
}
return str;
}
public static string rego()
{
{
l[q].setlight("GREEN");
var now = DateTime.Now;
tv = (now - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
l[q].settime(tym);
if (n == q + 1)
{
f = 0;
str = "YOUR LIGHT IS ON FOR : ";
cdt=15;
}
if (n == m + 1)
{
str = "YOUR LIGHT WILL BE ON IN:";
cdt=15;
l[q].resetcount();
a[q] = 0;
l[q].setlight("RED");
f = 9;
}
if (n != m + 1 && n != q + 1)
{
x = m + 1 - n;
if (x < 0)
{
x = 0 - x;
}
str = "YOUR LIGHT WILL NOT BE ON FOR UNTIL ATLEAST " + x * 15 + " MORE SECS.YOU WILL GET AN UPDATE IN:";
if (x == 1)
{
str = "YOUR LIGHT WILL BE ON IN:";
}
cdt = x * 15;
a[q] = 0;
l[q].setlight("RED");
f = 9;
}
}
if (l[0].getcount() == 0 || s > 0)
{
l[0].Createcar();
}
a[0] += l[0].getcount();
t[0] = l[0].gettime();
if (l[1].getcount() == 0 || s > 0)
{
l[1].Createcar();
}
a[1] += l[1].getcount();
t[1] = l[1].gettime();
if (l[2].getcount() == 0 || s > 0)
{
l[2].Createcar();
}
a[2] = l[2].getcount();
t[2] = l[2].gettime();
if (l[3].getcount() == 0 || s > 0)
{
l[3].Createcar();
}
a[3] += l[3].getcount();
t[3] = l[3].gettime();
s++;
if (s % 2 != 0)
{
var now = DateTime.Now;
tv = (now - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
int[] pkl = { 0, 0 };
maxi(a, t, s, tym, ref pkl);
m = pkl[0];
}
else
{
var now = DateTime.Now;
tv = (now - begin).TotalMilliseconds;
tym = Convert.ToInt32(tv);
int[] pkj = { 0, 0 };
maxi(a, t, s, tym, ref pkj);
q = pkj[0];
}
return str;
}
Sourround your code with try catch and see what's the message.
try
{
// Your Code
}
catch (Exception ex)
{
Debug.writeline(ex.Message);
}

How to calculate Easter Sunday in X++?

X++ method to calculate Easter Sunday?
static date dateOfEaster(Yr y)
{
int a = y mod 19;
int b = y div 100;
int c = y mod 100;
int d = b div 4;
int e = b mod 4;
int f = (b+8) div 25;
int g = (b-f+1) div 3;
int h = (19*a+b-d-g+15) mod 30;
int i = c div 4;
int k = c mod 4;
int l = (32+2*e+2*i-h-k) mod 7;
int m = (a+11*h+22*l) div 451;
int n = (h+l-7*m+114) div 31;
int p = (h+l-7*m+114) mod 31;
return mkdate(p+1,n,y);
}
I got a little creative so you can enumerate all of the holidays for a given year using GET with a public web service and a little recursion. Play around with this as you like. Just copy/paste to a JOB:
static void HolidayWebService(Args _args)
{
System.Net.WebClient webClient = new System.Net.WebClient();
str holidaysAvailable = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx/GetHolidaysAvailable?countryCode=UnitedStates";
str holidayDate = "http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx/GetHolidayDate?countryCode=%1&holidayCode=%2&year=%3";
str retVal = webClient.DownloadString(holidaysAvailable);
XMLDocument doc=XMLDocument::newXml(retVal);
XmlNamedNodemap attributes;
XmlElement root = doc.root();
XmlNode node = root.firstChild();
void getHolidayDate(str _holidayCode, Yr _yr = datetimeutil::year(datetimeutil::utcNow()), str _countryCode = 'UnitedStates')
{
System.Net.WebClient webClientInner = new System.Net.WebClient();
str locRetVal;
;
try
{
locRetVal = webClientInner.DownloadString(strfmt(holidayDate, _countryCode, _holidayCode, _yr));
info(strfmt("[%1] %2", _holidayCode, locRetVal));
}
catch
{
error(strfmt("Error with %1, %2, %3", _holidayCode, _yr, _countryCode));
continue;
}
}
void dig(XmlNode _node, int _depth = 0)
{
XmlNode sib;
;
if (_node == null)
return;
if (_node.hasChildNodes())
dig(_node.firstChild(), (_depth+1));
else
{
if (_node.parentNode().name() == 'CODE')
getHolidayDate(_node.innerText());
}
sib = _node.nextSibling();
if (sib)
dig(sib);
}
;
dig(node);
}