text:
Q: Difference between Search and Incremental Exports? Incremental Exports:
I query at a certain time for all records which have changed since a specific time. I would personally use the max updated_at timestamp in my database.
https://developer.zendesk.com/rest_api/docs/support/incremental_export
Search:
I can query a certain endpoint/table for all tickets which have been updated since the max updated_at timestamp in my database.
https://developer.zendesk.com/rest_api/docs/support/search
path='/api/v2/search.json', query='query=type:ticket updated>=2019-06-10T00:00:00Z'

It seems like both of these methods achieve the same goal, but I want to be certain that I choose the right one and that there are no caveats or issues I will run into later.
I assume that if I keep track of the max update timestamp that I have already retrieved, then I can always pull new/changed records >= from that timestamp (and only have minor duplication that I need to address from records with the exact same timestamp). Any suggestions?

A: The main difference between Search and Incremental Export is Query.
But according to you start_time in Incremental Export and country=US&toll_free=true in Search  both are same but actually NOT.
Because query is checking the availability of something, which is actually performing by any search query but in start_time that is not query because you are just pointing a starting point you have no concern what the values is coming. But in query you have concerns, because you want "That is the value which I want"
Hope so you are getting my point and clearing your doubt.


text:
Q: Simulation Velocity of a harmonic oscillator system I am write a simulation for get true Velocity of a harmonic oscillator system as

Where P=[p1 p2;p2 p3] can find using Rung-Kutta Integration method with P(0)=[1 0; 0 1]
Now, I want to write matlab code to get the true postion z of the system and estimate x inwhich x=[x1 x2]'. This is my code to find x and z. However, the result is not correct. Could you help me to modify it. This is my matlab code
function  z=getPos(x)
  %% Function to get velocity
  v=0+1*randn; %r=1;
  z=[0 1]*x+v;
return

This is my result

Let see help me is correct implement for the solution. Thank you

A: Your code can return a negative value as randn is a normally distributed random number with standard deviation 1. In theory this could return any number and there is ~15% chance it will be less than -1.
You are also correct than you should update x at each step. I would take x as an input into getPos and xdot as an output. Then add another step to update the position.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Malformed XML, responseXML and jQuery - how to let then work? I need to parse some web pages with jQuery, and I've tried to make use of methods related to the httpRequest.responseXML approach. In this way, I've found that XML for this page appears malformed (that is what jQuery.isXMLDoc(httpRequest.responseXML) says), and so I don't have any way to work with it.
The strange aspect is that, if don't load the page in an httpRequest, but I parse with jQuery the same page opened in a tab in a Firefox extension, everything works successfully.
Can you suggest me a reason because there are such different behaviours, and how to make the first option work correctly?
Thanks, ciao!
Livio

A: Firefox may be 'correcting' the XML for you automatically (XML is fairly predictable, adding a missing closing tag for example).
When it's passed onto the extension, it already contains the corrections done by the browser itself and jQuery recognizes this as valid XML.
When you load the source directly, there's no interference and thus, the parsing fails.


text:
Q: Binding two UserControls to the same DataContext, or ViewModel? I am working on a UserControl, which is composed of a Chart panel and another area which manipulates some of the chart data i.e. the chart controls (change color of graph, enable or disable stuff on the chart, etc.).
I use a ViewModel to manage the chart and its data, but was thinking maybe it would be nice to make a separate usercontrol out of the chart control area to keep my xaml from getting to big and to separate out the components.
If I do this though, since the controls would need to manipulate the data from the Chart ViewModel, how should I approach it?  Can I bind the DataContext of the Chart controls to the DataContext of the Chart, so I just have one ViewModel?  Should I give my chart control its own viewmodel and then have the chart panel and chart controls viewmodels talk somehow?
Or just forget about a separate usercontrol and stuff everything into one big viewmodel/xaml control?
What would people recommend in this case?

A: You absolutely can have your two UserControls bind to the same ViewModel. You can either bind the DataContext of each to the same object instance, or I suppose you could have the DataContext of one control bound to the DataContext of the other and have it bound to your ViewModel.
If you're starting with a working implementation of your view and your viewmodel, and you feel like the XAML is getting unwieldy, I would agree that you should separate the XAML into multiple views. There's no reason that means you need to separate your ViewModel implementation until you feel that it is becoming incoherent, or just too big. Separating it now would just add complexity as you suggested that they would need to communicate anyway.
You might consider starting by simply creating a UserControl out of the chart controls area and embed that control inside your existing control. Then you don't have to modify any screens that use your chart control.


text:
Q: Calling a js function from another content script file I have a file a.js that is related to the a.html file.
Then. I have another content-script file, that modifies calendar.google.com
I added a button on the calendar page, and when I press it, I want to call a function from the other file:
I have done this. but I get an 404 error for it:
  $.getScript("vidyoChromeExt.js", function(){

                           alert("Script loaded but not necessarily executed.");
                            reLogin("event");

                        });

The issue is that it searches for the file inside:
jquery-2.0.3.min.js:6 GET https://calendar.google.com/calendar/vidyoChromeExt.js?_=1465892174555 404 ()

so instead of taking the root from my extension, it takes the root from the calendar.google.com page, so it won't find my file. How can I make it point to the files from my project?

A: Use chrome.runtime.getURL("vidyoChromeExt.js").
You have to include the file in the web_accessible_resources section of manifest file:
"web_accessible_resources": ["vidyoChromeExt.js"]


text:
Q: Ionic 3 Error - fullscreen and ion-refresher don't work together After adding fullscreen to my ion-content, my ion-refresher is no longer visible. Changing CSS is every way possible doesn't help. I've found this post https://github.com/ionic-team/ionic/issues/10490, which seems to indicate that this is a genuine Ionic bug, but it's been almost a year and so far I couldn't find anything else on this: https://github.com/ionic-team/ionic/issues/10490
Does anyone know a workaround? Or any advice will be highly appreciated.


text:
Q: Summing with a for loop faster than with reduce? I wanted to see how much faster reduce was than using a for loop for simple numerical operations. Here's what I found (using the standard timeit library):
In [54]: print(setup)
from operator import add, iadd
r = range(100)

In [55]: print(stmt1)
c = 0
for i in r:
    c+=i

In [56]: timeit(stmt1, setup)
Out[56]: 8.948904991149902
In [58]: print(stmt3)
reduce(add, r)

In [59]: timeit(stmt3, setup)
Out[59]: 13.316915035247803

Looking a little more:
In [68]: timeit("1+2", setup)
Out[68]: 0.04145693778991699

In [69]: timeit("add(1,2)", setup)
Out[69]: 0.22807812690734863

What's going on here? Obviously, reduce does loop faster than for, but the function call seems to dominate. Shouldn't the reduce version run almost entirely in C? Using iadd(c,i) in the for loop version makes it run in ~24 seconds. Why would using operator.add be so much slower than +? I was under the impression + and operator.add run the same C code (I checked to make sure operator.add wasn't just calling + in python or anything).
BTW, just using sum runs in ~2.3 seconds.
In [70]: print(sys.version)
2.7.1 (r271:86882M, Nov 30 2010, 09:39:13)
[GCC 4.0.1 (Apple Inc. build 5494)]

A: The reduce(add, r) must invoke the add() function 100 times, so the overhead of the function calls adds up -- reduce uses PyEval_CallObject to invoke add on each iteration:
for (;;) {
    ...
    if (result == NULL)
        result = op2;
    else {
        # here it is creating a tuple to pass the previous result and the next
        # value from range(100) into func add():
        PyTuple_SetItem(args, 0, result);
        PyTuple_SetItem(args, 1, op2);
        if ((result = PyEval_CallObject(func, args)) == NULL)
            goto Fail;
    }

Updated: Response to question in comments.
When you type 1 + 2 in Python source code, the bytecode compiler performs the addition in place and replaces that expression with 3:
f1 = lambda: 1 + 2
c1 = byteplay.Code.from_code(f1.func_code)
print c1.code

1           1 LOAD_CONST           3
            2 RETURN_VALUE

If you add two variables a + b the compiler will generate bytecode which loads the two variables and performs a BINARY_ADD, which is far faster than calling a function to perform the addition:
f2 = lambda a, b: a + b
c2 = byteplay.Code.from_code(f2.func_code)
print c2.code

1           1 LOAD_FAST            a
            2 LOAD_FAST            b
            3 BINARY_ADD
            4 RETURN_VALUE

A: It could be the overhead of copying args and return values (i.e. "add(1, 2)"), opposed to simply operating on numeric literals

A: edit: Switching out zeroes instead of array multiply closes the gap big time.
from functools import reduce
from numpy import array, arange, zeros
from time import time

def add(x, y):
    return x + y

def sum_columns(x):
    if x.any():
        width = len(x[0])
        total = zeros(width)
    for row in x:
        total += array(row)
    return total

l = arange(3000000)
l = array([l, l, l])

start = time()
print(reduce(add, l))
print('Reduce took {}'.format(time() - start))

start = time()
print(sum_columns(l))
print('For loop took took {}'.format(time() - start))

Gets you down almost no difference at all.
Reduce took 0.03230619430541992
For loop took took 0.058577775955200195

old: If reduce is used for adding together NumPy arrays by index, it can be faster than a for loop.
from functools import reduce
from numpy import array, arange
from time import time

def add(x, y):
    return x + y

def sum_columns(x):
    if x.any():
        width = len(x[0])
        total = array([0] * width)
    for row in x:
        total += array(row)
    return total

l = arange(3000000)
l = array([l, l, l])

start = time()
print(reduce(add, l))
print('Reduce took {}'.format(time() - start))

start = time()
print(sum_columns(l))
print('For loop took took {}'.format(time() - start))

With the result of
[      0       3       6 ..., 8999991 8999994 8999997]
Reduce took 0.024930953979492188
[      0       3       6 ..., 8999991 8999994 8999997]
For loop took took 0.3731539249420166


text:
Q: C - Sending UDP messages client-client through a socket I have a simple question. I think it is simple, at least!
I'm doing an university project and I've built a server-client instant messagging service, structured like so:
-The server create a TCP socket to listen for client requests
-Each client, besides the other functions, can send messagges to another client (even offline) using UDP
I've used port 4242 for the server, then tried to use 4243 and 4244 for two example clients.
My question is: are these ports not acceptable for UDP communications?
I'm asking because when I try to send messages to those ports, the receiving client gets and prints "strange" strings.
To be precise, it is as it stored precedent messages and prints first the new message, then a chunk of precedent messages.
On the other hand, if I use for example 4303 and 4486, it works as expected.
I got those numbers looking at Wikipedia, but since I'm not sure how to interpret that table (and so, if I interpreted it correctly) and since I know Wikipedia can be not-so-reliable, I figured I could ask here.
On a side note, is there any command or resource to check for this things, if the link I provided is not reliable?
Thanks in advance!
EDIT:
Here's my code! I couldn't upload it before.. I'll try to give a brief explanation of it as well.
As I mentioned in a comment, I thought I had it but one client does not receive the message from the other. So all works, except for the !send functionality, I guess...
Client
The client is an user that connects to the server with "!register username"; this command:
-Registers the client to the service if it's the first time that he's connecting to it, and of course set it as "online"
-Re-connects the client if he was already registered to the service; in this case, if there are some offline messages the servers delivers it to te client
Once connected, the client can use the following commands:
1)!help: displays the available commands
2)!who: shows online users
3)!deregister: as the nam suggests, de-register the client from the server
4)!send username: if the destination client is online, the server returns the UDP destination address and port and the client sends the message directly; if the destination client is offline, the servers stores the message to send it to the destination client once it will be connected
    #include <stdlib.h>
    #include <string.h>
    #include <arpa/inet.h>
    #include <netinet/in.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <unistd.h>
    #include <stdio.h>

    #define DIM 1024
    #define ADDR_DIM 16
    #define PORT_DIM 5
    #define CMD_DIM 12
    #define NAME_DIM 21

    void cl_help(int sckt) {
    int rv, length, l;
    char* text = "!help";
    char answer[DIM];

    length = strlen(text);
    l = htons(length);

    //Sending command dimension
    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {};

    //Sending the command itself
    rv = recv(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    length = ntohs(l);

    rv = recv(sckt, (void*) answer, length, 0);
    if(rv < 0) {};

    answer[length] = '\0';
    puts(answer);
    }

    void cl_quit(int sckt) {
    int rv, length, l;
    char* text = "!quit";
    char answer[DIM];

    length = strlen(text);
    l = htons(length);

    //Sending command dimension
    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {};

    //Sending the command itself
    rv = recv(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    length = ntohs(l);

    rv = recv(sckt, (void*) answer, length, 0);
    if(rv < 0) {};

    answer[length] = '\0';
    puts(answer);
    }

    void cl_who(int sckt) {
    int rv, length, l, n_net, n, i;
    char* text = "!who";
    char answer[DIM];

    length = strlen(text);
    l = htons(length);

    //Sending the dimension of the command
    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {};

    //Sending the command itself
    rv = recv(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    length = ntohs(l);

    rv = recv(sckt, (void*) answer, length, 0);
    if(rv < 0) {};

    answer[length] = '\0';
    puts(answer);

    if( (strcmp(answer, "Nessun utente in linea") != 0)\
        && (strcmp(answer, "Devi essere connesso per poter utilizzare questa funzione") != 0) ) { //No user online; Yuo have to be registered

        //Receiving number of users online
        rv = recv(sckt, (void*) &l, sizeof(l), 0);
        if(rv < 0) {};

        length = ntohs(l);

        rv = recv(sckt, (void*) &n_net, length, 0);
        if(rv < 0) {};

        n = ntohs(n_net);

        //Getting every username
        for(i=0; i<n; i++) {
            rv = recv(sckt, (void*) &l, sizeof(l), 0);
            if(rv < 0) {};

            length = ntohs(l);

            rv = recv(sckt, (void*) answer, length, 0);
            if(rv < 0) {};

            answer[length] = '\0';
            puts(answer);
        };
    };

    }

    void cl_deregister(int sckt) {
    int rv, length, l;
    char* text = "!deregister";
    char answer[DIM];

    //Sending command dimension
    length = strlen(text);
    l = htons(length);

    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {};

    //Receiving answer
    rv = recv(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    length = ntohs(l);

    rv = recv(sckt, (void*) answer, length, 0);
    if(rv < 0) {};

    answer[length] = '\0';
    puts(answer);
    }

    void cl_register(int sckt, char* name, char* port) {
    int rv, length, l, n, n_net, i;
    char msg[DIM+NAME_DIM+4];
    char answer[DIM];

    sprintf(msg, "!register %s %s", name, port);

    //Sending command
    length = strlen(msg);
    l = htons(length);

    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) msg, length, 0);
    if(rv < 0) {};

    //Receiving answer
    rv = recv(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    length = ntohs(l);

    rv = recv(sckt, (void*) answer, length, 0);
    if(rv < 0) {};

    answer[length] = '\0';
    puts(answer);

    if(strcmp(answer, "L'utente era gia' registrato al servizio: riconnessione completata.\n") == 0) { //Users already registered: reconnection
        //Receiving info
        rv = recv(sckt, (void*) &l, sizeof(l), 0);
        if(rv < 0) {};

        length = ntohs(l);

        rv = recv(sckt, (void*) answer, length, 0);
        if(rv < 0) {};

        answer[length] = '\0';
        puts(answer);

        if(strcmp(answer, "Messaggi offline presenti.") == 0) { //Offline messages found
            //Receiving the number of messages
            rv = recv(sckt, (void*) &l, sizeof(l), 0);
            if(rv < 0) {};

            length = ntohs(l);

            rv = recv(sckt, (void*) &n_net, length, 0);
            if(rv < 0) {};

            n = ntohs(n_net);

            //Recevingi messages
            for(i=0; i<n; i++) {
                rv = recv(sckt, (void*) &l, sizeof(l), 0);
                if(rv < 0) {};

                length = ntohs(l);

                rv = recv(sckt, (void*) msg, length, 0);
                if(rv < 0) {};

                msg[length] = '\0';
                puts(msg);
            };
        };
    };
    }

    void cl_send(int sckt, int udp_sd, char* name, char* info, char* source) {
    struct sockaddr_in dest;
    int rv, length, l,p;
    char msg[DIM+NAME_DIM+4];
    char address[ADDR_DIM];
    char port[PORT_DIM];
    char answer[DIM];
    char *pointer;

    sprintf(msg, "!send %s", name);

    //Sending command
    length = strlen(msg);
    l = htons(length);

    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) msg, length, 0);
    if(rv < 0) {};

    //Receiving answer
    rv = recv(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    length = ntohs(l);

    rv = recv(sckt, (void*) answer, length, 0);
    if(rv < 0) {};

    answer[length] = '\0';

    puts(answer);

    if(strcmp(answer, "Devi essere connesso per poter utilizzare questa funzione.\n") != 0) { //You have to be registered
        if(strncmp(answer, "Client attualmente connesso", 27) == 0) { //User connected right now
            pointer = answer+29; //to get only the address and the port number
            sscanf(pointer, "%s %s", address, port);
            address[ADDR_DIM] = '\0';
            port[PORT_DIM] = '\0';
            p = ntohs(atoi(port));

            memset(&dest, 0, sizeof(dest));
            memset(&msg, 0, sizeof(msg));f

            //Destination UDP socket
            dest.sin_family = AF_INET;
            dest.sin_port = htons(p);
            inet_pton(AF_INET, address, &dest.sin_addr);

            //Sending direct message using UDP
            sprintf(msg, "%s > ", source);
            strcat(msg, info);

            length = strlen(msg);
            l = htons(length);

            //Sending message
            rv = sendto(udp_sd, (void*) &l, sizeof(l), 0, (struct sockaddr*) &dest, sizeof(dest));
            if(rv < 0) {};

            rv = sendto(udp_sd, (void*) msg, length, 0, (struct sockaddr*) &dest, sizeof(dest));
            if(rv < 0) {};

        } else { //Offline transmission: transmits message to server using TCP
            length = strlen(info);
            l = htons(length);

            rv = send(sckt, (void*) &l, sizeof(l), 0);
            if(rv < 0) {};

            rv = send(sckt, (void*) info, length, 0);
            if(rv < 0) {};

            //Getting info from the server
            rv = recv(sckt, (void*) &l, sizeof(l), 0);
            if(rv < 0) {};

            length = ntohs(l);

            rv = recv(sckt, (void*) answer, length, 0);
            if(rv < 0) {};

            answer[length] = '\0';
            puts(answer);
        };
    };
    }

    int main(int argc, char* argv[]) {
    struct sockaddr_in srv_addr;
    struct sockaddr_in my_addr;
    int sd, udp;
    int err;
    int pid;
    int length, l;
    char buffer[DIM];
    char cmd[CMD_DIM];
    char dest[NAME_DIM];
    char my_name[NAME_DIM];
    char in[DIM];
    char to_send[DIM+NAME_DIM+4];
    char part[DIM] = "";

    if(argc != 5) {
        //Check argument
        exit(EXIT_FAILURE);
    };

    //TCP socket
    sd = socket(AF_INET, SOCK_STREAM, 0);
    //UDP socket
    udp = socket(AF_INET, SOCK_DGRAM, 0);

    //Pulizia
    memset(&srv_addr, 0, sizeof(srv_addr));
    memset(&my_addr, 0, sizeof(my_addr));

    //TCP server parameters
    srv_addr.sin_family = AF_INET;
    srv_addr.sin_port = htons(atoi(argv[4]));
    inet_pton(AF_INET, argv[3], &srv_addr.sin_addr);

    //my UDP parameters
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(atoi(argv[2]));
    inet_pton(AF_INET, argv[1], &my_addr.sin_addr);

    //Bind for UDP socket
    err = bind(udp, (struct sockaddr*) &my_addr, sizeof(my_addr));
    if(err < 0) {};

    //Connecting to the server
    err = connect(sd, (struct sockaddr*) &srv_addr, sizeof(srv_addr));
    if(err < 0) {};

    //Auto-sending help command to display available operations
    strcpy(cmd, "!help");

    length = strlen(cmd);
    l = htons(length);

    err = send(sd, (void*) &l, sizeof(l), 0);
    if(err < 0) {};

    err = send(sd, (void*) cmd, length, 0);
    if(err < 0) {};

    //Receiving info from the server -> available operations
    err = recv(sd, (void*) &l, sizeof(l), 0);
    if(err < 0) {};

    length = ntohs(l);

    err = recv(sd, (void*) buffer, length, 0);
    if(err < 0) {};

    buffer[strlen(buffer)] = '\0';
    puts(buffer);

    pid = fork();
    if(pid == 0) {
        //Child
        close(sd);

        while(1) {
            memset(to_send, 0, sizeof(to_send));

            err = recvfrom(udp, (void*) &l, sizeof(l), 0, 0, 0);
            if(err < 0) {
                puts("error recvfrom");
                exit(EXIT_FAILURE);
            };

            length = ntohs(l);

            err = recvfrom(udp, (void*) to_send, length, MSG_WAITALL, 0, 0);
            if(err < 0) {
                puts("error recvfrom");
                exit(EXIT_FAILURE);
            };

            to_send[length] = '\0';
            puts(to_send);
        };
    } else {
        //Parent

        while(1) {
            //Asking the user to prompt the command
            memset(cmd, 0, sizeof(cmd));
            memset(in, 0, sizeof(in));
            memset(dest, 0, sizeof(dest));
            puts("\nInserisci un comando: "); //Insert a command
            fgets(in, DIM, stdin);

            in[strlen(in)-1] = '\0';
            sscanf(in, "%s", cmd);
            cmd[CMD_DIM-1] = '\0';

            if(strcmp(cmd, "!help") == 0) {
                cl_help(sd);
                continue;
            };

            if(strcmp(cmd, "!deregister") == 0) {
                cl_deregister(sd);
            };

            if(strcmp(cmd, "!register") == 0) {
                sscanf(in, "%s %s", cmd, dest);
                cmd[CMD_DIM-1] = '\0';
                dest[NAME_DIM-1] = '\0';
                strcpy(my_name, dest);
                if(strlen(dest) == 0) { //to avoid an empty username
                    puts("Errore: non hai inserito alcun username; riprova.\n"); //Please insert an username
                } else {
                    cl_register(sd, dest, argv[2]);
                };
                continue;
            };

            if(strcmp(cmd, "!who") == 0) {
                cl_who(sd);
                continue;
            };

            if(strcmp(cmd, "!send") == 0) {
                sscanf(in, "%s %s", cmd, dest);
                cmd[CMD_DIM-1] = '\0';
                dest[NAME_DIM-1] = '\0';

                while(1) {
                    memset(part, 0, sizeof(part));

                    fgets(part, DIM-(strlen(to_send)-NAME_DIM-4), stdin);
                    l = strlen(part);

                    if((part[l-2] == '.') && (part[l-1] == '\n') && (strlen(part) == 2)) {
                        part[l-2] = '\0';
                        break;
                    } else {
                        strcat(to_send, part);
                    };

                    if(strlen(to_send) >= DIM+NAME_DIM+3) {
                        to_send[DIM+NAME_DIM+3] = '\0';
                        break;
                    };
                };
                strcat(to_send, "\0");
                cl_send(sd, udp, dest, to_send, my_name);
                memset(to_send, 0, sizeof(to_send)); //to empty the buffer used to store the message sent
                continue;
            };

            if(strcmp(cmd, "!quit") == 0) {
                cl_quit(sd);
                close(sd);
                break;
            } else{
                puts("Comando non valido.\n"); //Not a valid command
            };
        };
    };

    return 0;
    }

Server
The server answers the requests from the client and is structured as a concurrent server.
#include <sys/mman.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>

#define MAX_CONN 100
#define DIM 1024
#define ADDR_DIM 16
#define CMD_DIM 12
#define NAME_DIM 20
#define MSG_DIM DIM+NAME_DIM+4
#define PORT_DIM 5
#define MAX_UTN 1024

struct users {
    char username[NAME_DIM];
    char status; //c = connected, o = offline
    struct sockaddr_in address;
    char pendent[DIM][DIM];
    char sender[DIM][NAME_DIM];
    int msg; //last message to be sent
};

void srv_help(int sckt) {
    int rv, length, l;

    char* text = "Sono disponibili i seguenti comandi: \n\
 !help --> mostra l'elenco dei comandi disponibili \n\
 !register username --> registra il client presso il server\n\
 !deregister --> de-registra il client presso il server\n\
 !who --> mostra l'elenco degli utenti disponibili\n\
 !send username --> invia un messaggio ad un altro utente\n\
                (messaggio subito dopo comando\n\
 !quit --> disconnette il client dal server ed esce\n\
 ('username': max 20 caratteri)\n\
 (per terminare messaggio inserisci un . da solo)\n";//info about the available commands

    length = strlen(text);
    l = htons(length);

    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {};
};

void srv_who(int sckt, struct users* reg, int last) {
    int i, rv, length, l;
    char text[DIM];

    strcpy(text, "Nessun utente in linea\n");//No user online

    if(last == 0) { //if no user is online
        length = strlen(text);
        l = htons(length);

        rv = send(sckt, (void*) &l, sizeof(l), 0);
        if(rv < 0) {};

        rv = send(sckt, (void*) text, length, 0);
        if(rv < 0) {};
    } else {
        strcpy(text, "Utenti in linea:\n"); //Users online:

        length = strlen(text);
        l = htons(length);

        rv = send(sckt, (void*) &l, sizeof(l), 0);
        if(rv < 0) {};

        rv = send(sckt, (void*) text, length, 0);
        if(rv < 0) {};

        //Here I send the number of users online, to synchronize server and client
        length = sizeof(last);
        l = htons(length);

        rv = send(sckt, (void*) &l, sizeof(l), 0);
        if(rv < 0) {};

        l = htons(last);
        rv = send(sckt, (void*) &l, length, 0);
        if(rv < 0) {};

        //Transmitting users
        for(i=0; i<last; i++) {
            if(reg[i].status == 'c') {
                length = strlen(reg[i].username);
                l = htons(length);

                rv = send(sckt, (void*) &l, sizeof(l), 0);
                if(rv < 0) {};

                rv = send(sckt, (void*) reg[i].username, length, 0);
                if(rv < 0) {};
            };
        };
    };
};

void srv_deregister(int sckt, struct users* reg, char* name, int* last) {
    int i, rv, length, l;
    char text[DIM];
    strcpy(text, "Deregistrazione completata.\n"); //De-registration completed

    for(i=0; i<*last; i++) {
        if(strcmp(reg[i].username, name) == 0) { //user found
            reg[i] = reg[*last];
            (*last)--;

            length = strlen(text);
            l = htons(length);

            rv = send(sckt, (void*) &l, sizeof(l), 0);
            if(rv < 0) {};

            rv = send(sckt, (void*) text, length, 0);
            if(rv < 0) {};

            return;
        };
    };
}

int srv_register(int sckt, struct users* reg, char* name, struct sockaddr_in client, int p, int* last) { //char*
    int i, rv, length, l, j, pos;
    //char pos[MSG_DIM]; // = "";
    char text[DIM];
    char buffer[MSG_DIM];

    memset(text, 0, DIM);
    strcpy(text, "Registrazione effettuata con successo.\n"); //Registration completed

    for(i=0; i<*last; i++) {

        if(strcmp(reg[i].username, name) == 0) { //User already registered: re-connection
            strcpy(text, "L'utente era gia' registrato al servizio: riconnessione completata.\n"); //Re-connection completed
            reg[i].status = 'c';
            reg[i].address.sin_family = client.sin_family;
            reg[i].address.sin_port = p;
            reg[i].address.sin_addr.s_addr = client.sin_addr.s_addr;

            length = strlen(text);
            l = htons(length);

            rv = send(sckt, (void*) &l, sizeof(l), 0);
            if(rv < 0) {};

            rv = send(sckt, (void*) text, length, 0);
            if(rv < 0) {};

            if(reg[i].msg > 0) { //messaggi offline
                strcpy(text, "Messaggi offline presenti.\n"); //Offline messages found

                length = strlen(text);
                l = htons(length);

                rv = send(sckt, (void*) &l, sizeof(l), 0);
                if(rv < 0) {};

                rv = send(sckt, (void*) text, length, 0);
                if(rv < 0) {};

                //Sending number of messages to be sent
                length = sizeof(*last);
                l = htons(length);

                rv = send(sckt, (void*) &l, sizeof(l), 0);
                if(rv < 0) {};

                l = htons(*last);

                rv = send(sckt, (void*) &l, length, 0);
                if(rv < 0) {};

                for(j=0; j<reg[i].msg; j++) {

                    sprintf(buffer, "%s > ", reg[i].sender[j]);
                    strcat(buffer, reg[i].pendent[j]);

                    length = strlen(buffer);
                    l = htons(length);

                    rv = send(sckt, (void*) &l, sizeof(l), 0);
                    if(rv < 0) {};

                    rv = send(sckt, (void*) buffer, length, 0);
                    if(rv < 0) {};
                };

                //Set number of messages to send to 0
                reg[i].msg = 0;
            } else {
                strcpy(text, "Nessun messaggio offline presente.\n"); //No offline messages

                rv = send(sckt, (void*) &l, sizeof(l), 0);
                if(rv < 0) {};

                rv = send(sckt, (void*) text, length, 0);
                if(rv < 0) {};
            };
            return 1;
        };
    };

    //If the user is not already registered

    if(*last == MAX_UTN) { //max number of users reached
        strcpy(text, "Impossibile registrarsi al servizio: numero limite di utenti raggiunto.\n"); //Max number of users reached
        pos = -1;
    } else {
        strcpy(reg[*last].username, name);
        reg[*last].address.sin_family = client.sin_family;
        reg[*last].address.sin_port = p;
        reg[*last].address.sin_addr.s_addr = client.sin_addr.s_addr;
        reg[*last].status = 'c';
        reg[*last].msg = 0;
        (*last)++;
        pos = 1;
    };

    length = strlen(text);
    l = htons(length);

    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {}

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {}

    return pos;
}

void srv_quit(int sckt, struct users* reg, char* user, int num) {
    int i, length, l, rv;
    char text[DIM];
    memset(text, 0, DIM);
    strcpy(text, "Utente disconnesso.\n"); //_User disconnected

    for(i=0; i<num; i++) {
        if(strcmp(reg[i].username, user) == 0) { //user actually registered to the service
            if(reg[i].status == 'c') {
                reg[i].status = 'o';
            };
            memset(&reg[i].address, 0, sizeof(reg[i].address));

            length = strlen(text);
            l = htons(length);

            rv = send(sckt, (void*) &l, sizeof(l), 0);
            if(rv < 0) {};

            rv = send(sckt, (void*) text, length, 0);
            if(rv < 0) {};

            printf("%s disconnesso.\n", user); //<User> disconnected

            return;
            };
        };
    //if here, user is not registered to the service
    strcpy(text, "L'utente non era registrato al servizio.\n"); //User not registered

    length = strlen(text);
    l = htons(length);

    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {};
}

void srv_send(int sckt, struct users* reg, int num, char* dest, char* source) {
    int i, rv, length, l;
    char text[DIM];
    char addr[ADDR_DIM];
    memset(text, 0, DIM);

    for(i=0; i<num; i++) {
        if(strcmp(reg[i].username, dest) == 0) { //User registered

            if(reg[i].status == 'c') { //user connected: provides destination UDP address to the sender (it will directly send the message)
                inet_ntop(AF_INET, &reg[i].address.sin_addr.s_addr, addr, sizeof(addr));
                sprintf(text, "Client attualmente connesso: %s %d \n", addr , ntohs(reg[i].address.sin_port));
                break;
            } else { //user disconnected: save offline message
                //Getting the message
                rv = recv(sckt, (void*) &l, sizeof(l), 0);
                if(rv < 0) {};

                length = ntohs(l);

                rv = recv(sckt, (void*) reg[i].pendent, length, 0);
                if(rv < 0) {};

                reg[i].pendent[reg[i].msg][length] = '\0';
                strcpy(reg[i].sender[reg[i].msg], source);
                reg[i].msg++;

                //Sending info to te sender
                strcpy(text, "Messaggio salvato per l'invio offline.\n"); //Message saved offline

                length = strlen(text);
                l = htons(length);

                rv = send(sckt, (void*) &l, sizeof(l), 0);
                if(rv < 0) {};

                rv = send(sckt, (void*) text, length, 0);
                if(rv < 0) {};

                return;
            };
        };
    };
    //Here if got into the if statement
    length = strlen(text);
    l = htons(length);

    rv = send(sckt, (void*) &l, sizeof(l), 0);
    if(rv < 0) {};

    rv = send(sckt, (void*) text, length, 0);
    if(rv < 0) {};
}

int main(int argc, char* argv[]) {
    //shared (mapped) memory
    struct users* registered = mmap(0, MAX_CONN*sizeof(struct users), PROT_READ | PROT_WRITE,  MAP_ANONYMOUS | MAP_SHARED, 0, 0);
    //last index with user struct to be used
    int* last = mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, 0, 0);

    int sd; //socket descriptor
    int conn_sd; //socket descriptor after connect()
    struct sockaddr_in my_addr;
    struct sockaddr_in cl_addr;
    int err; //for errors
    int udp_port;
    char check[NAME_DIM]; //will containg the username of the client connected
    socklen_t len;
    int pid;
    int dim_rcvd_net, dim_rcvd, dim_sent_net, dim_sent;
    char buffer[DIM];
    char cmd[CMD_DIM];
    char name[NAME_DIM];
    char port[PORT_DIM];

    *last = 0;
    memset(registered, 0, MAX_CONN*sizeof(struct users));
    memset(check,0,  NAME_DIM);
    puts("Avvio del servizio...\n"); //Service starting..

    if(argc != 2) {
        printf("Errore: troppi argomenti. \n Utilizzare solamente un argomento."); //Please use only one argument
        exit(EXIT_FAILURE);
    };

    //Maybe check the argument itself?

    sd = socket(AF_INET, SOCK_STREAM, 0);

    memset(&my_addr, 0, sizeof(my_addr));

    //Socket parameters
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(atoi(argv[1]));
    my_addr.sin_addr.s_addr = INADDR_ANY;

    err = bind(sd, (struct sockaddr*) &my_addr, sizeof(my_addr));
    if(err < 0) {};

    err = listen(sd, MAX_CONN);
    if(err < 0) {};
    puts("Servizio attivo.\n"); //Service activated

    //Concurrent server
    while(1) {

        len = sizeof(my_addr);
        conn_sd = accept(sd, (struct sockaddr*) &cl_addr, &len);
        //error check to be done

        pid = fork();
        if(pid == 0) {
            //Child
            close(sd);

            while(1) {
                //Command dimension
                err = recv(conn_sd, (void*) &dim_rcvd_net, sizeof(dim_rcvd), 0);
                if(err < 0) {};

                dim_rcvd = ntohs(dim_rcvd_net);

                //Command
                err = recv(conn_sd, (void*) buffer, dim_rcvd, 0);
                if(err < 0) {};

                buffer[dim_rcvd] = '\0';

                sscanf(buffer, "%s", cmd);

                if(strcmp(cmd, "!help") == 0) {
                    srv_help(conn_sd);
                };

                if(strcmp(cmd, "!register") == 0) {
                    if(strlen(check) > 0) { //Already connected with another username
                        puts("Sei già connesso con altro nome.\n"); //Already connected
                    } else {
                        sscanf(buffer, "%s %s %s", cmd, name, port);
                        udp_port = atoi(port);

                        if(srv_register(conn_sd, registered, name, cl_addr, udp_port, last) == 1) {
                            strcpy(check, name);
                        };
                    };
                };

                if(strcmp(cmd, "!deregister") == 0) {
                    if(strlen(check) <= 0) { //if not registered
                        strcpy(buffer, "Devi essere connesso per poter utilizzare questa funzione.\n"); //You have to be registered

                        dim_sent = strlen(buffer);
                        dim_sent_net = htons(dim_sent);

                        err = send(conn_sd, (void*) &dim_sent_net, sizeof(dim_sent_net), 0);
                        if(err < 0) {};

                        err = send(conn_sd, (void*) buffer, dim_sent, 0);
                        if(err < 0) {};
                    } else {
                        srv_deregister(conn_sd, registered, check, last);
                        strcpy(check, "");
                    };
                };

                if(strcmp(cmd, "!send") == 0) {
                    if(strlen(check) <= 0) { //if not registered
                        strcpy(buffer, "Devi essere connesso per poter utilizzare questa funzione.\n"); //You have to be registered

                        dim_sent = strlen(buffer);
                        dim_sent_net = htons(dim_sent);

                        err = send(conn_sd, (void*) &dim_sent_net, sizeof(dim_sent_net), 0);
                        if(err < 0) {};

                        err = send(conn_sd, (void*) buffer, dim_sent, 0);
                        if(err < 0) {};
                    } else {
                        sscanf(buffer, "%s %s", cmd, name);
                        srv_send(conn_sd, registered, *last, name, check);
                    };
                };

                if(strcmp(cmd, "!who") == 0) {

                    if(strlen(check) <= 0) { //if not registered
                        strcpy(buffer, "Devi essere connesso per poter utilizzare questa funzione"); //You have to be registered

                        dim_sent = strlen(buffer);
                        dim_sent_net = htons(dim_sent);

                        err = send(conn_sd, (void*) &dim_sent_net, sizeof(dim_sent_net), 0);
                        if(err < 0) {};

                        err = send(conn_sd, (void*) buffer, dim_sent, 0);
                        if(err < 0) {};
                    } else {
                        srv_who(conn_sd, registered, *last);
                    };
                };

                if(strcmp(cmd, "!quit") == 0) {
                    srv_quit(conn_sd, registered, check, *last);
                    close(conn_sd);
                    exit(EXIT_SUCCESS);
                };
            };

        } else {

            //Parent
            close(conn_sd);
        };

    };

    close(sd);
    return 0;
}

EDIT 2
There's something I don't get. I've just re-executed the exactly same program I've pasted here, and it seems to send the messages correctly (only online for now).
Could it be some synchronization problem maybe?
EDIT 3 This is the text of the assignment: http://www2.ing.unipi.it/c.vallati/files/reti/Progetto2017.pdf
As I said in the comments, it's in italian..

A: OK, I've solved my problem!
First of all, I moved the UDP socket creation. Previously, in the code I've pasted here, it was before the fork(). Thinking about it, I thought it was wrong because parent and child would have shared the socket and the child would have continuously used it, and it seems I was right. So I create a separate UDP for parent (to send to other clients) and child (to receive transmissions).
Then I figured why sometimes the code worked and sometimes not: in my previous executions, when the program froze I was shutting it down with Ctrl+Z; looking at the output of htop, I noticed some of its execution (the children, to be precise) were still running and occupying the sockets. So I went ahead and terminate them.
After adding some more error capture code and correcting what was wrong in the communication, everyting went fine and still does.
And tis time I made sure to make the parent kill() the child when closed.
So yeah, all works as expected regarding the approach with the "dual" transmissions (first the dimension of the text, and then the text itself).

A: each port can be used for udp or tcp uses
there are some ports that are assigned to specific use officialy by the IANA
like 80 for http and 21 for ftp ... (the  table in wikipedia page )
your problem is that your reciving program read more than the client have sent
because the string sent via the socket doesn't contain any terminating character '\0' (strlen doesn't count the terminating char '\0')
so the server reads first the message and doesn't stop reading so it print that strange characters
the solution is to send the terminating character by adding one to the strlen(stirng) in send function like this
bytes_sent = send(client_socket, thestring, strlen(thestirng)+1, 0);


text:
Q: Plugin to use gitolite's ACLs for CGIT/Apache httpd? We use gitolite's ACL mechanism to control who has access to different repositories.  We also use CGIT with Apache httpd to allow browsing of readable repositories.
We'd like to also use the gitolite ACLs in the Apache httpd access control system.
Is there an Apache httpd authn/authz module that provides this functionality?
Thanks!

A: I have integrated CGit and gitolite a while ago with this cgi Perl script, calling gitolite: cgit/cgit.pl.tpl.
(don't mind the @H@, those are template placeholder that are supposed to be valued later in order to produce the actual Perl script)
The idea is to benefit from the authentication done by Apache:
my $remote_user=$ENV{"REMOTE_USER"};

And to use that user when calling Gitolite to check if the access to a repo can be granted, calling the actual cgit.cgi C procedure if the access is granted:
use Gitolite::Rc;
use Gitolite::Common;
use Gitolite::Conf::Load;

(my $repo)=($path_info =~ /\/([^\/]+)/);
  my $perm = "R";
  if ($repo ne "") {
  my $aperm = access( $repo, $user, 'R', 'any' );
  # my ($aperm, $creator) = &repo_rights($repo);
    $perm=$aperm;
  }
  if ($perm !~ /DENIED/) {
    system("@H@/cgit/cgit.cgi");
  }
  else {
    print "Content-type: text/html\n\n";
    print "\n";
    print "\n";
    print "
HTTP Status 403 - Access is denied
\n";
    print " You don't have access to repo $repo as $user\n";
    print "\n";
    print "\n";
  }


text:
Q: Solving differential equations for simulations Recently I've started a few programming projects which involve simulating physical systems. However, more than most involve a differential equation which needs to be solved. Some examples are:
$$\frac{d^2\theta}{dt^2} = -\frac{g}{l}\sin \theta$$
$$\left(\frac{da}{dt}\times\frac{1}{a}\right)^2 = \frac{8\pi G\rho}{3} - \frac{kc^2}{a^2}$$
The technique I have been doing so far is using Wolfram Alpha to integrate the equation and then plot the result. For some of the equations I have found, WA has struggled, leaving me clueless.
I don't know a huge amount about differential equations beyond simple equations such as $\frac{dy}{dx}=2xy$, so I am unable to integrate the equations by hand.
That was why I was wondering if there is a way to find the solution on the fly, so to speak. For example, I would like to generate a graph of $\theta(t)$ in the first equation without first integrating it.
I mostly use JavaScript and Python, but am willing to use another, free, language which has the tools which will help me complete my projects.

A: ODE is your friend, available in:

*

*ode45 in Matlab/Octave,

*ode45 in Simulink,

*ode in Scilab,

*scipy.integrate.ode in Phyton

*and perhaps in Java.

In MATLAB/Octave, Others solvers ode23, ode15 are intended for specific cases of ODEs, when the default choice of ode45 is not working well, or when the problems include nonlinearities, discontinuities, etc.

A: With the first one
$$\frac{d^{2}\theta(t)}{dt^{2}}=-g\sin{\theta(t)}$$
Multiply by $\frac{d\theta(t)}{dt}$
$$\frac{d\theta(t)}{dt}\frac{d^{2}\theta(t)}{dt^{2}}=-g\frac{d\theta(t)}{dt}\sin{\theta(t)}$$
Using the chain rule
$$\frac{d}{dt}\frac{1}{2}\Big(\frac{d\theta(t)}{dt}\Big)^{2}=g\frac{d}{dt}\cos{\theta(t)}$$
Thus
$$\Big(\frac{d\theta(t)}{dt}\Big)^{2}=2g\cos{\theta(t)}+c_{1}$$
Hence
$$t+c_{2}=\frac{1}{\sqrt{2g}}\int^{\theta}\frac{d\theta'}{\pm\sqrt{\frac{c_{1}}+\cos{\theta'}}}=\frac{2\sqrt{\frac{c_{1}+2g\cos{\theta}}{c_{1}+2g}}F\Big(\frac{\theta}{2}\Big{|}\frac{4g}{c_{1}+1}\Big)}{\pm\sqrt{c_{1}+2g\cos{\theta}}}$$
Where $F(z|k^{2})$ is the incomplete elliptic integral of the first kind. With the second one
$$\frac{da}{dt}=\pm\sqrt{\frac{8\pi{G}\rho}{3}a-\frac{kc^{2}}{a}}$$
$$t+c=\int^{a}\frac{da'}{\pm\sqrt{\frac{8\pi{G}\rho}{3}a'-\frac{kc^{2}}{a'}}}=\int^{a}\frac{\sqrt{a'}da'}{\pm\sqrt{\frac{8\pi{G}\rho}{3}(a')^{2}-kc^{2}}}$$
Let $a'=\sqrt{\frac{3kc^{2}}{8\pi{G}\rho}}\cos{\alpha}$ then
$$t+c=\Big(\frac{3kc^{2}}{8\pi{G}\rho}\Big)^{3/4}\frac{1}{\mp{i}\sqrt{kc^{2}}}\int^{\sqrt{8\pi{G}\rho/2kc^{2}}\arccos{a}}\sqrt{\cos{\alpha}}d\alpha=\Big(\frac{3kc^{2}}{8\pi{G}\rho}\Big)^{3/4}\frac{1}{\mp{i}\sqrt{kc^{2}}}E\Big(\frac{1}{2}\sqrt{8\pi{G}\rho/2kc^{2}}\arccos{a}\Big{|}2\Big)$$
Where $E(z, k^{2})$ is the incomplete elliptic integral of the second kind.

A: There is no difficulty writing a Runge-Kutta solver (RK4), for equations $y'=f(y,t)$ where $f$ is arbitrary. https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
The scalar version is suited to first order ODEs.
For higher order, you turn the equation in a vector form:
$$y'''=f(y'',y',y,t)$$ becomes
$$(y_2,y_1,y_0)'=(f(y_2,y_1,y_0,t),y_2,y_1)$$ which is of the type
$$(\vec y)'=\vec g(\vec y,t).$$


text:
Q: Printing an Array in a Queue I'm having a problem printing out the contents of an array used in a queue.
A portion of my template queue:
#include <iostream>
#include <cstdlib>
using namespace std;

template<class T>
class Queue
{
private:
    int front;      //front position
    int rear;       //rear position
    int maxQue;     //maximum number of elements in the queue
    T* items;       //points to a dynamically-allocated array code here
public:
    Queue()  // default constructor: Queue is created and empty
    {
        front = -1;
        rear = 0;
        maxQue = 10;
        items = new T[maxQue];
    }

    void Print()   // print the value of all elements in the queue
    {
        while(front != rear)
        {
            cout<<items[front];
            front++;
            if(front==rear)
               break;
            cout<<" - ";
        }
        cout<<endl;
    }

    void Enqueue(T add)      // insert x to the rear of the queue
    {                           // Precondition: the queue is not full
        if(IsFull())
        {
             cout<<"Queue is full!"<<endl;
        }
        else
        {
             items[rear] = add;
             rear++;
             rear = rear % maxQue;
        }
    }

    void Dequeue(T &x)  // delete the element from the front of the queue
    {                       // Precondition: the queue is not empty
         if(!IsEmpty())
         {
             front = (front+1)%maxQue;
             x = items[front];
         }
    }

    bool IsEmpty()   // test if the queue is empty
    {
         return (rear==front);
    }

    bool IsFull()   // test if the queue is full
    {
         return ((rear+1)%maxQue==front);
    }

    int length()    // return the number of elements in the queue
    {
         return abs(rear-front);
    }

    ~Queue()  // Destructor:  memory for the dynamic array needs to be deallocated
    {
         delete [] items;
    }
};

A portion of the main routine:
int main()
{
     Queue<float>FloatQueue;
     float y;
     FloatQueue.MakeEmpty();

     FloatQueue.Dequeue(y);
     FloatQueue.Enqueue(7.1);
     cout << "float length 3 = " << FloatQueue.length() << endl;

     FloatQueue.Enqueue(2.3);
     cout << "float length 4 = " << FloatQueue.length() << endl;

     FloatQueue.Enqueue(3.1);
     FloatQueue.Dequeue(y);
     cout << "The float queue contains:  ";
     FloatQueue.Print();

     return 0;
}

The code compiles fine up until it tries to print, at which point I get these errors.
0 00000000  0x00466a7f in std::__convert_from_v() (??:??)
1 00000000  0x00430302 in std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::_M_insert_float<double>() (??:??)
2 00000000  0x00430da8 in std::num_put<char, std::ostreambuf_iterator<char, std::char_traits<char> > >::do_put() (??:??)
3 00000000  0x00447455 in std::ostream::_M_insert<double>() (??:??)
4 00000000  0x00448988 in std::ostream::operator<<() (??:??)
5 0041CB37  Queue<float>::Print(this=0x28ff00)

I've been stuck on this for a few days now, any help would be greatly appreciated.

A: It looks like you're implementing a fixed-size circular buffer.  If so (or even if not) you have a few issues:

*

*If you enqueue more than the maximum size of the queue before taking anything out of it, it will never register as full.

*If your "front" pointer is greater than your rear pointer, your print function will never stop, and front will continue until MAX_INT and maybe loop around again.  You're not doing the mod operation on the maximum size of the buffer.

*You have no destructor, so your buffer will leak every time you make and destroy one of these objects.

*Your length function is incorrect.  Any time front is larger than rear (which is half the time) it will be in error.  Think of it this way, when it's full, size will say zero.

And maybe a few other things than that.  I'd re-think your design.  You're close, but you have a few math errors.


text:
Q: How will you design classes with many parameters and different clients For example, if we have a class with 8 parameters:
class TestClass(
    private val paramA: ParamA,
    private val paramB: ParamB,
    private val paramC: ParamC,
    private val paramD: ParamD,
    private val paramE: ParamE,
    private val paramF: ParamF,
    private val paramG: ParamG,
    private val clientA: ClientA,
    private val clientB: ClientB
)

Most of the time, when this class is used, first 7 parameters will always be passed. The last 2 parameters will depend on the use case. If we need use clientA to call other functions, it will pass clientA, and clientB will be null. If we need use clientB to call other functions, it will pass clientB, and clientA will be null. Inside the class, either clientA or clientB will be used to call other functions, depending on which one is not null.
Can we use different approach here? I don't like using if...else... to check clientA or clientB is null then do other things. Can we replace the two parameters with
private val clientGeneric: ClientGeneric

then clientA and clientB can inherit from ClientGeneric and be passed to TestClass. But I don't see a good way to make clientA and clientB inherit from a ClientGeneric class.

A: Just thought about the following approach. Does this look right?
interface TestGeneric {
    fun testFun()
}

class Client1 (clientA: ClientA): TestGeneric {
    override fun testFun() {
        System.out.println("from client 1")
    }
}

class Client2 (clientB: ClientB): TestGeneric {
    override fun testFun() {
        System.out.println("from client 2")
    }
}

class ClientA

class ClientB

class TestClass (private val test: TestGeneric) {
    fun testtest() {
        test.testFun()
    }
}


text:
Q: Hibernate - moving annotations from property (method) level to field level How do I generate hibernate domain classes from tables with annotations at field level? I used Hibernate Tools project and generated domain classes from the tables in the database. The generated classes have annotations on the getter methods rather than at the field level. Kindly advice a way to generate domain classes that have the fields annotated. Is there any refactoring facility available in eclipse/IDEA etc.. to move the annotations from method level to field level?
Appreciate your help and time.

A: Here are the steps:

*

*Allocate "hibernate-tools.jar" by perform a search within your eclipse folder
For example, You will find it at
C:\eclipse\plugins\org.hibernate.eclipse_3.4.1.xxx\lib\tools

*Extract to a temp folder (WinRar can do this)
For example, extract to [Your Project]\template

*Under [Your Project]\template\pojo folder, create a file named "Ejb3FieldGetAnnotation.ftl"
This file is actually a copy of "Ejb3PropertyGetAnnotation.ftl" but all of words "property" are replaced by "field" because this file will be placed in the a loop that iterates through all fields (instead of properties).
I include the content of the file in this post

*Remove property-level annotations:
In file "PojoPropertyAccessors.ftl", remove or comment out
<#include "GetPropertyAnnotation.ftl"/>

*Add field-level annotations:
In file "PojoFields.ftl", add
<#include "Ejb3FieldGetAnnotation.ftl"/>
${pojo.getFieldModifiers(field)} ...

*When generate Java entities, select "Use Custom Templates" and specify the template folder. In this case, it will be [Your Project]\template
==================================================================================
Ejb3FieldGetAnnotation.ftl
==================================================================================

<#if ejb3>
<#if pojo.hasIdentifierProperty()>
<#if field.equals(clazz.identifierProperty)>
 ${pojo.generateAnnIdGenerator()}
<#-- if this is the id property (getter)-->
<#-- explicitly set the column name for this property-->
</#if>
</#if>

<#if c2h.isOneToOne(field)>
${pojo.generateOneToOneAnnotation(field, cfg)}
<#elseif c2h.isManyToOne(field)>
${pojo.generateManyToOneAnnotation(field)}
<#--TODO support optional and targetEntity-->
${pojo.generateJoinColumnsAnnotation(field, cfg)}
<#elseif c2h.isCollection(field)>
${pojo.generateCollectionAnnotation(field, cfg)}
<#else>
${pojo.generateBasicAnnotation(field)}
${pojo.generateAnnColumnAnnotation(field)}
</#if>
</#if>

Hope it work for you.

A: I spent a lot of time reading answers from 5+ years ago without understanding how to do it (especially if you work in Intellij and not Eclipse) and how come this is not already solved. So i found it, here it is, and it is simple:
In Intellij:

*

*Create a file orm.xml in the same folder as your persistence.xml with this content

<?xml version="1.0" encoding="UTF-8"?>
    <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
                     version="2.0">
        <persistence-unit-metadata>
            <persistence-unit-defaults>
                <access>FIELD</access>
            </persistence-unit-defaults>
        </persistence-unit-metadata>
    </entity-mappings>

*Now you can generate your pojos (Generate persistence mapping -> By database schema -> choose your tables etc and don't forget to tick the "Generate JPA Annotations")

Your entities will have field annotations!
@Entity
@Table(name = "user", schema = "public", catalog = "my_db")
public class User {
    @Id
    @Column(name = "id")
    private Integer id;
...
}

A: currently it is necessary to use custom templates. here is more references and examples hot to implement this:
https://forum.hibernate.org/viewtopic.php?f=6&t=1003858&p=2429868#p2429868


text:
Q: React _services_persons__WEBPACK_IMPORTED_MODULE_3__.default.getAll(...) I have the following module:
import axios from 'axios'
const url = 'http://localhost:3001/persons'

const getAll = () => {
    axios.get(url).then(response => {
        return response.data
    })
}

const create = newPerson => {
    axios.post(url, newPerson).then(response => {
        return response.data
    })
}

const remove = id => {
    axios.delete(`${url}/${id}`).then(response => {
        return response.data
    })
}

export default { getAll, create, remove }

That I import with the following line:
import personService from './services/persons'

And when the variable personService is called:
useEffect(() => {
    console.log(personService)
    personService.getAll()
        .then(allPersons => {
            setPersons(allPersons)
        })
}, [])

I have the following error:
TypeError: _services_persons__WEBPACK_IMPORTED_MODULE_3__.default.create(...) is undefined
Note that the console.log(personService) display the following in the console:
    {…}
    create: create()
      length: 1
      name: "create"
      <prototype>: function ()
    getAll: getAll()
      length: 0
      name: "getAll"
      <prototype>: function ()
    remove: remove()
      length: 1
      name: "remove"
      <prototype>: function ()

my react versions are the following:

*

*"react": "^16.8.6",

*"react-dom": "^16.8.6",

*"react-scripts": "3.0.1"

A: The problem came from the functions of my module personService that did not return anything. I fixed it by adding a return statement in my functions getAll, create and remove and now they returns a promise:
import axios from 'axios'
const url = 'http://localhost:3001/persons'

const getAll = () => {
    return axios.get(url).then(response => {
        return response.data
    })
}

const create = newPerson => {
    return axios.post(url, newPerson).then(response => {
        return response.data
    })
}

const remove = id => {
    return axios.delete(`${url}/${id}`).then(response => {
        return response.data
    })
}


text:
Q: Using source() fucntion in r/Rstudio to read the first 100 rows of R file Simple question: I need to read only the first 100 rows of my soruce R file: File.R.
How can I do this?
source(here::here('R/Code_Files/File.R'))


text:
Q: unable to send mail through Yahoo - skpsmtpmessage I downloaded skpsmtpmessage code from Github and ran it on my iphone, it is unable to send any e-mails through my yahoo account. I set
     testMsg.relayHost=@"smtp.mail.yahoo.com"
but it always fail with "Unsupported login mechanism." or something like that even though I have the right login and password on there. see console log below.
Has anybody tried sending mail thru yahoo with this program?
    SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
    testMsg.fromEmail = @"mylogin@yahoo.com";
    testMsg.toEmail =   @"mylogin@yahoo.com";
    testMsg.relayHost = @"smtp.mail.yahoo.com";
    testMsg.requiresAuth = YES;
    testMsg.login = @"mylogin";
    testMsg.pass = @"mypassword";
    testMsg.subject = @"test message";
    testMsg.wantsSecure = NO; // I tried both YES and NO, neither works

Log as follows
    2014-04-25 17:10:08.748 SMTPSender[14408:60b] C: Attempting to connect to server at: smtp.mail.yahoo.com:25
    2014-04-25 17:10:08.774 SMTPSender[14408:60b] Application windows are expected to have a root view controller at the end of application launch
    2014-04-25 17:10:09.010 SMTPSender[14408:60b] *** stopping watchdog ***
    2014-04-25 17:10:09.011 SMTPSender[14408:60b] S: 220 smtp.mail.yahoo.com ESMTP ready
    2014-04-25 17:10:09.011 SMTPSender[14408:60b] C: EHLO localhost
    2014-04-25 17:10:09.012 SMTPSender[14408:60b] *** starting short watchdog ***
    2014-04-25 17:10:09.070 SMTPSender[14408:60b] *** stopping watchdog ***
    2014-04-25 17:10:09.071 SMTPSender[14408:60b] S: 250-smtp.mail.yahoo.com
    2014-04-25 17:10:09.071 SMTPSender[14408:60b] *** stopping watchdog ***
    2014-04-25 17:10:09.071 SMTPSender[14408:60b] S: 250-PIPELINING
    2014-04-25 17:10:09.072 SMTPSender[14408:60b] *** stopping watchdog ***
    2014-04-25 17:10:09.072 SMTPSender[14408:60b] S: 250-SIZE 41697280
    2014-04-25 17:10:09.072 SMTPSender[14408:60b] *** stopping watchdog ***
    2014-04-25 17:10:09.072 SMTPSender[14408:60b] S: 250-8 BITMIME
    2014-04-25 17:10:09.073 SMTPSender[14408:60b] *** stopping watchdog ***
    2014-04-25 17:10:09.073 SMTPSender[14408:60b] S: 250 STARTTLS
    2014-04-25 17:10:09.074 SMTPSender[14408:60b] delegate - error(-2): Unsupported login mechanism.

Any ideas?


text:
Q: My view on an answer has changed dramatically but it is locked - who can help? One of my most popular answers is definitely outdated from my understanding today. I'd like to either add a disclaimer to the top, delete it, or remove my name from it. However, it is closed and locked.
Who can help?

A: Considering it's historically locked, the question and answers shouldn't be updated. That banner shows the content should be taken with a grain of salt already, so I wouldn't feel obligated to get the content adjusted.
If you want to remove your name from it, you can request disassociation of the specific post. That's explained here. Do keep in mind (as in part pointed out by the answer in the link) it's a drastic measure and has side-effects you may not have considered.
To quote:

So how do I remove my name from a post?
If you would like to have your name dissociated from one of your posts, you can request we do so by clicking on the Contact link at the bottom of the respective page. Your username will no longer be linked, the username will be shown as "anon", and you will no longer earn any reputation from the post. All reputation you had previously gained/lost from the post including bounties will also be reversed, and badges you earned from the post may be revoked


text:
Q: Which block of code will execute faster? B1
if (this.id === 'username') {
  switch (this.value.length) {
    case  0:
    case  1:
    case  2:
      // 'Username must be at least 3 characters'
      break;
    case  3:
    case  4:
    case  5:
    case  6:
    case  7:
    case  8:
    case  9:
    case 10:
    case 11:
    case 12:
    case 13:
    case 14:
    case 15:
    case 16:
    case 17:
    case 18:
    case 19:
    case 20:
      // Another if else statement
      break;
    default:
      // 'Username must be at most 20 character'
  }
}

B2
if (this.id === 'username') {
  if (this.value.length < 3) {
    // 'Username must be at least 3 characters'
  } else if (this.value.length > 20) {
    // 'Username must be at most 20 characters'
  } else {
    // Another if else statement
  }
}

I would test this myself using browser developer tools, but unfortunately I'm a n00b to programming, and don't yet know how to use the developer tools all that well. Any input would be greatly appreciated.

A: It's negligible and really depends on the user's Javascript parser.
You should use the second option though as it's much better readability-wise, and much easier to change at a later date. Moreover if you're so concerned with performance the second is fewer characters too which means your site will load faster.

A: The second one is always the better choice for readability, and the performance benefit (if one even exists) would be marginal using a switch statement. The < / > operators are probably an instruction or two of native code, and I can't imagine that any switch statement would compile down to something so small.
I wouldn't even bother to test the difference; it shouldn't be worth your time unless you can prove that those few lines are the bottleneck in your program. (In which case, I would be exceedingly surprised.)
Also, if you're really concerned about good performance practices you could cache the length and achieve a small readability win too.
if (this.id === 'username') {
  var length = this.value.length
  if (length < 3) {
    // 'Username must be at least 3 characters'
  } else if (length > 20) {
    // 'Username must be at most 20 characters'
  } else {
    // Another if else statement
  }
}


text:
Q: How can I show the elapsed time instead of remaining in Rhythmbox? Can I configure Rhythmbox to show the elapsed time instead of remaining time?

Figure 1: Current configuration showing remaining time

A: Simply you can click on that. After clicking you can see elapsed time.


text:
Q: EF6 Migration automatic Migration is not executed Hi I'm trying my hands on a EF6 Code First approach. I understand the basic Concept of Migration and how Code First works but somehow this does not work. I wrote the following Migration class myself not via Add-Migration:
public override void Up()
{
  CreateTable("dbo.Todo", column => new
  {
    Id = column.Int(nullable:false, identity:true),
    Value = column.String(nullable: true),
    CreatedAt = column.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()")
  }).PrimaryKey(t => t.Id);
}

public override void Down()
{
  DropTable("dbo.Todo");
}

But the up Method is not called My Configuration class is as follows:
internal sealed class Configuration : DbMigrationsConfiguration<DataProviderCodeFirst.Entities.TodoContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
        ContextKey = nameof(TodoContext);
    }

    protected override void Seed(DataProviderCodeFirst.Entities.TodoContext context)
    {
    }
}

This is my DataContext:
public TodoContext(): base("SomeConnectionString")
{

}

public TodoContext(string connectionString)
  : base(connectionString)
{
  Database.CreateIfNotExists();
  Database.SetInitializer(new MigrateDatabaseToLatestVersion<TodoContext, Configuration>());
  Database.Initialize(false);
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  base.OnModelCreating(modelBuilder);
  modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

public virtual DbSet<Todo> Todos { get; set; }

An my Entity Class
  public class Todo
  {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime CreatedAt { get; set; } = DateTime.Now;

    public string Value { get; set; }

  }

It creates the Database and the tables the key is set to identity, but the CreatedAt is not set to computed and in Debugging the Up() Function is not called.
Thanks is advance

A: You have to run 'Enable-Migration' then 'Add-Migration' command and then run  'Update-Database' command.


text:
Q: RCT_EXPORT_METHOD for Zendesk support SDK I'm trying to bridge the Zendesk Support SDK to render in my react native app.
Here is what I would normally do in objective-c:
#import "ViewController.h"
#import <ZendeskSDK/ZendeskSDK.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)ButtonPress:(id)sender {
    [ZDKHelpCenter presentHelpCenterWithViewController:self];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

How can I use RCT_EXPORT_METHOD to bridge?
At the moment I got something like this:
#import "zendeskSupportView.h"
#import <ZendeskSDK/ZendeskSDK.h>
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>
#import <React/UIView+React.h>

@implementation zendeskSupportView

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(findEvents:(RCTResponseSenderBlock)callback)
{
  UIViewController *rootController = [UIApplication sharedApplication].delegate.window.rootViewController;
  rootController = [rootController topMostController];
  [ZDKHelpCenter presentHelpCenterWithViewController:rootController];

}

@end

A: For setting native module you can refer to react native module documentation or have a look at a gist of a small module i created in my project earlier which opens IOS settings app.
In your RCT_EXPORT_METHOD macro code, you will need to call [ZDKHelpCenter presentHelpCenterWithViewController:self]; . As there is no controller instance available directly in this function, you can do something like this:
UIViewController *rootController = [UIApplication sharedApplication].delegate.window.rootViewController;
rootController = [rootController topMostController];
[ZDKHelpCenter presentHelpCenterWithViewController:rootController];

Above code, passes topmost controller in ios controllers stack to ZendDeskHelpCenter.


text:
Q: How to access data graphic item class from existing stencils on visio c#/vba? Below is my code where i want to access the existing data graphic item. But i got null object from the below code. how will i get access to the existing data graphic item?
Visio.Document visioStencil = visioDocs.OpenEx("C:/Users/user/Documents/sample.vssx",
                (short)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenDocked);

Visio.Page visioPage = app.ActivePage;

Visio.Master vsoMaster = app.ActiveDocument.Masters.AddEx(VisMasterTypes.visTypeDataGraphic);

Visio.Master vsoMaster_old = app.ActiveDocument.Masters.get_ItemU(@"Data Graphic.9");


text:
Q: Changing puttyTRAY's URL regex in order to match URLs across lines separated by tmux window boundaries I use puttytray to access a shell account on which I have a tmux instance running. Inside tmux, I have irssi running in a window. When people post long URLs in IRC, however, it's annoying since these URLs are broken across lines. Therefore puttytray ends up highlighting something like:
http://blogs.forbes.com/matthewherper/2011/07/13/did-reddit-discover-silent-│
as the URL instead of http://blogs.forbes.com/matthewherper/2011/07/13/did-reddit-discover-silent-censorship-on-google-plus/ .
PuttyTray's regex for URLs is configurable and is currently:
(((https?|ftp):\/\/)|www\.)(([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|net|org|info|biz|gov|name|edu|[a-zA-Z][a-zA-Z]))(:[0-9]+)?((\/|\?)[^ "]*[^ ,;\.:">)])?

Would there be a way to change this in order to match up until the '│' (not pipe) character, ignore the rest of the line, and start matching on the new line?


text:
Q: Exploiting the voice chat feature in Game Centre to create a Skype-like voip app? So one can use AVAudioSession and GKVoiceChatService classes to set up voice chat in ones application like this. Now, is it possible to extend the same feature to creating full featured voip apps the sole purpose if which is device-to-device voice chat.
Assuming this is possible, would Apple approve non-gaming apps that uses this feature?

A: They do allow other game center features for use in non game center apps.  They allow the bluetooth/ad hoc networking.  Similar apps to bump use it, so why not?


text:
Q: animation of sfml by using array of objects How to animate sprite with this code?I know what i should to add time delay,but how do it? I use array of objects to they's fast changing. or is it an irrational way of animating?
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
sf::RenderWindow window(sf::VideoMode(600, 400), "!!!");
void animation()
{
    sf::Texture arrayOfTexture[9];
    sf::Sprite imageOfLamp;
    arrayOfTexture[0].loadFromFile("1.png");
    arrayOfTexture[1].loadFromFile("2.png");
    arrayOfTexture[2].loadFromFile("3.png");
    arrayOfTexture[3].loadFromFile("4.png");
    arrayOfTexture[4].loadFromFile("5.png");
    arrayOfTexture[5].loadFromFile("6.png");
    arrayOfTexture[6].loadFromFile("7.png");
    arrayOfTexture[7].loadFromFile("8.png");
    arrayOfTexture[8].loadFromFile("9.png");
    for(;;)
    {
        for(int i= 0;i <=8;i++)
        {
            imageOfLamp.setTexture(arrayOfTexture[i]);
            window.draw(imageOfLamp);
        }
        for(int i =8;i >=0;i--)
        {
            imageOfLamp.setTexture(arrayOfTexture[i]);
            window.draw(imageOfLamp);
        }
    }
}

A: As said in the comments. For the animation you need to capture the time. Or you will not be able to calculate the duration per frame. And you need to store the current frame in a variable. I put some comment in the example code below. It is not a class anymore because I think we need a running code block here.
An alternative is the sprite sheet, see https://www.gamefromscratch.com/post/2015/10/26/SFML-CPP-Tutorial-Spritesheets-and-Animation.aspx I can re-write the answer with the sprite sheet, but I think you wanted to understand the basic mechanism of an animation first. Please indicate so in a comment to my post.
Btw, if you are not used to game loops, have a look on https://gafferongames.com/post/fix_your_timestep/
#include <SFML/Graphics.hpp>

int main(){
  sf::RenderWindow renderWindow(sf::VideoMode(800, 600), "Color Animation");

  // Duration to control animation speed
  int currentFrame = 1;
  float duration = float();

  sf::Clock clock;
  sf::Event event;

  sf::Texture arrayOfTexture[9];
  arrayOfTexture[0].loadFromFile("1.png");
  arrayOfTexture[1].loadFromFile("2.png");
  arrayOfTexture[2].loadFromFile("3.png");
  arrayOfTexture[3].loadFromFile("4.png");
  arrayOfTexture[4].loadFromFile("5.png");
  arrayOfTexture[5].loadFromFile("6.png");
  arrayOfTexture[6].loadFromFile("7.png");
  arrayOfTexture[7].loadFromFile("8.png");
  arrayOfTexture[8].loadFromFile("9.png");

  // Assign basic texture to sprite
  sf::Sprite imageOfLamp;
  imageOfLamp.setTexture(arrayOfTexture[0]);

  while (renderWindow.isOpen()){
    // How much time since last loop?
    sf::Time dt = clock.restart();
    duration += dt.asSeconds();

    while (renderWindow.pollEvent(event)){
      //Handle events here
      if (event.type == sf::Event::EventType::Closed)
        renderWindow.close();
    }

    // Animation duration per frame (0.1f) reached
    if (duration > 0.1f){
      // Restart calculation of the duration
      duration = 0;

      // Loop through the animation frames
      if (currentFrame < 9){
        currentFrame += 1;
      } else {
        // Start from first frame if last frame reached
        currentFrame = 0;
      }
      imageOfLamp.setTexture(arrayOfTexture[currentFrame]);
    }

    // Clear render window and draw sprite
    renderWindow.clear(sf::Color::Black);
    renderWindow.draw(imageOfLamp);
    renderWindow.display();
  }
}


text:
Q: Mysql "memory usage" increasing and increasing I have a really big website built old fashioned with PHP & MYSQL.
I have more than 1,000 different queries in my website, on different PHP pages, and it's really hard to update all of them to MYSQLI.
I bought VPS server with 4GB RAM and in the past months I experience really slow page loads.
When I restart my server, everything runs smoothly, but after couple of hours/days the website is getting muchu slower with loading time of 3+ seconds for a page load. I notice that the mysqld service is increasing and increasing in memory usage, from 80MB on server restart it reached about 400MB and more of usage.
I put in the end of my index.php mysql_close() but it seem like the connection number still increasing.
Questions
What can cause unlimited increment in mysql memory usage?
Updating all my queries to MYSQLI may improve the performance?
Some information:
innodb_version
5.5.31
protocol_version
10
slave_type_conversions
version
5.5.31-log
version_comment
MySQL Community Server (GPL)
version_compile_machine
x86_64
version_compile_os
Linux

storage engine: Mixed (Somes tables are INNODB,some tables are MyISAM.
my.cnf:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
max-connections=100000
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
thread_cache_size=5
table_open_cache=99390
sort_buffer_size=512M
read_rnd_buffer_size=512M
query_cache_size=512M
query_cache_limit = 16M
query_cache_type = 1
slow_query_log=1
slow_query_log_file=slow_query_log.log #
long_query_time=5
log-queries-not-using-indexes=1

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

I have about ~6-7 queries running when I use show processlist

A: max-connections=100000 -- Yikes!  Drop to 1000
table_open_cache=99390 -- drop to, say, 2000
sort_buffer_size=512M -- drop to 1% of RAM, say, 40M
read_rnd_buffer_size=512M -- ditto
query_cache_size=512M -- too big; slows things down; drop to 40M
long_query_time=5 -- not low enough to catch much; drop to 2
log-queries-not-using-indexes=1 -- clutters the slowlog without providing much info; change to 0
You did not say which Engine you are using.  Read this for advice on MyISAM and InnoDB.
1000 pages -- that's not too many.
Which web server?  If Apache, don't set MaxClients to more than 20.
2022 postscript: The query_cache_size and query_cache_type variables have been removed from mySQL 8.0.3+.


text:
Q: How to prove that the limit of a function is $0$ at every point I have the following function defined on $\mathbb{R}$:
$$f(x) = \begin{cases}
    0 & \text{if $x$ irrational} \\
    1/n & \text{if $x = m/n$ where $m, n$ coprime}
  \end{cases}$$
I want to show that $f$ is continuous at every irrational point, and has a simple discontinuity at every rational point. I was able to show the first and partially the second (I showed that $f$ has a discontinuity at every rational point, but got stuck on showing that the discontinuity is simple).
However, I've realized that I can simply show that $\lim_{t \rightarrow x}f(t) = 0$ for every $x$, and both of the things I want to show follow from this. How can I show this?

A: Take any $x$. Let $\epsilon > 0$, and find $N$ such that $\frac1 N < \epsilon$.
Now, I claim that there is a $\delta>0$ such that if $y \in (x-\delta,x+\delta) \backslash \{ x\}$, then $y$ is not of the form $\frac mN$ for any integer $m$. Suppose not. Then, considering $\delta$ going to zero and repeatedly contradicting the statement, we get a sequence $y_n = \frac {m_n}N$ such that $y_n \to x$. Now, $m_n \to Nx$. However, remember that $m_n$ are integers, and convergence can only happen in the integers if the sequence is eventually constant! (because different integers are at least $1$ distance from each other). So, $y_n$ is eventually constant. You can work it out from here.
With this lemma, surely the proof is not too far away, is it?

A: Hint.
For $x \in \mathbb R$ and $\epsilon > 0$, the set
$$S(x,\epsilon,n)=\{p/q \ ; \; p \in \mathbb Z \text{ and } 1 \le q \le n \text{ and } p/q \in (x-\epsilon,x+\epsilon) \setminus\{x\}\}$$ is finite.

A: HINTS: observe that there are a finite number of rationals $n/m<1$ for any fixed $m$ (observe that Im not taking into account if $n$ and $m$ are coprime or not).
Now remember that exists infinite rationals of the kind $n/p<1$ where $p$ is prime.
What happen with $m$ when you approximate a number $x$ with a rational $n/m$?


text:
Q: VBA: Running "Worksheet_Change Function" when cell value actually changed, not when just entering and exiting edit mode without any changes I want VBA to ignore "Worksheet_Change Function" when I just double click and exit the cell without any changes to cell value.
P.S. I've bellow code in Worksheet_Change to compare cell value to its previous value:
vNew = Range("cellChanged").value
Application.EnableEvents = False
Application.Undo
vOld = Range("cellChanged").value
Range("cellChanged").value = vNew
Application.EnableEvents = True

But in my VBA code, changing value of a cell leads to change in another cells. So, this code runs nested until I got error on Application.Undo.
Appreciate any help.


text:
Q: Index Error: boolean index did not match indexed array along dimension 0; dimension is 2000 but corresponding boolean dimension is 1001 I have a list of len 2000 and when i try converting it to numpy array i get this error:
Index Error: boolean index did not match indexed array along dimension 0;
  dimension is 2000 but corresponding boolean dimension is 1001

Code Snippet :
NCR = NCR + GROUPED
print(len(NCR))               # 2000
INCR_RESULT = np.array(NCR)   # ERROR!

Any suggestions?


text:
Q: Finding the residual of $\frac 1{e^z-1}$ at $z=2\pi ki$ using limits I'm working on finding $Res(f,2\pi ki)$ where $f(z)= \frac1{e^z-1}$. The example asks for me to use limits, which I know I can as $f$ has a simple pole at $2\pi ki$ for integers k, so I must take $\lim_{z\to 2\pi ki} (\frac {z-2\pi ki}{e^z-1})$. I was stuck at moving on from this step, and the solutions show the next step as simplifying it to $\lim_{z\to 2\pi ki} (\frac 1{e^z})$, and I can see why the residual is 1 from here. However, I'm struggling to see how $\frac {z-2\pi ki}{e^z-1}$ was simplified to $\frac 1{e^z}$

A: You just apply L'Hopital's rule.


text:
Q: How to set up google-diff-match-patch C# library So I am a newbie and I couldn't find a proper answer to this on the internet.
After digging a little bit here is what I came up with.

A: Download google-diff-match-patch from here
One you have extracted it, open up your microsoft visual studio project
Go to View->Solution Explorer or press Ctrl+Alt+L
In solution Explorer right click on your project name and go to Add->Existing Item... or press Shift+Alt+A
In the dialog box that appears locate your diff-match-patch folder and go in csharp directory and select DiffMatchPatch.cs and click on Add
Then in solution explorer right click on References->Add Reference...
Search for System.Web and add it.
Now come back to your program (in my case Form1.cs) and type
using DiffMatchPatch;

Now you are ready to use all the functions of the diff-match-patch library in your C# program

A: Alternatively, add the Nuget Package DiffMatchPatch and add it to your project.
A Demo Code is as follows :
using System;
using System.IO;
using DiffMatchPatch;

namespace ConsoleApp_DMPTrial
{
     class Program
        {
            static void Main(string[] args)
            {
                var dmp = DiffMatchPatchModule.Default;

                string file1Content = "";
                string file2Content = "";

                using (StreamReader sr = new StreamReader("file1.json"))
                {
                    file1Content = sr.ReadToEnd();
                }

                using (StreamReader sr = new StreamReader("file2.json"))
                {
                    file2Content = sr.ReadToEnd();
                }

                var diffs = dmp.DiffMain(file1Content, file2Content);

                dmp.DiffCleanupSemantic(diffs);

                for (int i = 0; i < diffs.Count; i++)
                {
                    Console.WriteLine(diffs[i]);
                }

                Console.ReadLine();
            }
        }
}


text:
Q: 14.04lts data rescue My 14.04 installation has been stable until the latest round of updates. Now on boot I get to the log in password, when I enter it the screen goes blank then random splashes of colour, mouse pointer moves but keyboard is locked out. after approximately thirty seconds the system reboots and goes throught the same loop.
Tried the recovery option using low graphics mode but that froze when I selected that option.
I'm not much more than a beginner, thugh if it requires the command line so be it.
I need to access the ext4 partition to rescue my data before I go further. Used a Live USB to check and all seems to be there but as I'm not logged in with my user name and password it won't let me copy my Home directory data to an external hard drive. Particularly my email archive (thunderbird).
How do I convince this Ubuntu that I'm allowed to access my data?
The system is dual booted with XP hence Ubuntu has been my primary access to the outside world!

A: When you boot form a LiveUSB, you do not login with your name and password. You have access to your HDD, unless there are restrictions.
But if you run
sudo nautilus

in terminal, file manager will start with root rights, and you will be able to do whatever you want.


text:
Q: How do I do about solving this matrix equation? Solve the matrix equations $CYA = D$ in which
$$A=\begin{pmatrix} 1 & 0 & 1  \\ 0 & 2 & 1 \\ 0 & 1 & 1 \end{pmatrix}
\qquad D = \begin{pmatrix} 1 & 1 & 2  \\ 2 & 0 & 1 \end{pmatrix}
\qquad C = \begin{pmatrix} 3 & 2  \\ 1 & 1 \end{pmatrix} $$
How do I solve it?
$$CYA = D \implies Y = D (CA)^{-1}$$
Is that correct?

A: hint: $Y = C^{-1}\cdot D\cdot A^{-1}$


text:
Q: How to make nautilus use file-roller in 17.10 like in 17.04? In Ubuntu 17.10 ubuntu upgraded Nautilus (File Browser) to version 3.26.0. New nautilus is not using file-roller anymore, it has switched to an integrated compression mechanism.

This makes it complicated to create encrypted archives and/or different types compression archives that file-roller does provide.
How to make nautilus use file-roller as before?
Related question: How to get more options in File-Roller?

A: Install nautilus-actions:
sudo apt install nautilus-actions

*

*Context Label: Compress with FR

*Create new action; path: file-roller

*Parameters: -d %F

*Working diretory: %d
For installing nautilus-actions in 18.04, see Nautilus-actions in 18.04.


text:
Q: Repeat a QgsLayoutItem on several pages without using atlas I am creating a script to export an attribute table in pdf format with PyQGIS 3. The number of features is different regarding the farmer's number of fields and features are sorted by the field id.
Regarding the number of fields, the attribute table may need to be extended to next page(s). I would like to repeat the main informations about the farm on the next page(s). Like a header only starting from the second page.
I first defined as many QgsLayoutItemLabel as there were page (making if statements regarding the number of features) but it makes my script really heavy.
There is no map in the layout so I would like to know if it's possible to do it without using the atlas composer.
The following script allows to put my header on the 2nd page, and I would like to repeat it on the 3rd page without creating a new QgsLayoutItemLabel.
project = QgsProject.instance()
layout = QgsPrintLayout(project)

BD = project.mapLayersByName('Base de données client')[0]
prop_field = BD.fields().indexFromName('Propriétaire')
prop = BD.getFeature(idCode).attribute(prop_field)

header1 = QgsLayoutItemLabel(layout)
header1.setText("Liste des contraintes - " + prop)
header1.setFont(QFont("Ms Shell Dlg 2", 11))
header1.setHAlign(Qt.AlignLeft)
header1.setMinimumSize(QgsLayoutSize(133.376, 8.215, QgsUnitTypes.LayoutMillimeters))
header1.attemptMove(QgsLayoutPoint(6, 3.590),page=1)

EDIT
I tried the following code that allows to duplicate an item, but I don't understand why both items are at the same location, on the 1st page, even if a different page is called:
# Crédit
def generateLayoutItemCredit(layoutn, pagenb):
    credit_text = QgsLayoutItemLabel(layoutn)
    credit_text.setText("Plan réalisé par le Club agroenvironnemental de l'Estrie")
    credit_text.setFont(QFont("Ms Shell Dlg 2", 11))
    credit_text.setHAlign(Qt.AlignLeft)
    credit_text.setMarginX(3)
    credit_text.setMinimumSize(QgsLayoutSize(130, 8, QgsUnitTypes.LayoutMillimeters))
    credit_text.attemptMove(QgsLayoutPoint(6, 268),page=pagenb)
    layoutn.addLayoutItem(credit_text) #add layout item inside the function
    return credit_text

generateLayoutItemCredit(layout, 1)
generateLayoutItemCredit(layout, 2)

EDIT 2
Following the same logic as the answer provided, here is how a) I repeated a label only from the 2nd page and b) I repeated a label with the text changing for each page
a) Header repeated from the 2nd page
def generateLayoutItemHeader(layoutn, pagenb):
    header_text = QgsLayoutItemLabel(layoutn)
    header_text.setText("Liste des contraintes - " + prop)
    header_text.setFont(QFont("Ms Shell Dlg 2", 11))
    header_text.setHAlign(Qt.AlignLeft)
    header_text.setMinimumSize(QgsLayoutSize(120, 8, QgsUnitTypes.LayoutMillimeters))
    header_text.attemptMove(QgsLayoutPoint(9, 3),page=pagenb)
    return header_text

# additionnal number of pages
pages_sup=4
for i in range(0, pages_sup):
    page = QgsLayoutItemPage(layout)
    page.setPageSize('Letter', QgsLayoutItemPage.Portrait)
    layout.pageCollection().addPage(page)

for i in range(1, pages_sup + 1):
    header = generateLayoutItemHeader(layout, i)
    layout.addLayoutItem(header)

b) Updating the page number
def generateLayoutItemPage(layoutn, pagenb, label):
    page_text = QgsLayoutItemLabel(layout)
    page_text.setFont(QFont("Ms Shell Dlg 2", 10))
    page_text.attemptMove(QgsLayoutPoint(193, 3.590),page=pagenb)
    page_text.setHAlign(Qt.AlignRight)
    page_text.setMinimumSize(QgsLayoutSize(15, 8.215, QgsUnitTypes.LayoutMillimeters))
    page_text.setText(label)
    return page_text

currPage = 1
for j in range(1, pages_sup + 1):
    labelp = 'page' + str(currPage) + '/' + str(pages_sup + 1)
    pagel = generateLayoutItemPage(layout, j-1, labelp)
    currPage+=1
    layout.addLayoutItem(pagel)

A: You need to add pages before attempting to move your items. Your current code tries to move items to "non existing pages". A demo below (I start from an existing empty layout named demo_multi with one page)
project = QgsProject.instance()
projectLayoutManager = project.layoutManager()
layout = projectLayoutManager.layoutByName('demo_multi')

def generateLayoutItemCredit(layoutn, pagenb):
    credit_text = QgsLayoutItemLabel(layoutn)
    credit_text.setText("Plan réalisé par le Club agroenvironnemental de l'Estrie")
    credit_text.setFont(QFont("Ms Shell Dlg 2", 11))
    credit_text.setHAlign(Qt.AlignLeft)
    credit_text.setMarginX(3)
    credit_text.setMinimumSize(QgsLayoutSize(130, 8, QgsUnitTypes.LayoutMillimeters))
    credit_text.attemptMove(QgsLayoutPoint(6, 268),page=pagenb)
    return credit_text

# additionnal number of pages
pages_sup=2
# Loop twice to add 2 pages
for i in range(0, pages_sup):
    page = QgsLayoutItemPage(layout)
    page.setPageSize('A4', QgsLayoutItemPage.Portrait)
    layout.pageCollection().addPage(page)

# Add items to page by looping 3 times
for i in range(0, pages_sup + 1): # Loop from 0 to 2
    credit = generateLayoutItemCredit(layout, i + 1) # Fix page number to i by adding 1
    layout.addLayoutItem(credit)


text:
Q: Mat Paginator not working in Angular Material Table I am developing a sample code to use pagination . For this , i am using Angular Material Table . I have managed to show the data inside the table as well as the controls for pagination , but somehow it is not working as it should be.
Below is the stackblitz repo link :
https://stackblitz.com/edit/angular-ivy-i4lmdx?file=src/Service/app.service.ts
Important : It is showing the following error on my VSCode.

Any solution please ?

A: There are a lot of mistakes in the stackblitz you linked, to name a few:

*

*No imports for the angular material components you are using

*Not calling the correct component

*Not specifying the correct data source in the mat-table

the error you are seeing

Property 'paginator' does not exist on type 'any[]'.

happens because you are trying to assign an object (paginator) into an array (dummyDataArray), you should instead be setting the paginator on the MatTableDataSource object (in your case - dataSource)
Here is a working stackblitz


text:
Q: Converting UTC Time formatted string into Local Time Zone in Python The  Sunrise-Sunset API returns sunrise/sunset times in UTC string format. How can I convert this time into my local time zone (PST) and store the hours, minutes, and seconds into variables easily and concisely in python?
  {
      "results":
      {
        "sunrise":"2015-05-21T05:05:35+00:00",
        "sunset":"2015-05-21T19:22:59+00:00",
        "solar_noon":"2015-05-21T12:14:17+00:00",
      },
       "status":"OK"
    }


text:
Q: Using strings from other classes C# I have a class that requests that when called a string is sent when requesting / initializing it.
class Checks
{
    public Checks(string hostname2)
    {
        // logic here when class loads

    }

    public void Testing()
    {
        MessageBox.Show(hostname2);
    }
}

How would it be possible to take the string "hostname2") in the class constructor and allow this string to be called anywhere in the "Checks" class?
E.g. I call Checks(hostname2) from the Form1 class, now when the Checks class is initialized I can then use the hostname2 string in my Checks class as well

A: Declare a member inside the class and assign the value you passed to the member inside the constructor:
class Checks
{
    private string hostname2;

    public Checks(string hostname2)
    {
       this.hostname2 = hostname2; // assign to member
    }

    public void Testing()
    {
        MessageBox.Show(hostname2);
    }
}

If you also need to have outside access, make it a property:
class Checks
{
    public string Hostname2 { get; set; }

    public Checks(string hostname2)
    {
       this.Hostname2 = hostname2; // assign to property
    }

    public void Testing()
    {
        MessageBox.Show(Hostname2);
    }
}

Properties start with a capital letter by convention. Now you can access it like this:
Checks c = new Checks("hello");
string h = c.Hostname2; // h = "hello"

Thanks to Andy for pointing this out: if you want the property to be read-only, make the setter private:
public string Hostname2 { get; private set; }

A: You need to copy the constructor argument in a class variable:
class Checks {

    // this string, declared in the class body but outside
    // methods, is a class variable, and can be accessed by
    // any class method.
    string _hostname2;

    public Checks(string hostname2) {
        _hostname2 = hostname2;
    }

    public void Testing() {
        MessageBox.Show(_hostname2);
    }

}

A: You can expose a public property to retun the hostname2 value which is the standard for exposing your private varibles

class Checks
{
    private string _hostname;
    public Checks(string hostname2)
    {
        _hostname = hostname2;
    }
    public string Hostname
    {
       get { return _hostname; }
    }
}


text:
Q: Pyspark logistic Regression fit RDD object has no attribute _jdf error I am using python to create Logistic Regression And tured to mllib for better performence
I installed spark and pyspark.
My data is stored in numpy array and i can easily convert it into pandas dataframe.
I tried to create a spark dataframe to feed the model, but creating the dataframe is too slow and using regular Sklearn is just faster in overall
I found that using Arrow algorithm using this conf

('spark.sql.execution.arrow.enabled', 'true')

can make it faster, But it's still just too slow, and not even utilizing cores (I checked my configurations, and both the executor and driver are set up to have multiple cores, but they are not utilized)
I tried using RDD instead of a dataframe with this code
d = [row.tolist() for row in encoded_data]
d = [LabeledPoint(label, row) for label, row in zip(y_train, d)]
rdd = spark.parallelize(d)
lr.fit(rdd)

But I keep getting this error

AttributeError: 'RDD' object has no attribute '_jdf'

I found this SO question regarding a similar issue, But It does not feet my case, My data does not come from a text file, but from a numpy array, I could write the data to file and then read it, but it does not make sense In my use case.
I would like to find a better way of using data from a numpy array - I have two arrays - one encoded_data than is (n*m) size array of features, and y_train that is (n*1) array of labels. I need to feed it to a Logistic regression in order to improve my training times.
The data is dense for a reason, these are numeric features vectors, not one hot, the reason I turned to Spark was to utilize local cores that are not utilized in Sklearn training.
Thanks.

A: The source of the error is usage of incompatible API's.
Spark provides two ML APIs:

*

*Old pyspark.mllib which is designed to work with RDDs

*New pyspark.ml which is designed to work with DataFrames

You lr object clearly belongs to the latter one, while parallelize is an RDD. See What's the difference between Spark ML and MLLIB packages as suggested in the comments.
Additionally your whole premise is wrong. If you're model can be easily trained on a local data, on single node, using standard Python libraries, then Spark ML has no chance to win here. Spark is all about scaling your process to large datasets, not about reducing latency.
See Why is Apache-Spark - Python so slow locally as compared to pandas?
On top of that using dense structures (I assume this is what you mean by NumPy arrays) to represent one-hot-encoded data is very inefficient, and will significantly affect the performance in general (Spark comes with its own Pipeline API, which among other tools, provides one-hot-encoder yielding Sparse representation).
Finally parallelizing local collections is a testing and development tool, not a production solution.