text:
Q: Undefined reference to `clock_gettime` although `-lrt` is given I've give -lrt as the last linker flag to the compiler. But still getting this error.
arif@khost:~/sak/sak.exosip$ gcc eXo_init.c -I/opt/osip2/include -I/opt/exosip/include  -L/opt/osip2/lib -L/opt/exosip/lib -leXosip2 -losipparser2 -losip2 -lrt
/opt/osip2/lib/libosip2.so: undefined reference to `clock_gettime'
collect2: ld returned 1 exit status

The man page says :
NAME
       clock_getres, clock_gettime, clock_settime - clock and time functions

SYNOPSIS
       #include <time.h>

       int clock_getres(clockid_t clk_id, struct timespec *res);

       int clock_gettime(clockid_t clk_id, struct timespec *tp);

       int clock_settime(clockid_t clk_id, const struct timespec *tp);

       Link with -lrt.

So i'm kind of confused where i'm doing it wrong.
I've tried to read symbols in librt.so with no luck :
arif@khost:~/sak/ortp/src/tests$ nm /lib/x86_64-linux-gnu/librt-2.15.so
nm: /lib/x86_64-linux-gnu/librt-2.15.so: no symbols

UPDATE 1 The reason i can't read symbols out of librt.so is that they are "stripped". Where can i get the symbol names ?
arif@khost:~/sak/ortp/src/tests$ file /lib/x86_64-linux-gnu/librt-2.15.so
/lib/x86_64-linux-gnu/librt-2.15.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), BuildID[sha1]=0x375b2c35c4e6503a5d1a88ab6f76f5b6e0ee81df, for GNU/Linux 2.6.24, stripped

UPDATE 2
Well things become very confusing because the following test code compiles and runs just fine :
#include <time.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv, char **arge) {
    struct timespec tps, tpe;
    if ((clock_gettime(CLOCK_REALTIME, &tps) != 0)
        || (clock_gettime(CLOCK_REALTIME, &tpe) != 0)) {
        perror("clock_gettime");
        return -1;
    }
    printf("%lu s, %lu ns\n", tpe.tv_sec-tps.tv_sec,tpe.tv_nsec-tps.tv_nsec);
    return 0;
}

Built with
arif@khost:~/sak/sak.exosip$ gcc what.c -lrt

UPDATE3 The code i'm trying compile :
#include <eXosip2/eXosip.h>
#include <netinet/in.h>
#include <unistd.h>

int ex_init(int port)
{
    struct eXosip_t *eXcontext;
    int i;
    TRACE_INITIALIZE(6, stdout);
    i = eXosip_init(eXcontext);
    if (i != 0)
        return -1;

    i = eXosip_listen_addr(eXcontext, IPPROTO_UDP, NULL, port, AF_INET, 0);
    if (i != 0) {
        eXosip_quit(eXcontext);
        fprintf (stderr, "could not initialize transport layer\n");
        return -1;
    }

    return 1;
}

int main(int argc, char **argv) {
    if(ex_init(1000))
        printf("success \n");
    return 0;
}

A: Well the problem is solved If i pass this linker flag
-Wl,--no-as-needed

Before the library list in command line.
Why this works because in my platform, linker is always passed with -Wl,--as-needed.
From ld manual :
--as-needed
       --no-as-needed
           This option affects ELF DT_NEEDED tags for dynamic libraries
           mentioned on the command line after the --as-needed option.
           Normally the linker will add a DT_NEEDED tag for each dynamic
           library mentioned on the command line, regardless of whether the
           library is actually needed or not.  --as-needed causes a DT_NEEDED
           tag to only be emitted for a library that satisfies an undefined
           symbol reference from a regular object file or, if the library is
           not found in the DT_NEEDED lists of other libraries linked up to
           that point, an undefined symbol reference from another dynamic
           library.  --no-as-needed restores the default behaviour.

So when --as-needed is given before a library , liker only links with the libraries which are given in NEEDED section of the library.
For example,
-Wl,--as-needed -llibA -llibB -llibC

Here --as-needed is given before libA. So during linking, linker will examine the NEEDED section of libA. If in NEEDED section of libA lists only libC, then the libB will not be linked.
This specific problem occurred because
arif@khost:~/sak/sak.exosip$ objdump -p /opt/osip2/lib/libosip2.so.10 | grep NEEDED
  NEEDED               libosipparser2.so.10
  NEEDED               libc.so.6

libosip2 does not lists librt as NEEDED.
If i pass --no-as-needed, then all the libraries will be linked regardless of what is given in ELF's NEEDED section.
Although this should not be the case because,
arif@khost:~/sak/sak.exosip$ nm --demangle /opt/osip2/lib/libosip2.so.10 | grep clock_gettime
                 U clock_gettime

It has undefined symbol clock_gettime which is provided by librt.so.
Well its actually a fault of the libosip2 devs that their autotools is not working with --as-needed.
The link command used by osip:
libtool: link: gcc -shared  -fPIC -DPIC  .libs/ict_fsm.o .libs/ist_fsm.o .libs/nict_fsm.o .libs/nist_fsm.o .libs/ict.o .libs/ist.o .libs/nict.o .libs/nist.o .libs/fsm_misc.o .libs/osip.o .libs/osip_transaction.o .libs/osip_event.o .libs/port_fifo.o .libs/osip_dialog.o .libs/osip_time.o .libs/port_sema.o .libs/port_thread.o .libs/port_condv.o   -Wl,-rpath -Wl,/home/arif/sak/osip/src/osipparser2/.libs -Wl,-rpath -Wl,/opt/osip2-test/lib -lnsl ../osipparser2/.libs/libosipparser2.so    -Wl,-soname -Wl,libosip2.so.10 -o .libs/libosip2.so.10.0.0

So its not linking with librt and thats why its not listing librt in its NEEDED list
If configured with :
 LDFLAGS="${LDFLAGS} -lrt" ./configure --prefix=/opt/osip2-test/

Then the link command becomes :
libtool: link: gcc -shared  -fPIC -DPIC  .libs/ict_fsm.o .libs/ist_fsm.o .libs/nict_fsm.o .libs/nist_fsm.o .libs/ict.o .libs/ist.o .libs/nict.o .libs/nist.o .libs/fsm_misc.o .libs/osip.o .libs/osip_transaction.o .libs/osip_event.o .libs/port_fifo.o .libs/osip_dialog.o .libs/osip_time.o .libs/port_sema.o .libs/port_thread.o .libs/port_condv.o   -Wl,-rpath -Wl,/home/arif/sak/osip/src/osipparser2/.libs -Wl,-rpath -Wl,/opt/osip2-test/lib -lnsl ../osipparser2/.libs/libosipparser2.so -lrt    -Wl,-soname -Wl,libosip2.so.10 -o .libs/libosip2.so.10.0.0

So its linking with librt. Its also reflected in its ELF:
arif@khost:~/sak/osip/src/osip2/.libs$ objdump -p libosip2.so.10 | grep NEEDED
  NEEDED               libosipparser2.so.10
  NEEDED               librt.so.1
  NEEDED               libc.so.6

This patch fixes this :
diff --git a/src/osip2/Makefile.am b/src/osip2/Makefile.am
index bb0d8f3..b72c22a 100644
--- a/src/osip2/Makefile.am
+++ b/src/osip2/Makefile.am
@@ -14,7 +14,7 @@ libosip2_la_SOURCES+=port_sema.c port_thread.c port_condv.c
 endif

 libosip2_la_LDFLAGS = -version-info $(LIBOSIP_SO_VERSION) \
- $(FSM_LIB) $(EXTRA_LIB) ../osipparser2/libosipparser2.la -no-undefined
+ $(FSM_LIB) $(EXTRA_LIB) ../osipparser2/libosipparser2.la -no-undefined -lrt

 INCLUDES = -I$(top_srcdir)/includ

Relevant usenet discussion thread :
https://groups.google.com/forum/#!topic/comp.unix.programmer/VKbARy6W4AY
UPDATE:
osip developer responded to my mail. He fixed it with a different patch (More general solution then mine)
http://git.savannah.gnu.org/cgit/osip.git/commit/?id=bd5b1ad58381e4bfce08bad9b66ad00cd28f9b65


text:
Q: Is progress in the coop campaign in Portal 2 saved? I've started playing the coop campaign of Portal 2 during launch break today, and had to stop because of time constraint. I didn't find an option to save the game, so we just disconnected.
Is there a way to save the coop campaign progression? If yes, how does it work? Or will I have to play the whole campaign in a single play session?

A: Yes, the progress is automatically saved and synced to the Steam Cloud individually - so when you next join a co-op game it will have stored which levels you have completed. This also means that your progress is shared across any computer you play Portal 2 on.
It's worth noting that progress is never saved during a test chamber though, only upon successful completion.
You will be able to pick which level to start at next time you start the game - if you go to the specific chapter you want to play and use the buttons until you've selected the level you want, then go into the assembly machine as usual.

A: If you're doing split-screen co-op on the one computer, then your progress is not saved. Instead, all levels are open to you so you can just go straight to the last level you completed.

A: No because when I went back on coop portal 2 I started from the begining

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to handle losing Internet connection with NSURLSession?
I am using NSURL to scrape HTML from a website. Problem is, if the internet cuts out during the NSURL request, the app crashes.Code:
let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        if error != nil {
             print("Error: \(error)")
        }
        dispatch_async(dispatch_get_main_queue()) {
            self.testLabel.text = "\(responseString!)"
        }
    }
}
task.resume()

I can check for internet connection before the NSURL connection with this code, however there is still the possibility of the internet cutting out during the operation:Code with internet connection check before NSURL:
let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        if error != nil {
             print("Error: \(error)")
        }
        dispatch_async(dispatch_get_main_queue()) {
            self.testLabel.text = "\(responseString!)"
        }
    }
}
task.resume()

To combat this problem I have researched using a try/catch operation, however I have had not luck successfully construction one that doesnt give me an error. Is there a way to wrap the whole NSURL operation in a giant try/catch that catches any errors? I was thinking something along the lines of this, but it does not work:Code:
let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    if error != nil {
         print("Error: \(error)")
    }
    dispatch_async(dispatch_get_main_queue()) {
        self.testLabel.text = "\(responseString!)"
    }
  }
}
task.resume()
} catch {
    timer.invalidate
    sendAlert("Error", message: "You are not connected to the internet")
}

A: The proper way to pronounce ! is "I swear on my program's life." Because that's what you're doing. Why do you feel you have to use !? Use guard-let to work everything out for you:
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        guard error == nil else {
            print("Error: \(error)")
            return
        }

        guard let data = data else {
            fatalError("error was nil, but no data. This should never happen")
        }

        guard let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) else {
            print("Couldn't decode data")
            return
        }

        dispatch_async(dispatch_get_main_queue()) {
            self.testLabel.text = "\(responseString)"
        }
    }

A: You should only force unwrap a variable if you know for a 100% there is a value there, otherwise you will cause your app to crash. If you require more information on this you should review the Optional Chaining section of the The Swift Programming Language guide
For checking for a
The code below should work for you.
    let myUrl = NSURL(string: "http://www.mywebsite.com/page.html")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {

            if let responseData = data {

                let responseString = NSString(data: responseData, encoding: NSUTF8StringEncoding)
                if error != nil {
                    print("Error: \(error)")
                }
                dispatch_async(dispatch_get_main_queue()) {
                    print("Response: \(responseString!)")
                }
            }

        }
    }

    task.resume()

In terms of handling a failure with your internet connection you should inspect the response send back in the closure and decide what course of action you want to take.
    if let httpResponse = response as? NSHTTPURLResponse {
    println("error \(httpResponse.statusCode)")
}


text:
Q: mdadm puts wrong devices in array on boot Correct mdadm.conf file Upon boot it stuffs it up every time:
    [root][centos ~] cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4]
md127 : inactive sda[2] sdb[3]
      1953524992 blocks
unused devices: <none>
[root][centos ~] mdadm --stop /dev/md127
mdadm: stopped /dev/md127
[root][centos ~] mdadm --assemble --scan
mdadm: /dev/md0 has been started with 4 drives.
[root][centos ~] cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4]
md0 : active raid5 sda1[0] sdd1[3] sdc1[2] sdb1[1]
      2930279424 blocks level 5, 1024k chunk, algorithm 2 [4/4] [UUUU]
unused devices: <none>

You can see first it detects a BS md127, then I have to stop that one, then reassemble it, here's one weird thing, it detects two md0's but it's sucessful:
[root][centos ~] mdadm -Es
ARRAY /dev/md0 UUID=39c28990:e753d835:8b94c90b:72da1a08
ARRAY /dev/md0 UUID=88edc937:2ecbc9bb:8b94c90b:72da1a08

my mdadm.conf
[root][centos ~] cat /etc/mdadm.conf
DEVICE partitions
ARRAY /dev/md0 UUID=88edc937:2ecbc9bb:8b94c90b:72da1a08
MAILADDR root
CREATE owner=root group=disk mode=0660 auto=yes
HOMEHOST <system>

But the weirdest thing, in dmesg, I think the problem lies here:
md: kicking non-fresh sdc from array!
md: unbind<sdc>
md: export_rdev(sdc)
md: kicking non-fresh sdd from array!
md: unbind<sdd>
md: export_rdev(sdd)
async_tx: api initialized (async)
xor: automatically using best checksumming function: generic_sse
   generic_sse:  6532.000 MB/sec
xor: using function: generic_sse (6532.000 MB/sec)
raid6: int64x1   1664 MB/s
raid6: int64x2   2148 MB/s
raid6: int64x4   1453 MB/s
raid6: int64x8   1457 MB/s
raid6: sse2x1    2417 MB/s
raid6: sse2x2    3222 MB/s
raid6: sse2x4    3429 MB/s
raid6: using algorithm sse2x4 (3429 MB/s)
md: raid6 personality registered for level 6
md: raid5 personality registered for level 5
md: raid4 personality registered for level 4
raid5: device sda operational as raid disk 2
raid5: device sdb operational as raid disk 3
raid5: allocated 4282kB for md127
2: w=1 pa=0 pr=4 m=1 a=2 r=4 op1=0 op2=0
3: w=2 pa=0 pr=4 m=1 a=2 r=4 op1=0 op2=0
raid5: not enough operational devices for md127 (2/4 failed)
RAID5 conf printout:
 --- rd:4 wd:2
 disk 2, o:1, dev:sda
 disk 3, o:1, dev:sdb
raid5: failed to run raid set md127
md: pers->run() failed ...

A: You probably need to rebuild your initrd so that it has the correct mdadm.conf file in it because the boot process has to use that version until it can get the root filesystem mounted.
What you need to do is something like this:
mkinitrd /boot/initrd-<kernel-version>.img <kernel-version>

I'm assuming here that the CentOS version you're using is still using mkinitrd - if it has switched to dracut then you will want:
dracut /boot/initramfs-<kernel-version>.img <kernel-version>

In either case you will need to rename the old file first before you can build the new one.

A: mdadm should be able to asseble a md device. It seems as it is seeing some wrong drives:
md127 : inactive sda[2] sdb[3]
That looks like it's taking the whole sda and sdb disks for the raid array, and not the partitions sda1 sdb1 sdc1 sdd1.
What does blkid show?
what does mdadm -E /dev/sda or mdadm -E /dev/sdb show?
Maybe there is something strange going on with the superblocks.
As TomH said you should also try to rebuild initrd.

A: In Ubuntu I solved this problem with this:
sudo update-initramfs -k all -u

A: I think I found it, it was a problem with my mdadm.conf file not being specific enough and possibly confusing for the OS.
So I read this: http://manpages.ubuntu.com/manpages/hardy/man5/mdadm.conf.5.html
And I found that if I use this
DEVICE partitions

Then:

This  will  cause mdadm to read /proc/partitions and include all devices and partitions found therein

So I've changed it to
DEVICE /dev/sd[abcd]1


text:
Q: How do I write an array to a file? I'm completely stuck on how to write my output to an output file. I've provided some info below to hopefully make myself more clear. Thanks to anyone that can help me.
Output when 1234 is the input (I need this to be written to the txt file):
Your original number was:
1234
The reversed digits are:
4321
The even digits are:
2 4
The odd digits are:
1 3

What is currently being written to the txt file:
Your original number was:
1234

Here is my code right now:
 import java.util.Scanner;
    import java.io.*;

    public class order {

    //Input validation. Allows any integer greater than 0. Any number starting
    with 0 is invalid.

    private static void validate(Scanner input) {

        String userEntry;

        System.out.println("Please enter a positive integer greater than 0.");
        userEntry = input.nextLine();

        while (!userEntry.matches("^[1-9][0-9]*$")) {
            System.out.println("Invalid number. Try again");
            userEntry = input.nextLine();
        }

        try {
            FileWriter writer = new FileWriter("outDataFile.txt", true);
            PrintWriter outputfile = new PrintWriter(writer);

            outputfile.println("Your original number was: ");
            outputfile.println(userEntry);
            System.out.println("Your original number was: ");
            System.out.println(userEntry);

            System.out.println("The reversed digits are: ");
            reverse (input, userEntry);
            System.out.println();

            System.out.println("The even digits are: ");
            even (input, userEntry);
            System.out.println();

            System.out.println("The odd digits are: ");
            odd (input, userEntry);
            System.out.println();

            } catch (IOException e){
        }
    }

    //Reverses the order of digits.

    public static void reverse(Scanner keyboard, String intString) {

        int strsize = intString.length();
        int[] digits = new int[strsize];

        for (int i = 0; i < strsize; ++i)
        {
            String temp = Character.toString(intString.charAt(i));
            digits[i] = Integer.parseInt(temp);
        }

        for (int i = strsize - 1; i >= 0; --i)
        {
            System.out.print(digits[i]);
        }
    }

    //Extracts even numbers.
    public static void even (Scanner keyboard2, String intString2) {

        int strsize2 = intString2.length();
        int[] digits2 = new int[strsize2];

        for (int i = 0 ; i < strsize2 ; ++i) {

                String temp = Character.toString(intString2.charAt(i));
                digits2[i] = Integer.parseInt(temp);

                if(digits2[i] % 2 == 0) {
                System.out.print(digits2[i] + " ");
            }
        }
    }

    //Extracts odd numbers.

    public static void odd (Scanner keyboard3, String intString3) {

        int strsize3 = intString3.length();
        int[] digits3 = new int[strsize3];

        for (int i = 0 ; i < strsize3 ; ++i) {

                String temp = Character.toString(intString3.charAt(i));
                digits3[i] = Integer.parseInt(temp);

                if(digits3[i] % 2 != 0) {

                System.out.print(digits3[i] + " ");
            }
        }
    }

    //Allows continuous input.

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        boolean validate = true;
        while (validate) {
        validate(keyboard);

        boolean invalid = true;
        while (invalid) {
            System.out.println( "Would you like to try another calculation? [y/n]" );

            Scanner input = new Scanner(System.in);
            char answer;
            String option = input.next();

            if ("y".equalsIgnoreCase(option)) {
                invalid = false;
            }
            else if ("n".equalsIgnoreCase(option)) {
                invalid = false;
                validate = false;
                    System.out.println( "Goodbye." );
                    input.close();
            }
            else {
                System.err.println("The only valid answers are y/n.");
                System.out.println();
            }
            }
        }
    }
}

A: The problem is in your try block.
Incorrect:
outputfile.println("Your original number was: ");
        outputfile.println(userEntry);
        System.out.println("Your original number was: ");
        System.out.println(userEntry);

    System.out.println("The reversed digits are: ");
    reverse (input, userEntry);
    System.out.println();

    System.out.println("The even digits are: ");
    even (input, userEntry);
    System.out.println();

    System.out.println("The odd digits are: ");
    odd (input, userEntry);
    System.out.println();

Problem: You almost have to mirror the System.out.println's with outputfile.println's
Correct:
outputfile.println("Your original number was: ");
outputfile.println(userEntry);
System.out.println("Your original number was: ");
System.out.println(userEntry);

System.out.println("The reversed digits are: ");
reverse (input, userEntry);
System.out.println();
outputfile.println("The reversed digits are: ");
reverse (input, userEntry);
outputfile.println();

System.out.println("The even digits are: ");
even (input, userEntry);
System.out.println();
outputfile.println("The even digits are: ");
even (input, userEntry);
outputfile.println();

System.out.println("The odd digits are: ");
odd (input, userEntry);
System.out.println();
outputfile.println("The odd digits are: ");
odd (input, userEntry);
outputfile.println();

A: I've tested the below code which works for writing the reverse number to the file. You can apply the same techniques to the other methods. Note I'm using PrintWriter.print as opposed to PrintWriter.println to get all the array elements on the same line.
public class Order {

    PrintWriter outputfile;
    FileWriter writer;

    public void validate(Scanner input) {

        String userEntry;

        System.out.println("Please enter a positive integer greater than 0.");
        userEntry = input.nextLine();

        while (!userEntry.matches("^[1-9][0-9]*$")) {
            System.out.println("Invalid number. Try again");
            userEntry = input.nextLine();
        }

        try {
            writer = new FileWriter("outDataFile.txt", true);
            outputfile = new PrintWriter(writer);

            outputfile.println("Your original number was: ");
            outputfile.println(userEntry);
            outputfile.flush();
            System.out.println("Your original number was: ");
            System.out.println(userEntry);

            System.out.println("The reversed digits are: ");
            outputfile.println("The reversed digits are: ");
            reverse (input, userEntry, writer);
            System.out.println();

        } catch (IOException e){
        }
    }

    //Reverses the order of digits.
    public void reverse(Scanner keyboard, String intString, FileWriter writer) {

        outputfile = new PrintWriter(writer);

        int strsize = intString.length();
        int[] digits = new int[strsize];

        for (int i = 0; i < strsize; ++i)
        {
            String temp = Character.toString(intString.charAt(i));
            digits[i] = Integer.parseInt(temp);
        }

        for (int i = strsize - 1; i >= 0; --i)
        {
            System.out.print(digits[i]);
            outputfile.print(digits[i]);
            outputfile.flush();
        }
    }
}


text:
Q: Output list of even Fibonacci numbers in Euler prob 2 with Python 2.75 How to output results in list form (with code not manually) on Python 2.75.
Instead of solving just for the sum I inserted print i then sum and got the numbers visible (11 of them). Please help with this very basic question. Thank you.
##Even Fibonacci numbers Problem 2
##Each new term in the Fibonacci sequence is generated by adding the previous two terms.
##By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55...
##By considering the terms in the Fibonacci sequence whose values do not exceed
##four million, find the sum of the even-valued terms.
import fibo
sum = 0
a = fibo.fib2(4000000)
for i in a:
    if i%2==0:
        print i
        sum += i
print "the sum of these even Fibonacci numbers = "
print sum
###how to create list or tuple of the
##even_fib=[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]

A: Start with an empty list and as you find them append them on:
even_fib = []

for i in a:
    if i %2 == 0:
        even_fib.append(i)

The result will be a list of all the even elements


text:
Q: add tag / push tags to remote in Python Dulwich I like the Dulwich project as it provides pure Python interface to interacting with git.
It looks pretty low-level though... While I couldn't find reference on how to perform simple tasks.

My need's are pretty simple, provide the same as below git CLI commands:

*

*git push --tags --force

*git tag --force

*git show-ref --tags (provides mapping between tag and the commit it points on)

Update:
looks like item #3 is answered here:
How to get a list of tags and create new tags with python and dulwich in git? (by Jelmer the creator of Dulwich)

A: The dulwich.porcelain (https://www.dulwich.io/docs/api/dulwich.porcelain.html#module-dulwich.porcelain) module is somewhat more high level, and should do what you need.
Specifically, the push and tag_create functions. Note that there is currently no force argument since all tag editing is currently done without safety checking.


text:
Q: Looks simple, but I'm stumped! This should be so simple, but I'm drawing a blank. I have two tables.
Table:article_tag_pvt
colum: article_id
column: tag_id

Table: tag
column: tag_id
column: name

The article_tag_pvt table is a many-to-many pivot table.
The problem is, I need a query which given a list of tag names, will retrieves article Ids which ONLY match those tag names. The basic joining of these tables looks like this:
SELECT article_id
FROM article_tag_pvt pvt
INNER JOIN tag t ON t.tag_id = pvt.tag_id

I've already got a query which will retrieve article ids which match ANY tag names specified. This looks like this:
SELECT article_id
FROM article_tag_pvt pvt
INNER JOIN tag t ON t.tag_id = pvt.tag_id
WHERE t.name IN ('events','news')

I've tried these but no joy:
SELECT article_id
FROM article_tag_pvt pvt
INNER JOIN tag t ON t.tag_id = pvt.tag_id
WHERE t.name = 'events' AND t.name = 'news'

SELECT article_id
FROM article_tag_pvt pvt
INNER JOIN (
SELECT tag_id
FROM tag
WHERE name IN ('events','news')
) AS t
ON t.tag_id = pvt.tag_id

Any help would be greatly appreciated
Dave

A: The problem is that you get ALL rows which have either event or news. If you never have more than 1 event or news in many to many table you can use GROUP BY and HAVING to solve it
SELECT article_id
FROM article_tag_pvt pvt
INNER JOIN tag t ON t.tag_id = pvt.tag_id
WHERE t.name = 'events' OR t.name = 'news'
GROUP BY article_id HAVING count(*) = 2

A: My preference is for:
SELECT pvt.article_id
  FROM article_tag_pvt pvt
  JOIN tag t ON t.tag_id = pvt.tag_id AND t.name = 'events'
  JOIN tag t2 ON t2.tag_id = pvt.tag_id AND t2.name = 'news'

Alternative using GROUP BY/HAVING:
  SELECT pvt.article_id
    FROM article_tag_pvt pvt
    JOIN tag t ON t.tag_id = pvt.tag_id
   WHERE t.name IN ('events', 'news')
GROUP BY pvt.article_id, t.name
  HAVING COUNT(DISTINCT t.name) = 2

The COUNT(DISTINCT t.name) needs to equal the number of options you define for the t.name IN clause.


text:
Q: What shell does os.system use in Python? In Python, when I run a command with
os.system

what shell gets used?

A: By default it will run in the Bourne shell (that would be /bin/sh).
os.system("/bin/bash \"echo 'Rincewind rules' \" ") to use bash and have it echo "Rincewind rules".


text:
Q: Configure and verify Vnet in Azure I have created a Virtual Network next to its subnet and integrated it into three service applications and created the rule on the firewall of my SQL Azure server.
Everything is in the same Azure subscription and region
I need to know if it is enough to direct all the traffic between these instances through the virtual network or do I need to configure some other aspect.
And how can I query the data traffic to verify that the virtual network is being used?

A: Azure Virtual Network (VNets) allows to place Azure resources in a non-internet-routable network.

https://learn.microsoft.com/en-us/azure/architecture/example-scenario/private-web-app/private-web-app#architecture
Using Azure App Service regional VNet Integration, the web app connects to Azure through an AppSvcSubnet delegated subnet in an Azure Virtual Network.
Virtual Network only routes traffic and is otherwise empty, but other subnets and workloads could also run in the Virtual Network.
The App Service and Private Link subnets could be in separate peered Virtual Networks, for example as part of a hub-and-spoke network configuration. For regional VNet Integration, the peered Virtual Networks must be located in the same Azure region.
Azure Private Link sets up a private endpoint for the Azure SQL database in the PrivateLinkSubnet of the Virtual Network.
The web app connects to the SQL Database private endpoint through the PrivateLinkSubnet of the Virtual Network.
The database firewall allows only traffic coming from the PrivateLinkSubnet to connect, making the database inaccessible from the public internet.


text:
Q: ChartJs annotation does not work with Tooltip I have a requirement where on hover i need to show one horizontal line like in below fiddle.
but tool-tip is getting disappeared once on hover horizontal line is drawn.
Can anyone help how i can get tool-tip along  with horizontal line.
Please note in below fiddle we have issue on hover it takes time but in my actual project hover is working fine , i just have issue that after hover tool-tip does not work after some time.
https://jsfiddle.net/h8ow63be/
var option = {
  legend: false,
  title: {
    display: true,
  },
  onHover: function(evt) {
    var item = myLineChart.getElementAtEvent(evt);
    if (item.length) {
     updateChart(data.datasets[0].data[item[0]._index].y)
    }
  },
  animation: {
                duration: 0
            },
  annotation: {
   annotations: lines
  },
  scales: {
    xAxes: [{
      id: 'x-axis',
      type: 'linear',
      position: 'bottom',
      ticks: {
        max: 12,
        min: 1,
        stepSize: 1
      }
    }],
    yAxes: [{
      id: 'y-axis',
      type: 'linear',
    }],
  }

};


text:
Q: Load data: TypeError: cannot convert the series to  I am currently working on a sentiment analysis project. When I was trying to load data, the errorTypeError: '<=' not supported between instances of 'str' and 'int' appears. So I modified the str to an int. However, now the error TypeError: cannot convert the series to <class 'int'> appears. How can I solve this error?
The data type = dtype('O')
import pandas as pd
#read data
review_df = pd.read_csv( '/Users/mhnwong/Desktop/FYP potential/metropark_trans_demoji.csv')
#create label
review_df["is_bad_review"] = int(review_df["rate"]).apply(lambda x:1 if x <= 8 else 0)
# select only relevant columns
review_df = review_df[["review","is_bad_review"]]

review_df.head()

Data:
This is the data I have got

A: Does your rate column in metropark_trans_demoji.csv file contain something that doesn't belong to numbers?
You should make sure that the content of the rate column can all be converted to int first.
Suppose the rate column's data all belong to int, then you can write
review_df["is_bad_review"] = review_df["rate"].apply(lambda x:1 if int(x) <= 8 else 0)

This converts the content of the rate column to int, then compares it with 8.
The type of review_df["rate"] is <class 'pandas.core.series.Series'>. It cannot be converted to int directly.


text:
Q: Updating constraints after rotating a UIView I have a rectangular UIView whose edges are constrained to its superview. I need to rotate this view by 90 degrees, but then update its constraints so it stays correctly constrained to the superview. If I do
self.overlayView.transform = CGAffineTransformMakeRotation(M_PI * 0.5);

The view rotates, but the width and height stay fixed the wrong way round. Do I need to break the constraints and set them again so that the top is constrained to the superview's left, the left is constrained to the superview's bottom and so on?

A: Autolayout plays with the frame to do its thing. As per the docs, the frame is undefined when the transform is set to something other than the identity.
Based on this, it would appear that this is fixed in iOS8 (and indeed they reference the above docs, noting that as of iOS8 setFrame method gets called on the transformed view).


text:
Q: Cartesian coordinates of the points on the plane in the same order as the Ulam Spiral
I'm messing around with doing a visualization that has nothing to do with the primes and in order to execute it correctly I need an ordered list of all point in the order that the Ulam Spiral crosses them. I've tried some of my work but have only run in to abundantly complicated paths to solution. Also is there a name for looking for pattern that generally occur in spiral, whether they are related to primes or not?

E.g.: Starting with this image:

if $1$ is at the origin, then the list would be as follows: $$(0,0),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1),(2,-1),(2,0),...$$

A: You are lucky because it seems that a very similar pair of sequences is already at OEIS.
The $x$-coordinates are sequence A174344 ("List of $x$-coordinates of point moving in clockwise spiral") and $y$-coordinates ("List of $y$-coordinates of point moving in clockwise spiral") are sequence A268038.
List of $x$-coordinates of point moving in clockwise spiral.

$$0, 1, 1, 0, -1, -1, -1, 0, 1, 2, 2, 2, 2, 1, 0, -1, -2, -2, -2, -2, -2, -1, 0, 1, 2, 3, 3, 3, 3, 3, 3, 2, 1, 0, -1, -2, -3, -3, -3, -3, -3, -3, -3, -2, -1, 0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, -1, -2, -3, -4, -4, -4, -4, -4, -4, -4, -4, -4, -3, -2, \cdots$$

List of $y$-coordinates of point moving in clockwise spiral.

$$0, 0, -1, -1, -1, 0, 1, 1, 1, 1, 0, -1, -2, -2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2, 2, 2, 1, 0, -1, -2, -3, -3, -3, -3, -3, -3, -3, -2, -1, 0, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, -1, -2, -3, -4, -4, -4, -4, -4, -4, -4, -4, -4, -3, -2, -1, 0, 1, 2, 3, 4, 4, 4, \cdots$$

In the referred OEIS pages there are formulas to calculate each sequence of coordinates.

A: A piecewise, explicit function is provided by the accepted answer of a similar question.


text:
Q: SpeechRecognition not listening on Chromium I'm trying to build a Javascript bot by using Puppeteer to open a https URL where I can listen for the microphone and output a transcript from the SpeechRecogniton API built in a browser, the below code seems to log something in normal Chrome, but on Chromium I get nothing despite this feature apparently being supported according to Modernizr. I've allowed microphone permissions but I get a dead console.log
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition

const recognition = new SpeechRecognition()
recognition.interimResults = true

recognition.addEventListener('result', e => {
  const transcript = Array.from(e.results)
    .map(result => result[0])
    .map(result => result.transcript)
    .join('')

    // I get nothing logged here in Chromium
    console.log(transcript)
})

recognition.addEventListener('end', recognition.start)

recognition.start()

UPDATE
After adding the following...
recognition.addEventListener('error', function(event) {
  console.log('Speech recognition error detected: ' + event.error);
});

I'm getting a Network error... and don't know what to do about this in Chromium?

A: Chromium no longer supports SpeechRecognition. I believe it's got something to do with Google wanting people to use their cloud services instead.


text:
Q: Simular proceso en indicador de aplicación con Python El título es un poco ambiguo. Estoy haciendo un indicador para Ubuntu (app indicator). Para el que no lo sepa, el Indicador vendría a ser la aplicación que sale en el margen de la pantalla con un pequeño icono, como el Wi-Fi o la batería.
Ocurre que tengo diseñado un Indicador con dos botones: "Contar" y "Parar de contar". Pretendo hacer que el primer botón haga lo siguiente:
from gi.repository import Notify as Notify
i = 0

def contar(_):
    Notify.Notification.new("Contar", i)
    i+=1

Quiero que "contar" se ejecute en bucle hasta que el usuario pulse el botón de "Parar de contar".
He probado con un bool y repitiendo "contar" en un while, pero no hay forma de pararlo. Algo me dice que voy muy mal encaminado.
Acepto todo tipo de sugerencias, gracias.
Ampliación del problema: Creo que no me he explicado debidamente. La idea es iniciar con uno de los dos botones un recorrido que funciona con un bucle, repitiéndose hasta que se pulsa el otro botón.
Por ejemplo; vamos a suponer que quiero hacer un botón que, tras pulsarlo, comience a bajar en "1" la retroiluminación de mi portátil. Transcurrido un periodo de tiempo, empezaría a perder iluminación, a menos que yo presione un botón "Stop" que detendrá el proceso justo donde está. Sin que éste siga bajando la retroiluminación.
He probado a hacer algo como esto:
cycle_loop = None

[...]

def button1(_):
    cycle_loop = True
    while cycle_loop == True:
        doSomething()
        time.sleep(60)

def button2(_):
    cycle_loop = False

Aunque, como es evidente, el bucle infinito impide la ejecución de button2. Cualquier idea será bien recibida.
Un saludo.

A: Pues lo que se me ocurre es que uses multiprocesos, lo puedes conseguir mediante multiprocessing.
Por ejemplo, considera estas dos funciones, una para iniciar y otra para detener:
import time
from multiprocessing import Event, Process

proceso = None

def cycle():
    while True:
        print 'Haciendo algo...'
        time.sleep(2)

def button1():
    print '[Iniciado]'
    global proceso
    proceso = Process(target=cycle)
    proceso.start()

def button2():
    proceso.terminate()
    print '[Detenido]'

if __name__ == '__main__':
    button1()
    time.sleep(6)
    button2()

El resultado de lo anterior sería:
[Iniciado]
Haciendo algo...
Haciendo algo...
Haciendo algo...
[Detenido]

Estoy usando una variable global llamada proceso para poder usarla dentro de los botones. El button1 llama a la función cycle paralelamente al hilo principal de ejecución, luego, mediante button2 se detiene.
Usando una clase:
import time
from multiprocessing import Process

def cycle():
    while True:
        print 'Haciendo algo...'
        time.sleep(2)

class Clase:
    def __init__(self, func):
        self.proceso = Process(target=func)

    def iniciar(self):
        print '[Iniciado]'
        self.proceso.start()

    def detener(self):
        print '[Detenido]'
        self.proceso.terminate()

if __name__ == '__main__':
    instancia = Clase(cycle)
    instancia.iniciar()
    time.sleep(6)
    instancia.detener()

Actualización
Usando notificaciones:
import time
from multiprocessing import Process
from gi.repository import Notify

contador = 0

def cycle(contador):
    while True:
        notification = Notify.Notification.new(
            "Contar",
            str(contador),
            'dialog-information'
        )
        notification.show()
        time.sleep(2)
        contador += 1

class Clase:
    def __init__(self, func):
        self.proceso = Process(target=func, args=(contador,))

    def iniciar(self):
        Notify.init('Test')
        print '[Iniciado]'
        self.proceso.start()

    def detener(self):
        Notify.uninit()
        print '[Detenido]'
        self.proceso.terminate()

if __name__ == '__main__':
    instancia = Clase(cycle)
    instancia.iniciar()
    time.sleep(6)
    instancia.detener()


text:
Q: Python Zeep - SHA-1 not allowed by policy I'm trying to fetch data from the government API using Python 3 and Zeep:
import zeep
import requests
import datetime
from zeep.wsse import utils
from zeep.wsse.signature import BinarySignature

requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL'

class BinarySignatureTimestamp(BinarySignature):
    def apply(self, envelope, headers):
        security = utils.get_security_header(envelope)

        created = datetime.datetime.utcnow()
        expired = created + datetime.timedelta(seconds=1 * 60)

        timestamp = utils.WSU('Timestamp')
        timestamp.append(utils.WSU('Created', created.replace(microsecond=0).isoformat()+'Z'))
        timestamp.append(utils.WSU('Expires', expired.replace(microsecond=0).isoformat()+'Z'))

        security.append(timestamp)

        super().apply(envelope, headers)
        return envelope, headers

    def verify(self, envelope):
        return envelope

client = zeep.Client('https://ws-int.epuap.gov.pl/sr_external_ws/services/SlownikiReferencyjne/wsdl/SlownikiReferencyjne.wsdl',
wsse=BinarySignatureTimestamp('test.key', 'test.pem'))

data = client.service.dajPozycjeSlownika(Limit=1,Offset=0)

I'm running the above code on Fedora 36 64-bit with Python 3.10.5,  Zeep 4.1.0 and requests 2.27.1.
This line:
data = client.service.dajPozycjeSlownika(Limit=1,Offset=0)

gives the following exception:

zeep.exceptions.Fault: Signature algorithm http://www.w3.org/2000/09/xmldsig#rsa-sha1 not allowed by policy (from client)

When I run curl -v -I https://ws-int.epuap.gov.pl I get:

curl: (35) error:0A00018A:SSL routines:dh key too small

Is there any solution for the Zeep's SHA-1 exception?


text:
Q: Pause new threads from executing using ExectuorService I would like to pause the new tasks from executing. The example provided in the Official Documentation seems to be stopping the currently executed tasks as well (though I am wondering how it does that without interrupting the thread).
class PausableThreadPoolExecutor extends ThreadPoolExecutor {
   private boolean isPaused;
   private ReentrantLock pauseLock = new ReentrantLock();
   private Condition unpaused = pauseLock.newCondition();

   public PausableThreadPoolExecutor(...) { super(...); }

   protected void beforeExecute(Thread t, Runnable r) {
     super.beforeExecute(t, r);
     pauseLock.lock();
     try {
       while (isPaused) unpaused.await();
     } catch (InterruptedException ie) {
       t.interrupt();
     } finally {
       pauseLock.unlock();
     }
   }

   public void pause() {
     pauseLock.lock();
     try {
       isPaused = true;
     } finally {
       pauseLock.unlock();
     }
   }

   public void resume() {
     pauseLock.lock();
     try {
       isPaused = false;
       unpaused.signalAll();
     } finally {
       pauseLock.unlock();
     }
   }
 }

A: Wrapping the Runnable interface could be easier for this, then you don't have to make your own ThreadPool.
public abstract class PausableRunnable implements Runnable{
     private final object _monitor;
     public PausableRunnable(object monitor){
         _monitor = monitor;
     }
     @Override
     public void Run(){
         WaitForNotify();
     }

     public void WaitForNotify(){
         synchronized(_monitor){
             while(!done){
                 _monitor.wait();
             }
         }
         doWork();
     }
     public abstract void doWork();
}

This could pause new threads easily.  Pausing a running thread is a different task, I think this is what you meant.  The biggest problem with my solution is if you already want to inherit from something, but it's a starting point

A: The question was incorrect. The PausablableThreadPoolExecutor does not stop the currently executed thread. Apologies for the incorrect question.


text:
Q: Make .minecraft file read from a usb How can I make Minecraft look into a USB for the .Minecraft file? I can do a bit of coding so just tell me if I have to make a program just tell me what I need to make it do.

A: I would not recommend storing it on a USB and playing the game from there. I would recommend transferring worlds when you need to switch computers (I'm sure you can write a script to transfer files from the USB onto the computer or the other way around). However, if you must, i would recommend looking in the Minecraft launcher settings. I am fairly certain you can change the source destination folder in there (along with allocated memory to the game and other semi-useful tweaks).
This guide may be helpful:
https://www.pcsteps.com/1346-create-portable-minecraft-usb-stick/


text:
Q: Static linking ActiveMQ-cpp I am creating a c++ project where I want it to run in standalone mode without any dependencies since it will be deployed on multiple servers.
This is my CMakeLists file :
project(CMS-test)
cmake_minimum_required(VERSION 2.6)

add_executable(main main.cpp)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

INCLUDE_DIRECTORIES(/usr/local/apr/include/apr-1)
INCLUDE_DIRECTORIES(/usr/local/include/activemq-cpp-3.9.4)

target_link_libraries(main ${CMAKE_SOURCE_DIR}/libapr-1.a)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libactivemq-cpp.a)

libactivemq-cpp.a and libapr-1.a are found in my project directory

but the error I'm getting after make main during linking is
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/DecafRuntime.cpp:72: undefined reference to `apr_initialize'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/DecafRuntime.cpp:73: undefined reference to `apr_pool_create_ex'
libactivemq-cpp.a(libactivemq_cpp_la-DecafRuntime.o): In function `decaf::lang::Runtime::shutdownRuntime()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/DecafRuntime.cpp:109: undefined reference to `apr_pool_destroy'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/DecafRuntime.cpp:110: undefined reference to `apr_terminate'
libactivemq-cpp.a(libactivemq_cpp_la-Network.o): In function `decaf::internal::net::Network::initializeNetworking()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/Network.cpp:116: undefined reference to `apr_signal_block'
libactivemq-cpp.a(libactivemq_cpp_la-SecureRandomImpl.o): In function `decaf::internal::security::SecureRandomImpl::providerNextBytes(unsigned char*, int)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/security/unix/SecureRandomImpl.cpp:128: undefined reference to `apr_file_read_full'
libactivemq-cpp.a(libactivemq_cpp_la-SecureRandomImpl.o): In function `decaf::internal::security::SecureRandomImpl::SecureRandomImpl()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/security/unix/SecureRandomImpl.cpp:76: undefined reference to `apr_file_open'
libactivemq-cpp.a(libactivemq_cpp_la-Exception.o): In function `decaf::lang::Exception::buildMessage(char const*, __va_list_tag (&) [1])':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/lang/Exception.cpp:124: undefined reference to `apr_pvsprintf'
libactivemq-cpp.a(libactivemq_cpp_la-System.o): In function `decaf::lang::System::unsetenv(std::string const&)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/lang/System.cpp:276: undefined reference to `apr_env_delete'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/lang/System.cpp:286: undefined reference to `apr_strerror'
libactivemq-cpp.a(libactivemq_cpp_la-System.o): In function `decaf::lang::System::getenv(std::string const&)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/lang/System.cpp:297: undefined reference to `apr_env_get'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/lang/System.cpp:306: undefined reference to `apr_strerror'
libactivemq-cpp.a(libactivemq_cpp_la-System.o): In function `decaf::lang::System::setenv(std::string const&, std::string const&)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/lang/System.cpp:326: undefined reference to `apr_env_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/lang/System.cpp:336: undefined reference to `apr_strerror'
libactivemq-cpp.a(libactivemq_cpp_la-InetAddress.o): In function `decaf::net::InetAddress::getLocalHost()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/net/InetAddress.cpp:158: undefined reference to `apr_gethostname'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/net/InetAddress.cpp:168: undefined reference to `apr_sockaddr_info_get'
libactivemq-cpp.a(libactivemq_cpp_la-AprPool.o): In function `decaf::internal::AprPool::destroyPool()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/AprPool.cpp:50: undefined reference to `apr_pool_destroy'
libactivemq-cpp.a(libactivemq_cpp_la-AprPool.o): In function `decaf::internal::AprPool::allocatePool() const':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/AprPool.cpp:42: undefined reference to `apr_pool_create_unmanaged_ex'
libactivemq-cpp.a(libactivemq_cpp_la-AprPool.o): In function `decaf::internal::AprPool::cleanup()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/AprPool.cpp:60: undefined reference to `apr_pool_clear'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::connect(std::string const&, int, int)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:312: undefined reference to `apr_sockaddr_info_get'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:318: undefined reference to `apr_socket_opt_get'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:319: undefined reference to `apr_socket_timeout_get'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:322: undefined reference to `apr_socket_opt_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:328: undefined reference to `apr_socket_timeout_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:332: undefined reference to `apr_socket_connect'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:335: undefined reference to `apr_socket_opt_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:336: undefined reference to `apr_socket_timeout_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:326: undefined reference to `apr_socket_timeout_set'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::available()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:417: undefined reference to `apr_os_sock_get'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::getLocalAddress() const':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:376: undefined reference to `apr_socket_addr_get'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:378: undefined reference to `apr_sockaddr_ip_getbuf'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::getOption(int) const':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:571: undefined reference to `apr_socket_opt_get'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:541: undefined reference to `apr_socket_timeout_get'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:545: undefined reference to `apr_socket_opt_get'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::setOption(int, int)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:621: undefined reference to `apr_socket_opt_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:591: undefined reference to `apr_socket_opt_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:593: undefined reference to `apr_socket_timeout_set'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:603: undefined reference to `apr_socket_opt_set'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::read(unsigned char*, int, int, int)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:675: undefined reference to `apr_socket_recv'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::write(unsigned char const*, int, int, int)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:745: undefined reference to `apr_socket_send'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::create()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:157: undefined reference to `apr_socket_create'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/tcp/TcpSocket.cpp:161: undefined reference to `apr_os_sock_get'
libactivemq-cpp.a(libactivemq_cpp_la-TcpSocket.o): In function `decaf::internal::net::tcp::TcpSocket::accept(decaf::net::SocketImpl*)':

/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/net/SocketError.cpp:42: undefined reference to `apr_strerror'
libactivemq-cpp.a(libactivemq_cpp_la-Date.o): In function `decaf::util::Date::toString() const':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/util/Date.cpp:112: undefined reference to `apr_time_exp_lt'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/util/Date.cpp:117: undefined reference to `apr_strftime'
libactivemq-cpp.a(libactivemq_cpp_la-OpenSSLContextSpi.o): In function `decaf::internal::net::ssl::openssl::OpenSSLContextSpi::providerInit(decaf::security::SecureRandom*)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:188: undefined reference to `SSL_load_error_strings'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:189: undefined reference to `SSL_library_init'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:190: undefined reference to `OPENSSL_add_all_algorithms_noconf'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:226: undefined reference to `SSL_CTX_use_PrivateKey_file'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:245: undefined reference to `SSL_CTX_load_verify_locations'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:253: undefined reference to `RAND_seed'
libactivemq-cpp.a(libactivemq_cpp_la-OpenSSLContextSpi.o): In function `decaf::internal::net::ssl::openssl::OpenSSLContextSpi::~OpenSSLContextSpi()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:162: undefined reference to `CRYPTO_set_locking_callback'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:163: undefined reference to `EVP_cleanup'
libactivemq-cpp.a(libactivemq_cpp_la-OpenSSLContextSpi.o): In function `~ContextData':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLContextSpi.cpp:110: undefined reference to `SSL_CTX_free'
libactivemq-cpp.a(libactivemq_cpp_la-OpenSSLSocketException.o): In function `decaf::internal::net::ssl::openssl::OpenSSLSocketException::getErrorString() const':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocketException.cpp:102: undefined reference to `ERR_get_error'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocketException.cpp:104: undefined reference to `ERR_error_string_n'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocketException.cpp:102: undefined reference to `ERR_get_error'
libactivemq-cpp.a(libactivemq_cpp_la-OpenSSLParameters.o): In function `decaf::internal::net::ssl::openssl::OpenSSLParameters::OpenSSLParameters(ssl_ctx_st*)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:573: undefined reference to `SSL_write'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:575: undefined reference to `SSL_get_error'
libactivemq-cpp.a(libactivemq_cpp_la-OpenSSLSocket.o): In function `decaf::internal::net::ssl::openssl::OpenSSLSocket::available()':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:641: undefined reference to `X509_free'
libactivemq-cpp.a(libactivemq_cpp_la-OpenSSLSocket.o): In function `decaf::internal::net::ssl::openssl::OpenSSLSocket::verifyServerCert(std::string const&)':
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:686: undefined reference to `X509_get_subject_name'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:692: undefined reference to `X509_NAME_get_index_by_NID'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:367: undefined reference to `SSL_ctrl'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:370: undefined reference to `SSL_connect'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:376: undefined reference to `SSL_get_error'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:406: undefined reference to `SSL_set_verify'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:408: undefined reference to `SSL_accept'
/home/isammour/Desktop/smart/activemq-cpp-library-3.9.4/src/main/decaf/internal/net/ssl/openssl/OpenSSLSocket.cpp:361: undefined reference to `SSL_set_verify'

and more..
I don't know what to do to fix these errors
Any advice ?

A: I assume apr is a dependency of activemq. If this is the case, you need to switch the link order of apr and activemq.
The linker will only use each library once. And when it processes libactivemq-cpp.a it sees that it depends on apr, but libapr-1.a has already been processed.

A: Figured out that I was doing  the target_link_libraries in the wrong order and as pointed by Finn I changed the order of the libraries
The full working CMakeLists file now is
project(CMS-test C CXX)
cmake_minimum_required(VERSION 2.6)

add_executable(main main.cpp)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

INCLUDE_DIRECTORIES(/usr/local/apr/include/apr-1)
INCLUDE_DIRECTORIES(/usr/local/include/activemq-cpp-3.9.4)
INCLUDE_DIRECTORIES(/usr/lib/x86_64-linux-gnu/)
find_package (Threads)
target_link_libraries(main ${CMAKE_THREAD_LIBS_INIT})

target_link_libraries(main ${CMAKE_SOURCE_DIR}/libactivemq-cpp.a)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libapr-1.a)
target_link_libraries(main ssl)
target_link_libraries(main crypto)
target_link_libraries(main dl)


text:
Q: How to make max-heap stable with counter and account for counter overflow? Generally I need size-efficient data structure similar to std::priority_queue but stable (preserving order of insertion).
By adding just 4 bytes to the object I could have 1 byte serving as priority and 3 bytes as counter to keep the order of insertion. Closest competitor - std::forward_list - would add an overhead of 5 bytes (in practice 8 due to alignment) - one for priority and 4 for link (32-bit architecture). It would also be slower than max-heap due to traversal when adding new element.
The problem with counter is the behavior of container when the counter overflows. In Boost the counter is 64-bits long and when it overflows, the container throws an exception ( http://www.boost.org/doc/libs/1_49_0/doc/html/heap/concepts.html#heap.concepts.stability ).
One solution to this problem that comes to mind is resetting the counter whenever the queue gets empty, but this is only a partial solution to the problem.
Is there a generic (and optimal - without traversing through the whole heap each time) way this could be solved? I planned to use std::push_heap() and std::pop_heap() from <algorithm> with an array of raw storage, so I have access to "internals" of the entries. If possible, I'd prefer to stick to these standard functions instead of implementing my own heap (or any other data structure) that would be stable.
EDIT:
As requested in a comment, I'm adding some more information about my use case here.
I need this data structure to implement a message queue in the RTOS I'm developing ( https://github.com/DISTORTEC/distortos ). This message queue must follow all POSIX requirements, and one of them is "stability" - new entries with the same priority must be placed AFTER older entries:
From http://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html# :

A message shall be inserted after other messages in the queue, if any, with equal msg_prio.

This is an RTOS for embedded microcontrollers, so I cannot give any specific usage scenario, because there will be many. Some devices will run for a second and shutdown, other devices may run for years without reboot. As I'm aiming for a design with no limitations, I'm mostly interested in a solution that works in all cases, without limits like the one imposed by simple counter - which fails when the counter overflows.
Because of the fact that this is for a microcontroller, I'd really prefer the solution to be size efficient, so solutions like "use 128-bit counter" are not acceptable.
Generally I see two options - using singly-linked list or using max-heap (as I originally intended).
Using singly-linked list would add 5 (in practice 8 - due to alignment) bytes to each stored object - 1 for priority, 4 for link. This solution is stable "by design", but insertion of object can be slow when there are many objects in the list - because a lot of nodes will have to be traversed to find the spot for insertion.
Using heap I could try to limit the overhead to 4 bytes - 1 for priority, 3 for counter. This option could possibly be faster than the list, but requires a solution for counter overflow. I see several options here (multiple can be used at the same time):

*

*use 56-bit counter (total overhead would be 8 bytes per object),

*reset the counter when the list gets empty (only partial solution),

*when the overflow happens, counter has to be reset, whole heap has to be traversed and each visited entry's counter has to be updated to "low" value.

Of course I know I could just ignore the overflow, but if there is a real solution, I'd like to implement it.
As there seems to be no simple, robust and deterministic solution to the counter overflow problem, I'm starting to lean towards the use of  - I would expect that there wouldn't be many entries in the message queue (most microcontrollers have really limited RAM), so the speed benefit of using heap would probably be negligible. Especially when I'd account for all these copying during insertion/deletion, while the contents of the singly-linked list would be mostly static in this regard. And there's also "instantaneous" extraction from the head of the list...

A: I don't think there's any good way to fix your overflow problem with the constraints given.
Renumbering your heap periodically means a stop-the-world housekeeping operation, which I reckon needs O(n log n) time without extra allocation, or perhaps O(n) time with O(n) temporary space.
Note that if O(n log n) stop-the-world operations aren't acceptable - you did say it's an RTOS - then you need to make sure there's always room to allocate the temporary working space. If you're reserving that anyway, you could equally spend twice as much space overhead per object on a structure that doesn't need stop-the-world housekeeping operations in the first place.

The simplest solution I can think of is to amortize that overhead over multiple objects, rather than adding a pointer to each instance. So, let's split it into two issues:

*

*FIFO-ordering of elements with the same priority
You can just use a FIFO-ordered container with constant-time pop_front and push_back: this is a deque.
You could try std::deque, and write a custom implementation if you need finer control over the block size, for example. The per-block overhead is amortized over all the objects in that block, so you can control the tradeoff between slack allocation and per-object overhead.

*key-ordered container of priority levels:

*

*Since 8 bits are enough to store your priority, an array of 256 levels (deques) would be the simplest solution.

*If that wastes too much slack space for you, a regular priority queue will still work, but pop_front/pop_heap should pop from the front priority level object, and only pop that level from the overall queue when it is empty.
Note that you can write this logic as a thin wrapper around the existing pop_heap to re-use its heap logic, but the same isn't true of push_heap, and in fact that will end up slower in this scheme (you'll have to search for the insertion point to see if it exists, and then sift it up if it doesn't).
This should have notionally constant-time everything, so is asymptotically better than a heap; whether it's fast enough in practice will depend on the platform, cache behaviour, and how well you can tune the allocators, block sizes, etc.
Space overhead is a few bytes (something like 2-4 pointers) per distinct priority level, plus hopefully 1 byte or fewer per element (depending on the deque block size and number of elements per block). So, this will only save space if you have a sufficiently large number of elements per priority level. However, it can never encounter your overflow problem, doesn't require any stop-the-world cleanup, and doesn't degrade significantly with time or size.


text:
Q: Asterisk broadcast mechanism I want to ask how the mechanism when broadcast communication occurs (many endpoints) where each endpoint enters the bridge through the ARI originate (outgoing call) function.
Suppose there are 3 participants in a communication bridge. When one endpoint is talking, how does the mechanism occur? Does the endpoint make 2 packets with the same payload, then sent separately by the endpoint or only send one packet, then the asterisk duplicates the packet as much as n endpoint then sends it to each endpoint registered on the bridge?
Thank you

A: You can check app_conference.c code if you want.
Asterisk make independend packet for each party. How that packet created will depend on confbridge settings.
There is experimental res_rtp_multicast.c, but it not used in most scenarios.


text:
Q: python np.round() with decimal option larger than 2 Python has default round() function, but I was programming with cython and want to replace pythonic code with numpy function. However, I got the following results when experimenting it in terminal.
>>> np.around(1.23456789)
1.0
>>> np.around(1.23456789, decimals=0)
1.0
>>> np.around(1.23456789, decimals=1)
1.2
>>> np.around(1.23456789, decimals=2)
1.23
>>> np.around(1.23456789, decimals=3)
1.2350000000000001
>>> np.around(1.23456789, decimals=4)
1.2345999999999999

Which is kind of strange, and I still want the following "desired" result:
>>> round(1.23456789,3)
1.235
>>> round(1.23456789,4)
1.2346

A: The problem is that the binary representation of floating point numbers can't exactly represent most decimal numbers. For example, the two closest values to 1.235 are:

*

*1.2350000000000000976996261670137755572795867919921875

*1.234999999999999875655021241982467472553253173828125

Since the first one is closer to the desired value, it's the one you get.
When you let the Python environment display a floating-point number, it uses the __repr__ conversion function which shows enough digits to unambiguously identify the number. If you use the __str__ conversion instead, it should round the number to a reasonable number of digits. At least that's what the built-in float type does, I assume numpy works the same way. The print function calls __str__ by default, so try this:
print np.around(1.23456789, decimals=3)

For applications where you absolutely need decimal accuracy there is the decimal module. It can do rounding as well.


text:
Q: SQL: SELECT the inverse of a query I have this query and I'd like to select the inverse of this query (the ones which are not concerned.
SELECT*
FROM input1
LEFT OUTER JOIN (
    SELECT MAX(Ref) AS Ref, Nomlatin, Lieudit, Commune
    FROM input1
    GROUP BY Nomlatin, Lieudit, Commune
) as t1
ON input1.Ref = t1.Ref
WHERE t1.Ref IS NULL

I have already searched for answers to this question but I didn't succeed to use the NOT IN.
If someone can help me, it would be great.
Thanks

A: Well, you have your WHERE clause at the end that filters everything in the final result set that IS NULL.
The "inverse" or opposite of that would be returned if you would replace IS NULL with IS NOT NULL.
SELECT*
FROM input1
LEFT OUTER JOIN (
    SELECT MAX(Ref) AS Ref, Nomlatin, Lieudit, Commune
    FROM input1
    GROUP BY Nomlatin, Lieudit, Commune
) as t1
ON input1.Ref = t1.Ref
WHERE t1.Ref IS NOT NULL -- minor change here

A: I would do it with correlated subquery :
SELECT i.*
FROM input1 i
WHERE Ref = (SELECT MAX(i1.Ref)
             FROM input1 i1
             WHERE i1.Nomlatin = i.Nomlatin AND i1.Lieudit = i.Lieudit, i1.Commune = i.Commune
            );


text:
Q: Using SVN, how can I compare a tag/path against non-versioned files? Let's say I have a set of source files on disk, and the same application in SVN. I'd like to compare these files with a particular repository path, for example to see if the files on disk actually are the same as a particular tag.
svn diff doesn't work in this case because the files on disk aren't a working copy.
Obviously I could check out or export the tag I'm interested in to a temporary location and then diff, but I'm hoping to find an option that doesn't involve a whole second copy of the files living on disk.
(My overall goal for this is to audit for changes on live web app files that haven't made it to source control)

A: You realllly raellly should consider using rsync --dry-run -acp devbox:/workingCopy server:/liveCopy for the comparison. That's how I do audits across the huge clusters I maintain...

A: For repo-objects you can|have to use svn cat URL, which output target's content (and fix broken workflow after it)


text:
Q: How do I render an object in react native? Working on pulling data from an external API (FlightStats).
Currently the data fetch is working as it finds the childs of the parent request. Now stuck rendering through an array problem.

*

*Tried multiple options for the request and data source options

Request from API:

componentDidMount() {
    fetch('https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2019/3/24?appId=XXXXX&appKey=+XXXXX')
    .then((response) => response.json())
    .then((response) => {
      this.setState({
        request: response.request
      })
    })
    .catch((error) => {
        console.log(error)
        });
    }

Constructor:

    constructor() {
        super();
        this.state = {
            request: 'carrier'
        }
    }

Render:

      <View style={Global.container}>
        <Text>{this.state.request.carrier}</Text>
          {/* //={[{ key: 'a'}, { key: 'b'}]}
          //renderItem={({item }) => <Text>{item.key}</Text>} */}
      </View>

Data result in Json

{"request":{"carrier":{"requestedCode":"AA","fsCode":"AA"},"codeType":{},"flightNumber":{"requested":"100","interpreted":"100"},"departing":true,"date":{"year":"2019","month":"3","day":"24","interpreted":"2019-03-24"},"url":"https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2019/3/24"},"scheduledFlights":[{"carrierFsCode":"AA","flightNumber":"100","departureAirportFsCode":"JFK","arrivalAirportFsCode":"LHR","stops":0,"departureTerminal":"8","arrivalTerminal":"3","departureTime":"2019-03-24T19:40:00.000","arrivalTime":"2019-03-25T06:50:00.000","flightEquipmentIataCode":"77W","isCodeshare":false,"isWetlease":false,"serviceType":"J","serviceClasses":["R","F","J","Y"],"trafficRestrictions":[],"codeshares":[{"carrierFsCode":"AY","flightNumber":"4012","serviceType":"J","serviceClasses":["F","J","Y"],"trafficRestrictions":[],"referenceCode":1139031},{"carrierFsCode":"BA","flightNumber":"1511","serviceType":"J","serviceClasses":["R","F","J","Y"],"trafficRestrictions":[],"referenceCode":1250367},{"carrierFsCode":"GF","flightNumber":"6654","serviceType":"J","serviceClasses":["J","Y"],"trafficRestrictions":["Q"],"referenceCode":2204628},{"carrierFsCode":"IB","flightNumber":"4218","serviceType":"J","serviceClasses":["R","F","J","Y"],"trafficRestrictions":[],"referenceCode":2305895},{"carrierFsCode":"LY","flightNumber":"8051","serviceType":"J","serviceClasses":["F","J","Y"],"trafficRestrictions":["Q"],"referenceCode":2942513}],"referenceCode":"807-470028--"}],"appendix":{"airlines":[{"fs":"AA","iata":"AA","icao":"AAL","name":"American Airlines","phoneNumber":"08457-567-567","active":true},{"fs":"LY","iata":"LY","icao":"ELY","name":"El Al","phoneNumber":"+ 972-3-9771111","active":true},{"fs":"AY","iata":"AY","icao":"FIN","name":"Finnair","phoneNumber":"+ 358 600 140 140","active":true},{"fs":"IB","iata":"IB","icao":"IBE","name":"Iberia","phoneNumber":"1800 772 4642","active":true},{"fs":"BA","iata":"BA","icao":"BAW","name":"British Airways","phoneNumber":"1-800-AIRWAYS","active":true},{"fs":"GF","iata":"GF","icao":"GFA","name":"Gulf Air","phoneNumber":"973 17 335 777","active":true}],"airports":[{"fs":"JFK","iata":"JFK","icao":"KJFK","faa":"JFK","name":"John F. Kennedy International Airport","street1":"JFK Airport","city":"New York","cityCode":"NYC","stateCode":"NY","postalCode":"11430","countryCode":"US","countryName":"United States","regionName":"North America","timeZoneRegionName":"America/New_York","weatherZone":"NYZ178","localTime":"2019-03-24T00:55:59.327","utcOffsetHours":-4.0,"latitude":40.642335,"longitude":-73.78817,"elevationFeet":13,"classification":1,"active":true},{"fs":"LHR","iata":"LHR","icao":"EGLL","name":"London Heathrow Airport","city":"London","cityCode":"LON","stateCode":"EN","countryCode":"GB","countryName":"United Kingdom","regionName":"Europe","timeZoneRegionName":"Europe/London","localTime":"2019-03-24T04:55:59.327","utcOffsetHours":0.0,"latitude":51.469603,"longitude":-0.453566,"elevationFeet":80,"classification":1,"active":true}],"equipments":[{"iata":"77W","name":"Boeing 777-300ER","turboProp":false,"jet":true,"widebody":true,"regional":false}]}}

Error Message:
Invariant Violation: Objects are not valid as a React child (found: object with keys {resquestedCode, fsCode}). If you meant to render a collection of childen, use an array instead.
So this is where I am stuck. The initial fetching is working and finding the sub children. For some reason not sure why I cannot render the items or just display the results from the json.
Any help or tutorials will do.
Thanks again

A: carrier is an object in your JSON data and hence you cannot print it directly. If you want to print it as a string, please do this.
<Text>{JSON.stringify(this.state.request.carrier)}</Text>

If you want it to look neat, you can format it like this.
<Text>{JSON.stringify(this.state.request.carrier, 0, 4)}</Text>


text:
Q: Cannot append value to string C# I've got two methods in my Windows Forms application for parsing some gzip encoded strings.
Here are my two methods, which both return the same value.
public static async Task<string> DecodeGzipAsync(string str)
{
    var values = new Dictionary<string, string>
    {
        { "data", str }
    };

    var content = new FormUrlEncodedContent(values);

    var client = new HttpClient();

    var response = await client.PostAsync("http://www.txtwizard.net/compression/decompress/gz", content);

    var json = await response.Content.ReadAsStringAsync();

    var result = JsonConvert.DeserializeObject<GzipData>(json);

    return result.DecompressedData;
}

public static string DecodeGzip(string str)
{
    byte[] gzBuffer = Convert.FromBase64String(str);

    using (MemoryStream ms = new MemoryStream())
    {
        int msgLength = BitConverter.ToInt32(gzBuffer, 0);
        ms.Write(gzBuffer, 0, gzBuffer.Length);

        byte[] buffer = new byte[msgLength];

        ms.Position = 0;

        using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
        {
            zip.Read(buffer, 0, buffer.Length);
        }

        return Encoding.UTF8.GetString(buffer);

    }

And then I call these two methods from my main form.
var string1 = await Utilities.DecodeGzipAsync(xml.InnerText);
var string1Concat = string.Concat("<Connotes>", string1, "</Connotes>");

var string2 = Utilities.DecodeGzip(xml.InnerText);
var string2Concat = string.Concat("<Connotes>", string2, "</Connotes>");

Where xml.InnerText is
H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Ih6fVMtl1ebp6bIt2uvPPto/ffnR0ePff7qu63w5vT763R7fdX88zqbTZXW0e3Bv5/7ju/LH48m6batl07RZmx/tuOfx3eCbx9Osrou8LmZH+w92H991f5pvltkiPzr58uTbr45fnL5On3/5+WvbjL/jhj+olvnR652H8hX/9Xg6z+qLvK2OXuXTvLjMa/rSfPR4Wi1nQODe7t2d3bt7O7sH9K1+Zr4s84uMxvfg4d7DPfutfog2NM6T4zc7O/sP7+3y90sBDNIt14tJXve+t1+Ydqu6WLb57Oj3sQ3MJ2ixqs/fAQZ/yX/g06a4WC7yZQt0FBwGsLOr3US+f2xn6/irp9TIzt0sK8prIvfu/gFmz/xpPv/9r7LlEc1++DV/+pipUS0vvM7tR49z5hxM6+nLx3ftX4/P67y4mLdlscxneUvgGuKfRXtEL+MH4Tkhfhnv7N6/BzTpj8ezvJkSEV69+fIF9YA/Hs8v6A2abPx8XObLI3SOn4/r/Pxo997BvU/vp2n67Nnju/jg8dWsPdr79PFd/Hx8RS/RfOLH47sxfM7raqEMtYMW+tfjizpbztqqXdRv1ysg+fhu+JFtUTPX+w34k8cXxPWLar1s9Uv7J76plj5g9/fjYgb6nRfTrC2qJbMAkfLgePf42f2dT7f3nz65t71/8OnO9sPT4/vb9/Ye7h9/+vD+wf37T5gdQPa7XRhlNskxVv65rH5/QnD6tqCZsxx7TBTtfmmax1rpl8y+63YKVmgLkk/mjZ29vb2H2rTX4vGyqs4FoVl+nq1LZof+h/o+Yb3IlsV5TtQTzbOz+ylNaPihbUMSQApob3/ftcBH/veQkH4TlptFdZlDltrrVX705Vdvnnz51QsSoODjx1VdXBTLrCTmXGXtdM5axElF9Gvi1Klg+vu8BJfqH/zxbEY907+7R3v30y+Oz16kr0kF8Af4+N7RyVevXh1/8dXz3+uYP77HH+8fvZY/9/nP+0f37x/s8Af3+YNPSfZfv3l1/PxMmn16JP1yb/QLsQrRrqW5PXvz/Pd5wV+az/B9WU2Ptu/tjz/99NOdnU/3R7v3HowfHDy8t3+wx23xPdqxVv59XqbHn/PHoqTpl9X8aOcgPTi4v5/u7ezv8pf02eMmJ8Xqhry7u717L3357bPnz89evqaRvzo9DUf/5tunT1QdbBj8Dki/cfCuY/xmhvrk+fHvdSpf2tHjj3xB2uGIxLLOf0+SomyRTcfTajHO1tJYvuemhlIPd/d39x/uEqUOxvcf7N3f3f9U2jKp8ItYt+M3x18cn8hXQi78xvQ62N/99MED6CH9iL6qL4tpfnT6e798dfr6Nb6QDx632TtWM7vU2vz+mHRPoFPN3/iiaPNFA1mzv+NT1Y/62+N2dW1nJ0ZF+73REqz0V/ls5/emL91nj69Y0+aztwvC8P74wYOH+5/e39k5+HQXmtl9+fiuuh9HX88Puffg059jN2RPvvrhuyHy/bAbYr7/f7Ub8ulmN8R9/UNwQ+6xS7nJDbn3qe+G3Ou6Ifc2uiH3/7/vhhwf3N87PT7e3T7e+/R0e/8J/XP88N6D7b1P7z249/Dek9Pj03vMDl/PDdm7lRvitbrJDbn34EduSNQNeXn86uz1t4ddkZMXr9JnX756ShY5/YXZYnWY/l5nLz5/TeKQvjkld+TkNDDSx189+erVZgu9f/8mCx1zT744fvV7DfomO3sPyNPcYYv7KXnA9z/d6fsmMtL02fGrL8i7Ovn22YvTV79P+ur05fHZq9dxn2X/Ifksn97/kc/yw/ZZWAHfzme5/8E+y2S28/sM+yz3Ph0f7O98+pD+f//+7v1v1GfZZ0/959JnuSdf/fB9FrEOwz6L+f7/zT4LuHeDz+J9/bPvs+wdfLp/g8/yYM/zWR4chD7L3t5Bx2WBmnaZkxt8llvhuLMHmBtxRLrA+VWfhjju7+123ap9D8dP/7/vVj149uzk3rMH97bvPznY2d7ffXa6/fDB0/3tT/d2H5zuHdzfuX/6bNitGsgYPXx4+umz/Z3tB08/fbi9f/rpyfaTe7un2zv37z97und8vPPw9P4HuGr3buWqea02umrkTbE3/Q25ajdj/+RW2LtWN2B/H/nSbwr7/5c5mtZFfHV28u3jV09fD3uN93Z20lfHZ8+/e/z7pG86LuLLL1+9SV+evTqTjwezWPtfJ4v1+uwLKJSon3hvvPtg54DypOzlUAri4P6nD/p+ohld+sWXb74c8Aw/vbeX7u0/2P+RZ/hD9gzv7cIF63uGexHPELT7QNewmCGrM+AakiSNyW7u7j64d59+7H+jruHug/uf/nz1Dff5+2Hf0Hz//2rfcHezb+i+/tn3DcnSw8Jv8rvu+b4hvLQgn/XwQdpNaGESrOf18P/7ntfDT09OTsg6bJMwk+f1dH9v+8ne8UP688HJ/U+PyWo8+JCE1v6tvCSv1Y1e0jfvZ/y/xc/4sITWk1dffvX5t9+oFxD1Tr795asXTyj18+Xx075n4r2/yTvZ2/sa3gm5Qy9OB72T+wf36NnhFbaH9wayWBa99An5VhtdlPvp3qc7Bz9yUX7ILopo29slrx5+sIdyPoOdHkpePdwf7+7v3Ht48On93Z1Pdwc8lP8Hq6xfMfkjAAA=

The results I get are really frustrating (and weird!)
string1 and string2 both return the same string, however string1Concat and string2Concat return different results.
string1Concat = "<Connotes>" + string1 + "</Connotes>"

string2Concat = "<Connotes>" + string2  // Notice how it is missing the concatenation on the end

What might be causing this behaviour? I have tried changing the encoding to ASCII and UTF8 but both give the same results.
Any help is much appreciated!

A: This was a little tricky, but I found the problem/solution:
You convert the array of the size of the compressed data to a string at Encoding.UTF8.GetString(buffer). This will create a string which a length of 559903 instead of the correct 9209. If you create a new byte-array with the actually read bytes it is working:
public static string DecodeGzip(string str)
{
    byte[] gzBuffer = Convert.FromBase64String(str);

    using (MemoryStream ms = new MemoryStream())
    {
        int msgLength = BitConverter.ToInt32(gzBuffer, 0);
        ms.Write(gzBuffer, 0, gzBuffer.Length);

        byte[] buffer = new byte[msgLength];

        ms.Position = 0;
        int length;
        using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
        {
            length = zip.Read(buffer, 0, buffer.Length);
        }

        var data = new byte[length];
        Array.Copy(buffer, data, length);
        return Encoding.UTF8.GetString(data);
    }
}


text:
Q: My react-navigation fullscreeen modal does not cover the tabs navigation on android I'm currently struggeling with a behavior on react-navigation for react-native. My Navigation has a  bottom tab navigator which has four entries represented as Stacks.
const Tabs = createBottomTabNavigator<AppParamList>();

export const AppTabs: React.FC<AppTabsProps> = () => {
  return (
    <Tabs.Navigator>
      <Tabs.Screen
        name="Store"
        options={{
          title: i18n.t("STORE.STORE"),
          header: () => null,
        }}
        component={StoreStack}
      />
      <Tabs.Screen
        name="Favorites"
        options={{ title: i18n.t("FAVORITES"), header: () => null }}
        component={FavoriteStack}
      />
      <Tabs.Screen
        name="Orders"
        options={{ title: i18n.t("ORDERS"), header: () => null }}
        component={OrdersStack}
      />
      <Tabs.Screen
        name="Account"
        options={{ title: i18n.t("ACCOUNT"), header: () => null }}
        component={AccountStack}
      />
    </Tabs.Navigator>
  );
};

One of those Stacks, the first one, includes a Stack which is represented as a fullscreen modal ( The last one called checkout).
const Stack = createNativeStackNavigator<StoreParamList>();

export const StoreStack: React.FC<StoreStackProps> = () => {
  return (
    <Stack.Navigator initialRouteName="Home">
      <Stack.Screen
        options={{ header: () => null }}
        name="Home"
        component={HomeScreen}
      />
      <Stack.Screen
        options={{ header: () => null }}
        name="Product"
        component={ProductScreen}
      />
      <Stack.Screen
        options={{ header: () => null, presentation: "fullScreenModal" }}
        name="Checkout"
        component={CheckoutStack}
      />
    </Stack.Navigator>
  );
};

Now this does work as intended on ios, where its just opening a fullscreen modal only showing my checkout stack. My problem is, that, since the modal stack is contained within my TabsNavigator, on android it opens the modal while still presenting the TabNavigator on the bottom. Does anyone have a advice on how I can go around this problem?

There is a flag on the tabsNavigator, where you can remove the tabBar
options={{
   tabBarStyle: { display: "none" },
}}

, however that is only on the upper level and is not available within my Tabs.Screens. I was thinking of moving up the modal to that level, but then it displays a fifth entry in my tabsBar and also complicates the navigation with Typescript.


text:
Q: Shortest Path between capitals passing through other capitals I am trying to develop some code for a college work and I have an algorithm that gives me the shortest path between two nodes in a graph. Please note that the nodes are Countries that have a capital.
Can anyone explain me how I can develop something that gives me the shortest path from country A to country B passing trough a list of capitals (countries)?
I have implemented a method that gives me the distance between two geographical points as well.
My initial thought was to order the list of capitals based on their distance to the country A and then sum all the distances of the shortest path between country A and the first of the list, then the first of the list and the third of the list and so on. Apparentely this is not correct.
    public double shortestPathCapitals2(List<String> capitais, Pais pOrig, Pais pDest) {
    double dist = 0;
    LinkedList<Pais> shortPath = new LinkedList<Pais>();
    LinkedList<String> temp = new LinkedList<>(capitais);

    temp.addFirst(pOrig.getCapital());
    temp.addLast(pDest.getCapital());

    Collections.sort(temp, (c1, c2) -> (int) (distance(pOrig, shortestPathCapitals2(c2)) - distance(pOrig, obterPaisPorCapital(c1))));

    for (int i = 0; i < temp.size() - 1; i++) {
        Pais p1 = obterPaisPorCapital(temp.get(i));
        Pais p2 = obterPaisPorCapital(temp.get(i + 1));
        dist += shortestPath(p1, p2, shortPath);
        shortPath.clear();
    }

    return dist;
}

Thank you.

A: problem description:
Given a graph with vertices V and edges E.
We want to find a path P between Va and Vb such that:

*

*the path contains {V0, V1, ..} (some subset of V)

*the sum of weights on edges in P is minimal

pseudo-code:
function findPath(startVertex, endVertex, verticesToBeVisited, currentPath)

    // check if we have reached the destination
    if startVertex == endVertex:

          /*
           * there are multiple ways of reaching the destination
           * calculate the length of the past (also called the cost)
           * if the cost is lower than the current minimum, store the path
           */
          cost = calculateCost(currentPath)
          if cost  < currentMinCost:
              currentMinCost = cost
              currentMinPath = currentPath

    else:

        /*
         * if we have not reached the destination
         * we need to try all possible next hops
         * this algorithm uses recursion to do so
         */
        for every vertex Vn that is a neighbour of startVertex:

            /*
             * this check prevents us from going
             * Paris --> Rome --> Paris --> Rome (endlessly)
             */
            if currentPath contains Vn:
                 continue

            // add the next hop to our path
            currentPath += Vn

            // if this vertex needed to be visit, cross it out in the list
            if verticesToBeVisited contains Vn:
                verticesToBeVisited -= Vn

            // recursion
            findPath(Vn, endVertex, verticesToBeVisited, currentPath)

            // clean up
            if verticesToBeVisited contained Vn:
                verticesToBeVisited += Vn

            currentPath -= Vn


text:
Q: Aligning a multidimensional array in java? Is there a way to align the columns of a multidimensional array to make all the values of a column line up properly. For example this is what happens when I System.out my code.
    Mon Tue Wed Thurs Fri Sat Sun Average
1   5.0 5.0 5.0 5.0 5.0 5.0 5.0 5
2   5.0 5.0 5.0 5.0 5.0 5.0 5.0 5
3   5.0 5.0 5.0 5.0 5.0 5.0 5.0 5
4   5.0 5.0 5.0 5.0 5.0 5.0 5.0 5

Towards the end because of Thurs text it starts of off set my columns. Is there a way I can line them up?

A: Take a look at System.out.printf.

A: Definitely checkout http://trac.inamik.com/trac/jtable_format, which is a open-source library for formatting fixed width character based tables.


text:
Q: Mongoose: How to add additional field into subdocument array I have a question regarding mongoDB, namely mongoose:
Let's say I have 2 models: 1) Product model 2) User model
const ProductSchema = new Schema({
  title: String,
  description: String,
  product_type: String,
  image_tag: String,
  created_at: Number,
  price: Number
});
const Product = module.exports = mongoose.model('product', ProductSchema);

const UserSchema = new Schema({
  login: String,
  email: String,
  password: String,
  purchases: [{
    type: Schema.Types.ObjectId,
    ref: 'product'
  }]
});
const User = module.exports = mongoose.model('user', UserSchema);

When the user buys some goods, I just add product to purchases array in user model(using push method). If I need to match purchase's ID to its full description I use populate.
The problem is I need somehow to control quantity of each purchase made by user -> I need additional field in each purchase object inside array...something like quantity or total, like that:
const UserSchema = new Schema({
     ...
      purchases: [{
        type: Schema.Types.ObjectId,
        ref: 'product',
        quantity: {
          type: Number,
          default: 1
        }
      }]
    });

I'm stuck and have no clue how to implement this. Example above does not work.

A: Try this, this way will definitely work:
const UserSchema = new Schema({
    purchases: [{
            ref: {
                 type: Schema.Types.ObjectId,
                 ref: 'product'
            },
            quantity: {
              type: Number,
              default: 1
            }
          }]
 });


text:
Q: Application Insights in Net Core 2 WebApi - Share Context To Append Properties We are looking to record the username attached to every authorized request for our system in Application Insights.
The issue I'm facing is, using this article as a guide, that it throws an InvalidOperationException whenever I try to access session.
public class PropertyTelemetryInitializer : ITelemetryInitializer
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public PropertyTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void Initialize(ITelemetry telemetry)
    {
        try
        {
            if (!(telemetry is RequestTelemetry requestTelemetry))
                return;

            if (_httpContextAccessor.HttpContext?.Session == null || !_httpContextAccessor.HttpContext.Session.IsAvailable)
                return;

            var userId = _httpContextAccessor.HttpContext.Session.GetInt32("UserId");
            requestTelemetry.Context.Properties["userId"] = userId?.ToString();
        }
        catch (Exception)
        {
            // Throws "Session has not been configured for this application or request."

        }

    }
}

We get the user details out of session in the base class of every controller in our WebApi system - is there a way to get the current request context at that point and append the userId to the Properties collection at that level of the request?

A: Yes, you can access the RequestTelemetry inside your controller as shown below.
    // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var requestTelemetry = HttpContext.Features.Get<RequestTelemetry>();
            requestTelemetry.Context.Properties["userId"] = "myuserid"
            return new string[] { "value1", "value2" };
        }


text:
Q: how to get only todays posts based on expression match nodejs mongo moment.js //this is my controller
 async getTasksCount (req, res) {
        try {
            let resultall = {};
            const strDate = moment().startOf('day').utc().toDate();
            const endDate = moment().endOf('day').utc().toDate()

                let todayTask = await tasksRepo.getToDayTaskCount({"isDeleted" : false, "isScheduled": true, "isCompleted": false, startDate: { $ne: null },
                $expr: {
                    $or: [
                        { $gte: ['strDate', moment().startOf('day').utc().toDate()] },
                        { $lte: ['endDate', moment().endOf('day').utc().toDate()] }
                    ]
                }
                });

              console.log("x1"+strDate)
              console.log("x2"+endDate)
              console.log("xx"+ todayTask.length)
}

//this is the query written for expression match and to get projection of data with start and end date we have some kind of pattern we make repo called file in project in that we write queries or else normally this method would be in controller

    getToDayTaskCount: async (params) => {
        try {
            let aggregate = await TasksModel.aggregate([
               {
                   $project:{
                       _id: '$_id',
                       title: '$title',
                       description: '$description',
                       isCompleted: '$isCompleted',
                       isScheduled: '$isScheduled',
                       status: '$status',
                       strDate: { $dateToString: { format: "%Y-%m-%d", date: "$start" } },
                       endDate: { $dateToString: { format: "%Y-%m-%d", date: "$end" } },
                       isDeleted: '$isDeleted',
                    //    daysCount: {
                    //     $round: {
                    //       $divide: [
                    //         {
                    //           $subtract: [
                    //             "$end",
                    //             "$start"
                    //           ]
                    //         },
                    //         86400000
                    //       ]
                    //     }
                    //   }
                   },
               },
               {$match: params},
            ]);

            return aggregate;
        } catch (e) {
            return e;
        }
    },
//this is my model if needed

    const TasksSchema = new Schema({
      title: { type: String, default: '' },
      workorder_id: { type: Schema.Types.ObjectId, ref: 'Workorders', default: null },
      manager: { type: Schema.Types.ObjectId, ref: 'User', default: null },
      technicians: [{ type: Schema.Types.ObjectId, ref: 'User', default: null }],
      description: { type: String, default: '' },
      start: { type: Date, default: null },
      end: { type: Date, default: null },
      timezone: { type: String, default: '' },
      isCompleted: { type: Boolean, default: false, enum: [true, false] },
      price: { type: Schema.Types.Double, default: 0.00 },
      status: { type: String, default: 'New', enum: status },
      isDeleted: { type: Boolean, default: false, enum: [true, false] },
    }, { timestamps: true, versionKey: false });

//some of background
I have to show total count of todays tasks using momentjs after getting the aggregated data I even got todays data but that was last years same date.  if i create 5 tasks today i must get 5 posts . so that i can take count of it and show it on dashboard I'm new to aggregation please help me out!
// what I have tried out of scope
I even tried mapping on results and filter it to get all taks and then count of only todays but in this way i got last years todays tasks as result that is not desired output

A: I would suggest making use of the fromNow function

moment().startOf('day').fromNow();        // 17 hours ago

moment().endOf('day').fromNow();          // in 7 hours

moment().startOf('hour').fromNow();

from relative time section

*

*https://momentjs.com/