text:
Q: Dynamically Filter a Dynamically generated list based on id and textbox text WORKING
$(document).ready(function() {
            $("#submit").click(function() {
                    $.ajax({
                        url : "/vmstatus/",
                        type : "POST",
                        dataType: "json",
                        data : {
                            selected_customer : $("#selected_customer").val(),
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                            },
                            success : function(json) {
                                $('#table-repeat-data').remove();
                                setInterval(update_powerstatus, 2000);
                                var on = ''
                                var off = ''
                                var sortarrows = ''
                                $('#table_name').append("

 VM Name" +sortarrows+ "	 Command Status	PowerState " +sortarrows+ " 	Commands

");
                                for (var index = 0; index < json.vmlist.length; index++) {
                                    var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn1(this)" class="btn btn-success" value="' + json.vmlist[index][2] + '">Power On</button>';
                                    var powerOff = '<button type="button" name="PowerOff" id="powerOff" onClick="Reset_send(this)" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
                                    var resetVM = '<button type="button" name="ResetVM"  id="ResetVM" onClick="powerOff_send(this)" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
                                    if(json.vmlist[index][1] == 'poweredOn'){
                                        $('#table-repeat-data').append ('
' + json.vmlist[index][0] + '	' + json.vmlist[index][3] + '	' + on + '	' + powerOn + ' ' + powerOff + ' ' + resetVM + '
');
                                    }else{
                                        $('#table-repeat-data').append ('
' + json.vmlist[index][0] + '	' + json.vmlist[index][3] + '	' + off + '	' + powerOn + ' ' + powerOff + ' ' + resetVM + '
');
                                    }
                                }

                            },
                            error : function(xhr,errmsg,err) {
                                console.log(xhr.status + ": " + xhr.responseText);
                            }

                    });
                    return false;

            });
            $("#table-repeat-data").tablesorter();
        });

function update_powerstatus(){

                    $.ajax({
                        url : "/vmstatus/",
                        type : "POST",
                        dataType: "json",
                        data : {
                            selected_customer : $("#selected_customer").val(),
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                            },
                            success : function(json) {
                                var on = ''
                                var off = ''

                                for (var index = 0; index < json.vmlist.length; index++) {

                                    var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn_send(this)" class="btn btn-success" value="' + json.vmlist[index][2] + '">Power On</button>';
                                    var powerOff = '<button type="button" name="PowerOff" id="powerOff" onClick="powerOff_send(this)" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
                                    var resetVM = '<button type="button" name="ResetVM" id="ResetVM" onClick="Reset_send(this)" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
                                    if(json.vmlist[index][1] == 'poweredOn'){
                                        var get_element_id = json.vmlist[index][2] + '1';
                                        var stat_message_id = 'status' + json.vmlist[index][2];
                                        document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
                                        document.getElementById(stat_message_id).innerHTML = json.vmlist[index][3];
                                        document.getElementById(get_element_id).innerHTML = on + "1";
                                        document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
                                    }else{
                                        var get_element_id = json.vmlist[index][2] + '1';
                                        var stat_message_id = 'status' + json.vmlist[index][2];
                                        document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
                                        document.getElementById(stat_message_id).innerHTML =  json.vmlist[index][3];
                                        document.getElementById(get_element_id).innerHTML = off + "0";
                                        document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
                                    }
                                }

                            },
                            error : function(xhr,errmsg,err) {
                                console.log('Bad');
                                console.log(xhr.status + ": " + xhr.responseText);
                            }
                    });
var $rows = $("#table-repeat-data tr"),
    $filter = $("#filter");

$("#filter").keyup(function () {
    var filterText = $filter.val().toLowerCase();
    $rows.each(function () {
        var $row = $(this);
        $row.toggle($row.text().toLowerCase().indexOf(filterText) > -1);
    });
});
 $("#table-repeat-data").tablesorter();
}

I tried the answer provided by zord, I still call it inside of a looping function so that the values will update as they update in the dynamic table. To pre-answer any questions I have tried it outside of the looping function and the same thing happens. When I use the JS fiddle it works, however when I use it on mine it only filters tables when there are 0 tables with what is typed in the box. It is not recognizing the VM names in the table.

I'm trying to dynamically hide table rows tags that are passed to a function as a list. Then you loop through this list and compare lowercase letters typed in the textbox name vmfilter if the letters typed in the text box match the name it will hide all other tables without that name.
for example our list of vm names is
(test 1, test3vm, highlife, millerlight, beer, nitromilk stout)

and a user types 'm'
only test3vm, millerlight, and nitromilk will show because they have an m. I also need to convert the list names to lower as it loops.
I will preface this with I really suck at JavaScript to my attempt is only half complete and probably way out to lunch.. This function is started after all the data has been properly displayed and runs on a 200ms interval
This is my attempt but it doesn't actually work it will hide some of the  fields but it doesn't reconstruct them correctly, and it doesn't match correctly. I need it to remove the fields because there is still table white space when it removes them.
function checkForMatch(string,array){
    var arrKeys = array.length;
    var match = false;
    var patt;
        for (var index = 0; index < array.length; index++) {
         patt=new RegExp(" "+array[index][0].toLowerCase()+" ");
         if(patt.test(string)){
           document.getElementById(array[index][0]).style.visibility = "visible";
           console.log(string);
           console.log(array[index][0].toLowerCase());
          }else{
            console.log(array[index][0].toLowerCase());
            console.log(string);
            document.getElementById(array[index][0]).style.visibility = "hidden";
          }

        }
}

function vm_filter_name(vmlist){

    var name = $('#vmfilter').val().toLowerCase();
    if(name == ''){
        for (var index = 0; index < vmlist.length; index++) {
         document.getElementById(vmlist[index][0]).style.visibility = "visible";
        }

    }else{
            checkForMatch(name, vmlist);
    }

}

        $(document).ready(function() {
            $("#submit").click(function() {
                    $.ajax({
                        url : "/vmstatus/",
                        type : "POST",
                        dataType: "json",
                        data : {
                            selected_customer : $("#selected_customer").val(),
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                            },
                            success : function(json) {
                                $('#table-repeat-data').remove();
                                setInterval(update_powerstatus, 2000);
                                var on = ''
                                var off = ''
                                $('#table_name').append("

 VM Name	 Command Status	PowerState  	Commands

");
                                for (var index = 0; index < json.vmlist.length; index++) {
                                    var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn1(this)" class="btn btn-success" value="' + json.vmlist[index][5] + '">Power On</button>';
                                    var powerOff = '<button type="button" name="PowerOff" id="powerOff" onClick="Reset_send(this)" class="btn btn-danger" value="' + json.vmlist[index][6] + '">Power Off</button>';
                                    var resetVM = '<button type="button" name="ResetVM"  id="ResetVM" onClick="powerOff_send(this)" class="btn btn-warning" value="' + json.vmlist[index][7] + '">ResetVM</button>';
                                    if(json.vmlist[index][8] == 'poweredOn'){
                                        $('#table-repeat-data').append ('
' + json.vmlist[index][0] + '	' + json.vmlist[index][10] + '	' + on + '	' + powerOn + ' ' + powerOff + ' ' + resetVM + '
');
                                    }else{
                                        $('#table-repeat-data').append ('
' + json.vmlist[index][0] + '	' + json.vmlist[index][14] + '	' + off + '	' + powerOn + ' ' + powerOff + ' ' + resetVM + '
');
                                    }
                                }

                            },
                            error : function(xhr,errmsg,err) {
                                console.log(xhr.status + ": " + xhr.responseText);
                            }

                    });
                    return false;
            });
        });
function update_powerstatus(){

                    $.ajax({
                        url : "/vmstatus/",
                        type : "POST",
                        dataType: "json",
                        data : {
                            selected_customer : $("#selected_customer").val(),
                            csrfmiddlewaretoken: '{{ csrf_token }}'
                            },
                            success : function(json) {
                                var on = ''
                                var off = ''

                                for (var index = 0; index < json.vmlist.length; index++) {
                                    setInterval(vm_filter_name(json.vmlist), 150);
                                    var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn_send(this)" class="btn btn-success" value="' + json.vmlist[index][17] + '">Power On</button>';
                                    var powerOff = '<button type="button" name="PowerOff" id="powerOff" onClick="powerOff_send(this)" class="btn btn-danger" value="' + json.vmlist[index][18] + '">Power Off</button>';
                                    var resetVM = '<button type="button" name="ResetVM" id="ResetVM" onClick="Reset_send(this)" class="btn btn-warning" value="' + json.vmlist[index][19] + '">ResetVM</button>';
                                    if(json.vmlist[index][20] == 'poweredOn'){
                                        var get_element_id = json.vmlist[index][21] + '1';
                                        var stat_message_id = 'status' + json.vmlist[index][22];
                                        document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
                                        document.getElementById(stat_message_id).innerHTML = json.vmlist[index][23];
                                        document.getElementById(get_element_id).innerHTML = on;
                                        document.getElementById(json.vmlist[index][24]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
                                    }else{
                                        var get_element_id = json.vmlist[index][25] + '1';
                                        var stat_message_id = 'status' + json.vmlist[index][26];
                                        document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
                                        document.getElementById(stat_message_id).innerHTML = json.vmlist[index][27];
                                        document.getElementById(get_element_id).innerHTML = off;
                                        document.getElementById(json.vmlist[index][28]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
                                    }
                                }

                            },
                            error : function(xhr,errmsg,err) {
                                console.log('Bad');
                                console.log(xhr.status + ": " + xhr.responseText);
                            }
                    });

}

A: Here is a simple example of table row filtering. I hope this helps.
You can try it out here: jsfiddle.
var $rows = $("#table tr"),
    $filter = $("#filter");

$("#filter").keyup(function () {
    var filterText = $filter.val().toLowerCase();
    $rows.each(function () {
        var $row = $(this);
        $row.toggle($row.text().toLowerCase().indexOf(filterText) > -1);
    });
});


text:
Q: Node.js Cluster to Process Data as Often As Possible Bear with me as I'm completely newb to cluster and the documentation isn't clicking with me.
if (cluster.isMaster)
{
  for (let i = 0; i < numCPUs; i++)
  {
    cluster.fork();
  }

  for (const file in files)
  {
    cluster.workers.send(file); //***
  }
}
else if (cluster.isWorker)
{
  process.on("message", (msg) =>
  {
    //...Process data here...
  });
}

*** is the sort of thing I want. Something like cluster.workers.send(...) that sends a message to the workers and whoever is not busy will take the message. If all workers are busy, then the message will wait to be sent until there's a free worker.

A: You need a database to manage the queue if you will have a large number of tasks and redis will be a good choice for this as Vinay Pandya suggests.
You want to prevent extra dependencies, you can use a queue array in the cluster master process and push/shift the tasks to/from that array. To determine the free node, you can maintain a 'nodes' object and have a feedback from the each node on finish its task to update it. Feedback can be done with process.send.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ HTTP Winsock: "Banned URL" at school, even websites that are permitted I'm fairly new to working with sockets and am working on one of my first projects; the first of which I actually fully intend to complete without any libraries.  I'm on Windows 7, using only WinAPI.
I'm working on it partially at school,and at my school they have a web filter, FortiGuard I believe.  Even when I try to GET a page at a domain that's allowed when I try to open it via a web browser, for example google.com, I'm returned the following message:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>The URL you requested has been blocked</title>

The URL you requested has been blocked

The page you have requested has been blocked, because the URL is banned.

URL = invalid

(I tried to break that up a bit).
As you can see it says the URL is banned, and I think that this is the web filter as this only happens when I'm at school
At least I believe I'm using a correct standard HTTP GET request to a website that works normally on a web browser, yet I'm receiving this message.  Am I doing anything wrong with the socket request?
Here's my socket code:
I have a basic "socket_t" structure to pass to all of my functions.  Here's the definition for that:
//custom socket structure
typedef struct
{
    //windows-specific
    struct sockaddr win_addr;
    u_long mode;
    SOCKET socket;//acutal SOCKET structure

    // General
    bool listening;//set to true if actively listening
    bool thread_terminate;//when boolean is set to true, listening thread terminates
    void (*error_callback) (int);
    http_response_t * response;
} socket_t;

for the connection:
//see socket_t definition in socket.h
//returns 0 on success, SOCKET_ERROR on WinSock failure, positive error code on DNS failure
int socket_connect(socket_t * sock, char * addr, int port)
{
    //bear in mind sock is the custom socket_t structure.  sock->socket is the actual SOCKET structure.
    //pardon the nomenclature.  rookie code.
    //TODO:  IPv6 support?

    //DNS lookup structures
    struct addrinfo *   res             = NULL;// Result of the getaddrinfo() call
    struct sockaddr *   sockaddr_v4     = NULL;// IPv4 sockaddr structure

    // So-called "hints" structure detailed in the getaddrinfo() MSDN page.
    // I guess it contains information for the DNS lookup.
    struct addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family     = AF_UNSPEC;
    hints.ai_socktype   = SOCK_STREAM;
    hints.ai_protocol   = IPPROTO_TCP;

    //Perform DNS lookup
    DWORD getaddrinfo_res = getaddrinfo(addr, "80\0", &hints, &res);//hardcode port number, for now
    if(getaddrinfo_res != 0) return getaddrinfo_res;

    //for each
    for(struct addrinfo * ptr = res; ptr != NULL; ptr = ptr->ai_next)
    {
        switch(ptr->ai_family)
        {
        case AF_INET:
            sockaddr_v4 = (struct sockaddr *) ptr->ai_addr;//set current address
            sock->win_addr = * sockaddr_v4;//set socket address
        }
    }

    //initialize actual SOCKET
    sock->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);// TCP/IP, stream-oriented, and TCP rather than UDP; respectively
    if(sock->socket == INVALID_SOCKET) return SOCKET_ERROR;

    //actual connection
    int connect_res = connect(sock->socket, &(sock->win_addr), sizeof(sock->win_addr));
    if(connect_res == SOCKET_ERROR) return SOCKET_ERROR;
    return 0;
}

And the HTTP request bit:
// Execute an HTTP request.
// Param 1: socket_t object
// Param 2: resource locator not including site name.
int socket_httprequest(socket_t * sock, char * rl)
{
    std::string str_req = std::string("GET /");
                str_req.append(rl);
                str_req.append(" HTTP/1.0\r\n");

                /*
                //user agent header
                str_req.append("User-Agent: conley-client/");
                str_req.append(VERSION);
                str_req.append("\r\n");
                */

                //final newline
                str_req.append("\r\n");

    const char * z_req = str_req.c_str();
    return send(sock->socket, z_req, (int) strlen(z_req), 0);
}

They are all called in the main function like so:
// Initialization
conley::init_sockets();
conley::init_http();

conley::socket_t * sock = conley::socket_alloc(err_callback);
int connect_res = conley::socket_connect(sock, "google.com\0", 80);
if(connect_res > 0) std::cout << "DNS ERR " << connect_res << std::endl;
if(connect_res < 0) std::cout << "CONNECT ERR " << WSAGetLastError() << std::endl;
if(connect_res == 0) std::cout << "Connected" << std::endl;

int httpreq_res = conley::socket_httprequest(sock, "\0");
if(httpreq_res != -1) std::cout << "HTTP request success: " << httpreq_res << " bytes sent" << std::endl;
else std::cout << "HTTP request failure: Error " << WSAGetLastError() << std::endl;

conley::socket_listen(sock);

Thank you for your time!

A: Probably the error is not caused by your program, but because the filter detects that the request is not send by a browser. Browsers send headers like user-agent to identify themselves to the server that they sent the request to. My  advise is to use a tool like Wireshark to capture the traffic generated by a browser and try to mimic it from you application.


text:
Q: Dafny: copy array region method validation I am working on a language comparison of several languages created with verification in mind (Whiley, Dafny and Frama-C etc.) I was given this example of a function which copied a region of one array to another array with different placement within the destination array. The specification I came up with looks like this in Dafny:
method copy( src: array<int>, sStart: nat, dest: array<int>, dStart: nat, len: nat)
    returns (r: array<int>)
  // both arrays cannot be null
   requires dest != null && src != null
  // Source array must contain enough elements to be copied
   requires src.Length >= sStart + len
  // Destination array must have enough space for copied elements
   requires dest.Length >= dStart + len
  // Result is same size as dest
  ensures r != null
  ensures r.Length == dest.Length
  // All elements before copied region are same
   ensures r[..dStart] == dest[..dStart]
  // All elements above copied region are same
   ensures r[dStart + len..] == dest[dStart + len..]
  // All elements in copied region match src
   ensures forall k: nat :: k < len ==> r[dStart + k] == src[sStart + k]

{
    if len == 0 { return dest; }
    assert len > 0;
    var i: nat := 0;
    r := new int[dest.Length];
    while (i < r.Length)
      invariant i <= r.Length
      decreases r.Length - i
      invariant r.Length == dest.Length
      invariant forall k: nat :: k < i ==> r[k] == dest[k]
    {
        r[i] := dest[i];
        i := i + 1;
    }
    assume r[..] == dest[..];
    i := 0;
    while (i < len)
      invariant i <= len
      decreases len - i
      invariant r.Length == dest.Length
      invariant r.Length >= dStart + i
      invariant src.Length >= sStart + i
      invariant r[..dStart] == dest[..dStart]
      invariant r[(dStart + len)..] == dest[(dStart + len)..]
      invariant forall k: nat :: k < i ==> r[dStart + k] == src[sStart + k]
    {
        r[dStart + i] := src[sStart + i];
        i := i + 1;
    }
}

In the second while loop above there may be some unneeded invariants as I have tried to cover everything I can think of. but, yeah, this doesn't verify and I am perplexed as to why...
Dafny/copy.dfy(35,4): Error BP5003: A postcondition might not hold on this return path.
Dafny/copy.dfy(17,11): Related location: This is the postcondition that might not hold.
Execution trace:
    (0,0): anon0
    (0,0): anon19_Else
    Dafny/copy.dfy(24,5): anon20_LoopHead
    (0,0): anon20_LoopBody
    Dafny/copy.dfy(24,5): anon21_Else
    (0,0): anon23_Then
    Dafny/copy.dfy(35,5): anon24_LoopHead
    (0,0): anon24_LoopBody
    Dafny/copy.dfy(35,5): anon25_Else
    (0,0): anon27_Then
Dafny/copy.dfy(43,16): Error BP5005: This loop invariant might not be maintained by the loop.
Execution trace:
    (0,0): anon0
    (0,0): anon19_Else
    Dafny/copy.dfy(24,5): anon20_LoopHead
    (0,0): anon20_LoopBody
    Dafny/copy.dfy(24,5): anon21_Else
    (0,0): anon23_Then
    Dafny/copy.dfy(35,5): anon24_LoopHead
    (0,0): anon24_LoopBody
    Dafny/copy.dfy(35,5): anon25_Else
    Dafny/copy.dfy(35,5): anon27_Else

Dafny program verifier finished with 1 verified, 2 errors

A: You can get it to verify by adding one more invariant
invariant r[dStart .. dStart + i] == src[sStart .. sStart + i]

As in:
while (i < len)
  invariant i <= len
  decreases len - i
  invariant r.Length == dest.Length
  invariant r.Length >= dStart + i
  invariant src.Length >= sStart + i
  invariant r[..dStart] == dest[..dStart]
  invariant r[(dStart + len)..] == dest[(dStart + len)..]
  invariant r[dStart .. dStart + i] == src[sStart .. sStart + i]
  invariant forall k: nat :: k < i ==> r[dStart + k] == src[sStart + k]

By the way, I think you can remove many of the invariants if you want to
method copy( src: array<int>, sStart: nat, dest: array<int>, dStart: nat, len: nat)
    returns (r: array<int>)
  // both arrays cannot be null
   requires dest != null && src != null
  // Source array must contain enough elements to be copied
   requires src.Length >= sStart + len
  // Destination array must have enough space for copied elements
   requires dest.Length >= dStart + len
  // Result is same size as dest
  ensures r != null
  ensures r.Length == dest.Length
  // All elements before copied region are same
   ensures r[..dStart] == dest[..dStart]
  // All elements above copied region are same
   ensures r[dStart + len..] == dest[dStart + len..]
  // All elements in copied region match src
   ensures forall k: nat :: k < len ==> r[dStart + k] == src[sStart + k]

{
    if len == 0 { return dest; }
    var i: nat := 0;
    r := new int[dest.Length];
    while (i < r.Length)
      invariant i <= r.Length
      invariant r[..i] == dest[..i]
    {
        r[i] := dest[i];
        i := i + 1;
    }

    i := 0;
    while (i < len)
      invariant i <= len
      invariant r[..dStart] == dest[..dStart]
      invariant r[(dStart + len)..] == dest[(dStart + len)..]
      invariant r[dStart .. dStart + i] == src[sStart .. sStart + i]
      {
        r[dStart + i] := src[sStart + i];
        i := i + 1;
    }
}


text:
Q: Position a Div Right Below A Div With a Responsive Image I have a div which has a responsive image in it that is full width.
The height of the image and width adjusts as the browser resizes.
I would like to position another div right below this div that has the responsive image.
I can't seem to get it right.
Here's what I have:

You can see the div I want to position below the responsive image has a background.
Thanks so much for your help!

A: It's hard to say for sure, but I think there's confusion here around the height and the responsiveness.
Firstly, the reason you get that big gap under your image is because it's parent div has min-height: 374px set on it.  The div will expand to fit the image's height, so this isn't really needed.
However, you also talk about how the height and width of the image should adjust when resizing.  To do that, you'll need to make sure the image has width: 100% so it is only ever as wide as it's parent div.
I've separated out your HTML and CSS, and added comments in the CSS to try and help.
Hopefully, it's close to what you wanted.
http://jsbin.com/orahuPEh/1/edit

A: Don't give the height of the image div, keep it height:auto, div will take image height. As you mention its responsive image than div will take height as per image height.

working Demo

A: If I am understanding your question right, your problem is that your divs are not butting up against each other properly. Is this correct?
Since you are obviously at the point where things aren't necessarily working right anyway,
I would start by setting the height of the img's parent div to the actual height of the image.
If this does not work use negative margin on either of the divs:
div style="margin-top:-30px;
Hope this helps, let me know if there is anything I can clarify.


text:
Q: How to convert a date type input to a timestamp I need to convert the date that I am getting from an HTML5 date input to a timestamp and save it as a variable.
HTML:
<form>

  <input type="date" id="date" name="maintenanace_date"/>

   <input type="time" id="time" name="maintenance_time" placeholder="EST"/>

</form>

A: var date = new Date(document.getElementById("time").value);
var timestamp = date.getTime();

If you need to use it in a serverside language like PHP, you also need to divide it by 1000.
However, this depends on the format the date is entered in. If you're using a non-default date format, you'll need to split it up and convert it into year, month and date before instantiating the Date object.


text:
Q: VIM search for pattern into quickfix Basically I need to create a quickfix buffer listing all lines that match a regex.  What is the best way?
The global command may not be the best, but I think it should be usable.  The output of the global command is perfect, but I need it to hyperlink the matching lines.

A: You can also not use the global command and stick with what is built-in.
Use the vimgrep command as below:
:vimgrep /pattern/ %

And then :copen or :cwindow

A: Use caddexpr:-
g/<pattern>/caddexpr expand("%") . ":" . line(".") . ":" . getline(".")


text:
Q: PF_RING userland compilation issue im trying to read incomming ethernet packets usign PF_RING. Here's my sample code. Even though i have pf_ring successfully installed, compiler gives an error as below.
/home/entc24/workspace/PFRing/Debug/../main.c:32: undefined reference to pfring_open'
/home/entc24/workspace/PFRing/Debug/../main.c:36: undefined reference topfring_recv'
what am i doing wrong here?
#include <pfring.h>
#include <stdio.h>
#include <net/ethernet.h>
#include <stdlib.h>

#define MSS 1500
#define ITR 1000
#define promisc 0

int main(){
    FILE *logfile;
    logfile=fopen("log.txt","w");
        if(logfile==NULL)
        {
            printf("Unable to create log.txt file.");
        }
    printf("Starting...\n");

    const char *device_name = "zc:eth0";
    int packet_size = 0;
    char *packet_buffer = (char*)malloc(MSS);
    struct pfring_pkthdr hdr;
    pfring *pfr =  pfring_open(device_name, promisc, 0);

    int iterator =0;
    while(iterator<ITR){
    packet_size =  pfring_recv(pfr, packet_buffer, MSS, &hdr,1);
    print_ethernet_header(packet_buffer,MSS,logfile);
    iterator++;
    }

    return 0;
}

void print_ethernet_header(unsigned char* Buffer, int Size,FILE* logfile)
{
    struct ethhdr *eth = (struct ethhdr *)Buffer;

    fprintf(logfile , "\n");
    fprintf(logfile , "Ethernet Header\n");
    fprintf(logfile , "   |-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_dest[0] , eth->h_dest[1] , eth->h_dest[2] , eth->h_dest[3] , eth->h_dest[4] , eth->h_dest[5] );
    fprintf(logfile , "   |-Source Address      : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_source[0] , eth->h_source[1] , eth->h_source[2] , eth->h_source[3] , eth->h_source[4] , eth->h_source[5] );
    fprintf(logfile , "   |-Protocol            : %u \n",(unsigned short)eth->h_proto);
}


text:
Q: what happens when i use malloc() twice in the same pointer? I write a code to split string by delimiter.
I want the function get a string and return its strings divided.
It actually works except for one thing.
when I give string "test", it works.
but when I give string "1234 4567", I can access the value '4567', but not '1234'. (garbage value.)
also "1234 2345 3456 ..." results garbage value in only first argument '1234'.
I thought that using malloc() twice causes problem in the same pointer, but it doesn't.
What is the problem for my codes?
char    **ft_set_char(char *str)
{
    int     i;
    int     j;
    int     k;
    char    *str_c;
    char    **ret;

    k = 0;
    j = 0;
    ret = (char **)malloc(10);
    str_c = (char *)malloc(5);
    i = 0;
    while (*(str + i) != '\0')
    {
        if (*(str + i) == ' ')
        {
            *(str_c + k) = '\0';
            k = 0;
            *(ret + j) = str_c;
            j++;
            i++;
            str_c = (char *)malloc(5);
        }
        *(str_c + k) = *(str + i);
        i++;
        k++;
    }
    *(str_c + k) = '\0';
    *(ret + j) = str_c;
    *(ret + j + 1) = NULL;
    return (ret);
}

A: ret = (char **)malloc(10);

That is not correct because it allocates 10 bytes and not 10 char * elements. It should be:
ret = malloc(10 * sizeof *ret);

Other unrelated issues but should be noted for best practice:

*

*Don't cast the result of malloc

*Don't use magic numbers like 10 and 5. For the former at least use a #define MAX_ARRAY_SIZE 10. For the latter, you can keep work out the exact size of the string to be copied from the original str - that will make your code more robust in case it is ever used with longer sub-strings.


text:
Q: Space of solutions of nonlinear Helmholtz equation on a torus On a unit torus $T^n$ (or equivalently, on $\mathbb{R}^n$ with periodic boundary conditions), the linear Helmholtz equation:
$\nabla^2 \phi + k^2 \phi=0$
will have no non-trivial solutions for generic values of $k$, while for special values of $k$ it will have a finite-dimensional vector space of solutions, with a basis of functions:
$\phi_m(x)=\exp(2\pi i m_j x^j)$
for each $n$-tuple of integers $m=(m_1,m_2,...m_n)$ such that:
$m_1^2+m_2^2+...+m_n^2=\left(\frac{k}{2\pi}\right)^2$
Now, consider a non-linear version of this problem, such as:
$\nabla^2 \phi + k^2 \phi + \lambda \phi^3=0$
still on $T^n$.  The solutions will no longer comprise a vector space, but rather a manifold.
My question is:  how can I determine the cardinality of the dimension of that manifold?  Will it again be zero-dimensional generically and finite for some special parameter values, or will the behaviour change?

A: Ignoring boundary conditions, the PDE has solutions $\phi = a\; \text{sn}\left(b x, c\right)$ where $\text{sn}$ is the Jacobi SN function (in Maple's parametrization: note that Mathematics uses a different convention),  ${a}^{2}=2\;{\dfrac {{b}^{2}-{k}^{2}}{\lambda}}$, ${c}^{2}={\dfrac {{k}^
{2}}{{b}^{2}}}-1$.  These are periodic in $x$, with a period depending on $b$ and $c$.  For any given $k$ and $\lambda$ (at least in some region) I believe there should be infinitely many values of $a,b,c$ for which the period divides $2 \pi$. For example, with $k=2$ and $\lambda=1$ I get a period dividing $2 \pi$ for $c = 2.722857918$, $3.502129242$, $4.303773851$, $5.116503598$, etc.  Of course we can replace $bx$ by $\sum_j b_j x^j$ with $\sum_j b_j^2 = b^2$.
EDIT:  We can think about it this way. Assume $k, \lambda > 0$.
By scaling $y$ and time $t$ we can non-dimensionalize the autonomous differential equation $\ddot{y} + k^2 y + \lambda y^3 = 0$ to $\ddot{y} +  y +  y^3 = 0$.
The phase-plane trajectories of this autonomous differential equation  are the closed curves $\dfrac{v^2}{2} + \dfrac{y^2}{2} + \dfrac{y^4}{4} = C$ for $C > 0$, where $v = dy/dt$.  The period $P$ is of the orbit through $(y=y_0, v=0)$ is, by symmetry, $4$ times the time needed to get from $(y_0,0)$ to $(0,\sqrt{ y_0^2 + y_0^4/2})$, and thus
$$ P = 4 \int_0^{y_0} \dfrac{dy}{\sqrt{ y_0^2 - y^2 +  y_0^4/2  - y^4/2}}$$
Under the change of variables $y = s y_0$ this becomes
$$ P = 4 \sqrt{2} \int_0^1 \dfrac{ds}{\sqrt{2 - 2 s^2 + y_0^2 - y_0^2 s^4}} $$
which goes to $0$ as $y_0 \to \infty$.


text:
Q: More efficient decodeAudioData()? I am using the web audio api to decode an n channel audio file into separate channels which are then rendered to a canvas to visually create a frequency meter.
I am using decodeAudioData to decode an array buffer of bytes to then assign to an audio buffer source node in a seperate function.
 // load the specified sound
function loadSound(url) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';

    // When loaded decode the data
    request.onload = function () {

        // decode the data
        context.decodeAudioData(request.response, function (buffer) {
            // when the audio is decoded play the sound
            holdingBuffer = buffer;
            setupSound(buffer);
        }, onError);
    }
    request.send();
}

The issue i am having is that when i attempt to decode audio of around 60mb +, the browser will crash due to a lack of memory space.The decodeAudioData function is extremely memory hungry!
I was wondering if anyone had any experience of more efficient ways of decoding larger audio files?

A: The issue is the amount of memory taken up by the decoded audio. Just for the sake of example, I'll assume your 60MB audio file is an MP3.
This obviously depends on bitrate, but let's say you're at 128kbps – which is fairly typical. That would mean you're loading something around an hour of stereo audio.
But the Web Audio API decodes to 32-bit and usually 44.1 or 48kHz (this depends on your sound card, from what I remember).
Anyway, let's say 32-bit at 48kHz.
That means each channel is 32 * 48000 bits per second. That's 32 * 48000 * 60 bits per minute, and 32 * 48000 * 60 * 60 bits for the whole hour. And of course we multiply by two, since we're assuming stereo.
That means 11059200000 total bits of audio data – which is a 1.3824GB audio buffer that needs to be loaded into memory. So, basically – that's a ton of memory.
There's really no easy answer here. You could try generating the waveforms/spectrographs/whatever on the server. Or you could try loading the audio file in chunks so that you can process them individually (in serial) and let things be garbage collected.
There might be other solutions, but those are the two that immediately came to mind.


text:
Q: How to add script to ASP.NET Core partial view properly? I am new to ASP.NET.
I needed to show a list of items. I made a partial view to represent each item. It works fine.
I needed to add a script in the partial view. So I created a new javascript file in wwwroot > js. Then referenced it from the partial view, like this:

And this is the javascript file:
var upbtn = document.getElementById("upbtn");
var dnbtn = document.getElementById("dnbtn");

upbtn.onclick = upbtn_click;
dnbtn.onclick = dnbtn_click;

function upbtn_click() {
    upbtn.children[0].children[0].style.fill = "green";
    dnbtn.children[0].children[0].style.fill = "gray"
}

function dnbtn_click() {
    upbtn.children[0].children[0].style.fill = "gray";
    dnbtn.children[0].children[0].style.fill = "green";
}

The problem is with the script. It only executes fot the first partial view, not for the others.
So, for the first partial view, when I click the buttons, I can see the changes. But for the rest of the partial views, they have no effect. What should I do to make the script work for all partial views?
The project is using ASP.NET Core.

A: The reason you are seeing your functions only get called for the first partial view is due to how that javascript code works and the fact that the same element id's and javascript is being repeated in each partial view.
For example, the first partial view gets rendered and your onclick events get hooked up for your two elements with id's "upbtn" and "dnbtn". When the second partial view gets rendered (and any others after that), that document.getElementById runs, and finds the first element with that id in the document, which will be that of the first partial. (also element id's should be unique throughout a page, so you should look at ways to get unique id's in repeated partial views after you get this working. I didn't add that to this answer so as to keep focused on this question/answer)
In order to get this working, you need to re-design how the elements in your partials are calling the js functions, and you can move the js out to the parent view or to a single shared js file for your site. Note I'm making some assumptions/estimates on html elements below since you did not share that code.

*

*For your upbtn/dnbtn elements, you can change them to something like below. The "buttonsParentElement" div is so we can get to the other btn elements children upon any click.

UP

DOWN

*Then update your js methods (again, not in the partial but either in the parent view, or a shared js file):

function upbtn_click(element) {
    element.children[0].children[0].style.fill = "green";

    var relatedDnBtn = element.closest("#buttonsParentElement").querySelector("#dnbtn");
    relatedDnBtn.children[0].children[0].style.fill = "gray"
}

function dnbtn_click(element) {
    var relatedUpBtn = element.closest("#buttonsParentElement").querySelector("#upbtn");
    relatedUpBtn.children[0].children[0].style.fill = "gray";

    element.children[0].children[0].style.fill = "green";
}


text:
Q: Delay when update constant in Redux I'm trying to update a constant using Redux in my React application. But there is a delay when my callback, handleChange is fired. It is logging the value before calling setFormValues. The react version is ^16.8.0 and  react-redux is 7.1.1
Login.jsx
  const [formValues, setFormValues] = useState({ email: ' ', password: ' ' });

  const handleChange = (e) => {
    const updatedValues = { password: '', email: e.target.value };
    setFormValues(updatedValues);
    console.log(formValues);
  };

A: formValues is a simple variable that was set upon the call to useState on the first line.  It will not change during this render iteration.
When handleChange is called, the console.log uses the formValues from that iteration.  Only after the next time the component is rendered will setState return a new value, and handleChange be re-created with the updated value.

A: If you are using React Hooks, which I think you are, you can use useEffect to log/manipulate the new value on each update, something like this:
import React, { useState, useEffect } from 'react';

...

const [formValues, setFormValues] = useState({ email: ' ', password: ' ' });

const handleChange = (e) => {
  const updatedValues = { password: '', email: e.target.value };
  setFormValues(updatedValues);
};

useEffect(() => {
  console.log(formValues);
});


text:
Q: How to get particular value from SqlCommand I want to store values of SqlCommand in string variable and print it on label. Here is my C# code
String sq="select fullname,emailId from Registration where RgId= '"+Session["RgId"]+"'";

SqlCommand cmd1 = new SqlCommand(sq, con);
con.Open();

SqlDataReader rdr = null;
rdr = cmd1.ExecuteReader();

while(rdr.Read())
{
    string fname = (string)rdr["fullname"];
    string femail=(string)rdr["emailId"];
    Label4.Text = fname;
    label5.Text=femail;
}

if(rdr!= null)
{
    rdr.Close();
}

con.Close();

but instead of printing value it doesn't show value on label. What to do? Is there anything wrong in code?

A: To make SQL queries, not concatenate a string, this is very dangerous for your system facilitating SQL injections.
Validate your values before attempting to query and validate the query returns.
if (Session["RgId"] != null && !String.IsNullOrEmpty(Session["RgId"].ToString()))
{
    String sq = "select fullname,emailId from Registration where RgId = @RgId";

    SqlCommand cmd1 = new SqlCommand(sq, con);
    cmd1.Parameters.Add("@RgId", Convert.ToInt32(Session["RgId"].ToString()));

    con.Open();

    SqlDataReader rdr = cmd1.ExecuteReader();

    if (rdr != null)
    {
        while (rdr.Read())
        {
            if (rdr["fullname"] != DBNull.Value && rdr["emailId"] != DBNull.Value)
            {
                Label4.Text = rdr["fullname"].ToString();
                label5.Text = rdr["emailId"].ToString();
            }
        }
    }

    if (rdr != null)
    {
        rdr.Close();
    }

    con.Close();
}

Regards,
Andrew

A: I would recommend using using statements when dealing with db access. Things get cleaned up better this way. Since your not using a try/catch in the code provided I would assume your using it in an outer layer or something so I would:
        if (Session["RgId"] == null)
            throw new NullReferenceException("RgId");

        using (var con = new SqlConnection())
        {
            const string sql = "select fullname,emailId from Registration where RgId = @RgId";

            using (var cmd1 = new SqlCommand(sql, con))
            {
                cmd1.Parameters.Add(new SqlParameter("RdId", SqlDbType.Int) {Value = Session["RgId"]});
                con.Open();
                using (var rdr = cmd1.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    if (rdr.Read())
                    {
                        Label4.Text = (string) rdr["fullname"];
                        label5.Text = (string) rdr["emailId"];
                    }
                    else
                    {
                        //handle registration not found
                    }
                    rdr.Close();
                }
            }
        }


text:
Q: qooxdoo error (qx.html is undefined) I am learning qooxdoo (which i think is awesome btw since i actually understand it).
Unfortunately, while following the twitter client tutorial, i ran into an error when i load the page.
After creating a new class file MainWindow.js

qx.Class.define("twitter.MainWindow",
{
    extend: qx.ui.window.Window,

    construct : function()
    {
        this.base(arguments, "Tweeter");
    }
});

I go to the Application.js class file and add

var main = new twitter.MainWindow();
    main.open();

which is supposed to let me see the small window.
After running generate.py source
i get this error in firebug

qx.html is undefined
[Break On This Error] return new qx.html.Element("div", styles, attributes);

I have tried running generate.py with source-all and even build but to no avail.
Can someone please help me, I really need to get started with this (I wasted two days trying to work with cappuccino and SproutCore... useless)
UPDATE
I solved the issue. Apparently, i was typing the window code outside the application class definition. In my defense, the tutorial said "add this to the end of the Application.js file"
so this

qx.Class.define("twitter.Application",
{
  extend : qx.application.Standalone,

  members :
  {
    main : function()
    {
      // Call super class
      this.base(arguments);

      // Enable logging in debug variant
      if (qx.core.Environment.get("qx.debug"))
      {
        qx.log.appender.Native;
        qx.log.appender.Console;
      }

    }
  }
});

var main = new twitter.MainWindow();
        main.open();

should should have been

qx.Class.define("twitter.Application",
{
  extend : qx.application.Standalone,

  members :
  {

    main : function()
    {
      // Call super class
      this.base(arguments);

      // Enable logging in debug variant
      if (qx.core.Environment.get("qx.debug"))
      {
        qx.log.appender.Native;
        qx.log.appender.Console;
      }

      var main = new twitter.MainWindow();
        main.open();
    }
  }
});

A: Very good, you solved it all by yourself :-). Yes, the tutorial text is ambiguous in this point, and I will file a bug to fix that.
In general, qooxdoo uses a "closed form" for its class definition. Every information pertaining to a specific class is in this one big map that is passed to qx.Class.define. The manual goes to some length explaining the various elements of a class definition, maybe you find that helpful (see e.g. here).
On the other hand, what you did first is perfectly legal JavaScript, so you didn't get any of the syntax errors that would cause the generator to exit right away. You should have seen a warning, though, in the generator output.


text:
Q: Out of order rendering of pixel shaders in opengl I working on some code to help measure and correct for the optical distortion in a head mounted display system. I am doing this by writing two pixel shaders (fragment shaders rendering on a full screen quad) one that generates diffrent test patterns and another that will apply a warp correction. (Right now the warp shader is just a temp pixel shader that rendeders a multicolored quad). My problem is that in my main rendering loop even thought I render the pattern shader quad first and then my dummy test warp shader the pattern shader always apears on top of the warp shader. My code in my main render loop looks like this:
 if (showPattern){
   glUseProgram(patternShader->shaderprog);
   //configure shader uniforms
   glBindVertexArray(patternShader->vao);
   glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
   glUseProgram(NULL);
 }

 if (doWarp){
   glUseProgram(warpShader->shaderprog);
   //configure shader uniforms
   glBindVertexArray(warpShader->vao);
   glDrawElements(GLddddd_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
 glUseProgram(NULL);
 }

If only showPattern is true then I get the expected output of the patternShader. Likewise if only doWarp is true I get the expected output of the warpShader. However if both are true I get the output of the patternShader on top of the warp shader not the other way around as I expected. If I switch the order of the if blocks I get the opposite effect which I want but I want to understand why it does not work like I think it should.


text:
Q: Virtualbox content in a external drive I bought a very old Toshiba laptop for hobby and I wanted to install Debian woody on it. Doing it physically is quiet cumbersome since you have to make a special bootable floppy disk so it would accept to boot up from CD drive, and then burn a compact disk (that's not the hard part).
I want to know if I can load the Debian Linux (woody) operating system I configured in VirtualBox onto the laptop's hard drive (I can connect it), or not.
Tl;Dr : Can I load the operating system content I made in Virtual box into an external hard drive and boot from it?

A: Yes, if the hardware is close enough (e.g. the VM should be configured with an IDE disk). A virtual machine in VirtualBox works more or less like a real machine, it has its own complete HDD image stored in the *.vdi file – you could use something like qemu-img to convert it to "raw image" format, then write the resulting image directly to the laptop's disk (e.g. over a USB IDE adapter).


text:
Q: $ES_X(p)$ of a Lognormal I have been trying to find the expected shortfall for $X \sim Lognormal(\mu, \sigma^2)$.  I have calculated the following;
$$
ES_X(p)=\frac{1}{p}\exp\left(\mu+\frac{\sigma^2}{2}\right)\left[1-\Phi\left(\Phi^{-1}(1-p)-\sigma\right)\right]
$$
However, when comparing my result to those I have found online it appears as though the expected shortfall is:
$$
ES_X(\alpha)=\frac{1}{\alpha}\exp\left(\mu+\frac{\sigma^2}{2}\right)\left[\Phi\left(\Phi^{-1}(\alpha)-\sigma\right)\right],
$$
where (I am fairly certain) $1-\alpha=p$.  To me it appears as though these two answers are different, and if that is indeed the case does anyone happen to know where I went wrong in my calculations. I can't seem to figure out why these two answers do not correspond.  For the record, the formula I am using is;
$$
ES_X(p)=\frac{E\left[X\mathbb{I}_{X>VaR_X(p)}\right]}{P(X>VaR_X(p))}=\frac{1}{p}\int\limits_{VaR_X(p)}^\infty xf(x;\mu,\sigma^2)dx
$$
where $f(x;\mu,\sigma^2)$ is the probability density function of a Lognormal distribution.

A: I believe I came across the reason for my confusion.  The solution I provided for the expected shortfall of a $Lognormal$ was under the assumption that $X$ was the loss for a portfolio.  Whereas the results I came across online were for $X$, a payoff portfolio.  I am fairly certain this is the cause for the slight discrepancies between the two solutions.


text:
Q: Tail-Call sum-of-squares-recursive function Racket I am trying to write a tail-call recursive function to find the sum of squares that are in a list. I have some code that works but currently, it is a non-tail-call function. How would I change it to be tailed?
(define sum-of-squares
  (lambda (lst)
    (if (null? lst)
        0
        (+ (* (car lst) (car lst)) (sumsquares (cdr lst)))
        )))

A: The usual way to convert a function that accumulates results to tail recursion is by moving the accumulator into a parameter. In the code below, the sum parameter accumulates the sums of squares.
(define sum-of-squares
  (lambda (lst)
    (define recursive-sos
      (lambda (lst sum)
        (if (null? lst)
            sum
            (recursive-sos (cdr lst)
                           (+ (* (car lst) (car lst))
                              sum)))))
    (recursive-sos lst 0)))


text:
Q: Overloaded methods that handle subclasses of some abstract class I have a generic Person class, and two types of people Student and Teacher that extends the Person class. I also have teaching sessions which  will store a list of students and a list of teachers that will be in that session.
class Person {}
class Student extends Person {}
class Teacher extends Person {}

class Session {
  List<Student> students = new ArrayList();
  List<Teacher> teachers = new ArrayList();

  // add a person to the teaching session.
  // They should be placed into the appropriate lists
  public void enroll(Person p)
  {
    if (p instanceof Student)
      students.add((Student) p)
    else if (p instanceof Teacher)
      teachers.add((Teacher) p)
  }
}

The idea is that some other code will have a list of people and iterate the list to enroll them into the appropriate sessions as needed. However, the enroll method currently explicitly checks the object's type, which to me is undesirable and seems like bad design.
I have tried writing the enroll method like this using method overloading, which looks a lot cleaner
public void enroll(Student p)
{
    students.add(p)
}

public void enroll(Teacher p)
{
    teachers.add(p)
}

but it seems like the code that iterates through the list of Person objects would need to then figure out whether the current person is a student or teacher instance, and type-cast appropriately before passing it to an enroll method.
Is there a way for me to design this so that I do not need to invoke instanceof at any point in time in my own code?

A: *

*Session needs to have an overloaded enroll method as in your question.

*Add an abstract enroll method to Person class that takes Session as a parameter
public abstract void enroll (Session s);

*Teacher and Student each override enroll
public void enroll (Session s) {
     s.enroll(this);
}

A: The simplest way to do this is to add an isTeacher() method to the person class.
Here is a basic implemention (with the parts you already wrote left out)
abstract class Person {
  public abstract boolean isTeacher();
}

class Teacher extends Person {
  public boolean isTeacher() { return true; }
}

class Student extends Person {
  public boolean isTeacher() {return false; }
}

abstract class Session {
  public void enroll(Person p) {
    if (p.isTeacher()) teachers.add((Teacher)p);
    else student.add((Student)p);
  }
}

If you also want to avoid the typecast, try this...
abstract class Person {
  public abstract Teacher asTeacher();
  public abstract Student asStudent();
}

class Student extends Person {
  public Student asStudent() { return this; }
  public Teacher asTeacher() { return null; }
}

class Teacher extends Person {
  public Student asStudent() { return null; }
  public Teacher asTeacher() { return this; }
}

class Session extends Person {
  public void enroll(Person p) {
    Teacher t = p.asTeacher();
    if (t != null) teachers.add(t);
    else students.add(p.asStudent());
  }
}

This implementation has a minor weakness that it assumes Teachers and Students are the only types of people, but extending it to multiple types is fairly straightforward.

A: The issue with p instanceof Student is that you change the behavior based on something that is not a method invocation, so future changes will be hard (ie. if you add another sub-class of Person).
There are a couple of ways to look at this design problem:

*

*Why you need to create a hierarchy of Person? It's possible in your system that someone that is a student can be a teacher in another course? If that is the case, you have some information about a person, and what changes is the role of that person for a course. So is not convenient to use inheritance for that, use composition and create an object that represents the role of a Person in a course.

*You can add a isTeacher method, or use a visitor pattern to split the collection. That will be a little bit better than the instanceof. But in my opinion the problem is still in the incorrect class hierarchy.
For example, using "roles":
enum Role { TEACHER, STUDENT; }

class Session {
   List<SessionEnrolment> enrollments = new ArrayList<>();

   public void enroll(Person p, Role role)
   {
       enrollments.add(new SessionEnrollment(p, role));
   }

   public List<Person> getTeachers() {
      List<Person> result = new ArrayList<>();
      for (SessionEnrolment e : enrollments) {
            if (e.isTeacher()) { result.add(e.getPerson()); }
            return result;
      }
   }
}

Using a isTeacher method:
public void enroll(Person p)
{
    if (p.isTeacher()) { teachers.add(p); } else { students.add(p); }
}

As you can see having a isTeacher method for all persons looks awkward. And the role solution reflects better the temporal property of being a student or teacher.
You can use a visitor, and it will save you from the ugly isTeacher in Person; but to me that solution is overcomplicated, and you'll translate the "uglyness" to the Visitor interface.

A: You can do what you propose with an overloaded method per concrete Person implementation, and in addition to that add a Type to the List:
List<Student> students = new ArrayList<>();
List<Teacher> teachers = new ArrayList<>();

Then in your iteration logic you know the type.

A: You can turn it around:
class Session {
  StudentList students = new StudentList();
  TeacherList teachers = new TeacherList();

  // add a person to the teaching session.
  // They should be placed into the appropriate lists
  public void enroll(Person p)
  {
     p.addMe(students, teachers);
  }
}

public class StudentList extends ArrayList<Student> {
}

public class TeacherList extends ArrayList<Teacher> {
}

public abstract class Person {
    public abstract void addMe(StudentList sList, TeacherList tList);
}

public class Student extends Person {
    public void addMe(StudentList sList, TeacherList tList) {
        sList.add(this);
    }
}

public class Teacher extends Person {
    public void addMe(StudentList sList, TeacherList tList) {
        tList.add(this);
    }
}


text:
Q: Pandas merge multiple dataframes on one temporal index, with latest value from all others I'm merging some dataframes which have a time index.
import pandas as pd
df1 = pd.DataFrame(['a', 'b', 'c'],
    columns=pd.MultiIndex.from_product([['target'], ['key']]),
    index = [
        '2022-04-15 20:20:20.000000',
        '2022-04-15 20:20:21.000000',
        '2022-04-15 20:20:22.000000'],)
df2 = pd.DataFrame(['a2', 'b2', 'c2', 'd2', 'e2'],
    columns=pd.MultiIndex.from_product([['feature2'], ['keys']]),
    index = [
        '2022-04-15 20:20:20.100000',
        '2022-04-15 20:20:20.500000',
        '2022-04-15 20:20:20.900000',
        '2022-04-15 20:20:21.000000',
        '2022-04-15 20:20:21.100000',],)
df3 = pd.DataFrame(['a3', 'b3', 'c3', 'd3', 'e3'],
    columns=pd.MultiIndex.from_product([['feature3'], ['keys']]),
    index = [
        '2022-04-15 20:20:19.000000',
        '2022-04-15 20:20:19.200000',
        '2022-04-15 20:20:20.000000',
        '2022-04-15 20:20:20.200000',
        '2022-04-15 20:20:23.100000',],)

then I use this merge procedure:
def merge(dfs:list[pd.DataFrame], targetColumn:'str|tuple[str]'):
    from functools import reduce
    if len(dfs) == 0:
        return None
    if len(dfs) == 1:
        return dfs[0]
    for df in dfs:
        df.index = pd.to_datetime(df.index)
    merged = reduce(
        lambda left, right: pd.merge(
            left,
            right,
            how='outer',
            left_index=True,
            right_index=True),
        dfs)
    for col in merged.columns:
        if col != targetColumn:
            merged[col] = merged[col].fillna(method='ffill')
    return merged[merged[targetColumn].notna()]

like this:
merged = merge([df1, df2, df3], targetColumn=('target', 'key'))

which produces this:

And it all works great. Problem is efficiency - notice in the merge() procedure I use reduce and an outer merge to join the dataframes together, this can make a HUGE interim dataframe which then gets filtered down. But what if my pc doesn't have enough ram to handle that huge dataframe in memory? well that's the problem I'm trying to avoid.
I'm wondering if there's a way to avoid expanding the data out into a huge dataframe while merging.
Of course a regular old merge isn't sufficient because it only merges on exactly matching indexes rather than the latest temporal index before the target variable's observation:
df1.merge(df2, how='left', left_index=True, right_index=True)

Has this kind of thing been solved efficiently? Seems like a common data science issue, since no one wants to leak future information into their models, and everyone has various inputs to merge together...

A: You're in luck: pandas.merge_asof does exactly what you need!
We use the default direction='backward' argument:

A "backward" search selects the last row in the right DataFrame whose
'on' key is less than or equal to the left's key.

Using your three example DataFrames:
import pandas as pd
from functools import reduce

# Convert all indexes to datetime
for df in [df1, df2, df3]:
    df.index = pd.to_datetime(df.index)

# Perform as-of merges
res = reduce(lambda left, right:
             pd.merge_asof(left, right, left_index=True, right_index=True),
             [df1, df2, df3])

print(res)

                    target feature2 feature3
                       key     keys     keys
2022-04-15 20:20:20      a      NaN       c3
2022-04-15 20:20:21      b       d2       d3
2022-04-15 20:20:22      c       e2       d3

A: Here's some code that works for your example. I'm not sure about more general cases of multi-indexed columns, but in any event it contains the basic ideas for merging on a single temporal index.
merged = df1.copy(deep=True)
for df in [df2, df3]:
    idxNew = df.index.get_indexer(merged.index, method='pad')
    idxMerged = [i for i, x in enumerate(idxNew) if x != -1]
    idxNew = [x for x in idxNew if x != -1]
    n = len(merged.columns)
    merged[df.columns] = None
    merged.iloc[idxMerged,n:] = df.iloc[idxNew,:].set_index(merged.index[idxMerged])
print(merged)

Output:
                           target feature2 feature3
                              key     keys     keys
2022-04-15 20:20:20.000000      a     None       c3
2022-04-15 20:20:21.000000      b       d2       d3
2022-04-15 20:20:22.000000      c       e2       d3


text:
Q: Drawing graph in python3 with data enclosed in list I used function 'plt.bar' to draw graph about sum of dice twice thrown.
and it's value exist from 2 to 12.
Since function plt.bar use index of value in list for its X-axis, graph goes wrong.
How can I change value of X-axis?
Graph


text:
Q: Compute weighted summation of matrix power (matrix polynomial) in Matlab Given an nxn matrix A_k and a nx1 vector x, is there any smart way to compute

using Matlab? x_i are the elements of the vector x, therefore J is a sum of matrices. So far I have used a for loop, but I was wondering if there was a smarter way.

A: Short answer: you can use the builtin matlab function polyvalm for matrix polynomial evaluation as follows:
x = x(end:-1:1); % flip the order of the elements
x(end+1) = 0; % append 0
J = polyvalm(x, A);

Long answer: Matlab uses a loop internally. So, you didn't gain that much or you perform even worse if you optimise your own implementation (see my calcJ_loopOptimised function):
% construct random input
n = 100;
A = rand(n);
x = rand(n, 1);

% calculate the result using different methods
Jbuiltin = calcJ_builtin(A, x);
Jloop = calcJ_loop(A, x);
JloopOptimised = calcJ_loopOptimised(A, x);

% check if the functions are mathematically equivalent (should be in the order of `eps`)
relativeError1 = max(max(abs(Jbuiltin - Jloop)))/max(max(Jbuiltin))
relativeError2 = max(max(abs(Jloop - JloopOptimised)))/max(max(Jloop))

% measure the execution time
t_loopOptimised = timeit(@() calcJ_loopOptimised(A, x))
t_builtin = timeit(@() calcJ_builtin(A, x))
t_loop = timeit(@() calcJ_loop(A, x))

% check if builtin function is faster
builtinFaster = t_builtin < t_loopOptimised

% calculate J using Matlab builtin function
function J = calcJ_builtin(A, x)
  x = x(end:-1:1);
  x(end+1) = 0;
  J = polyvalm(x, A);
end

% naive loop implementation
function J = calcJ_loop(A, x)
  n = size(A, 1);
  J = zeros(n,n);
  for i=1:n
    J = J + A^i * x(i);
  end
end

% optimised loop implementation (cache result of matrix power)
function J = calcJ_loopOptimised(A, x)
  n = size(A, 1);
  J = zeros(n,n);
  A_ = eye(n);
  for i=1:n
    A_ = A_*A;
    J = J + A_ * x(i);
  end
end

For n=100, I get the following:
t_loopOptimised = 0.0077
t_builtin       = 0.0084
t_loop          = 0.0295

For n=5, I get the following:
t_loopOptimised = 7.4425e-06
t_builtin       = 4.7399e-05
t_loop          = 1.0496e-04

Note that my timings fluctuates somewhat between different runs, but the optimised loop is almost always faster (up to 6x for small n) than the builtin function.


text:
Q: How to observe Firebase changes in Flutter using StreamBuilder I am trying to observe Firebase collection changes. In the first run, Listview is not building. After changing data on Firebase, then listview is rendered properly but previous snapshot is used because I see my old data on the screen.
Any idea to find the error?
@override
  Widget build(BuildContext context) {
    return BlocListener<VoteCubit, VoteState>(
      listener: (context, state) {
        if (state.status == FormStatus.success) {
          print("Success");
        } else if (state.status == FormStatus.inprogress) {
          print("In progress");
        } else if (state.status == FormStatus.fail) {
          print("fail");
        } else {
          print("Empty Area");
        }
      },
      child: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('liveSurvey').snapshots(),
        builder: (context, snapshot) {
          final voteCubit = context.read<VoteCubit>();
          final voteState = voteCubit.state;
          if (snapshot.hasData) {
            voteCubit.getAllRooms(snapshot);
            print("Here");
            return ListView.builder(
              itemCount: voteState.rooms.length,
              itemBuilder: (context, i) {
                print("Inside Listview");
                . . .

A: Use stream builder like this for real time data.
child: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collection("travellers/India/details")
            .where(
              'firestore_id',
              isEqualTo: widget.get_firestore_id,
            )
            .snapshots(),
        builder:
            (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

if (snapshot.connectionState == ConnectionState.waiting) {
    print('play lodader')
}else if (snapshot.hasData) {
print('your_ui_here')
}


text:
Q: Compiler Errors-NSMutableDictionary for MultiTouchEvents I'm trying to use an NSMutableDictionary to store the X and Y values of 4 touches, as shown in Apple's Event Handling Guide (http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/Introduction/Introduction.html)
My code is:
- (void)cacheBeginPointForTouches:(NSSet *)touches {
if ([touches count] > 0) {
    for (UITouch *touch in touches) {
        CGPoint *point = (CGPoint *)CFMutableDictionaryGetValue(_TouchesDict, touch);
        if (point == NULL) {
            point = (CGPoint *)malloc(sizeof(CGPoint));
            CFDictionarySetValue(_TouchesDict, touch, point);
        }
        *point = [touch locationInView:_view.superview];
    }
}
}

However, I keep getting compiler errors such as this:
Undefined symbols for architecture i386:
  "_CFMutableDictionaryGetValue", referenced from:
  -[ViewController cacheBeginPointForTouches:] in ViewController.o
  "_OBJC_IVAR_$_UIViewController._view", referenced from:
  -[ViewController cacheBeginPointForTouches:] in ViewController.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Does anyone have any suggestions for what I may be doing wrong?
Thanks!

A: replace CFMutableDictionaryGetValue by CFDictionaryGetValue.
the CFMutableDictionaryGetValue function seems strange to me. I think it does not exist


text:
Q: How to get smooth transitions in pure JavaScript and CSS? I have div elements with a black background-color that get and loose the class animated that has an css definition for an animated colored background. The animation is working smooth. But the change from the black to the animated state and back are not. I tried some transition rules but I can not figure out how to get a smooth change.
Here is my minimal example:

let randomNumber;
let boxes = document.querySelectorAll(".dark");
let randomNumbers = [];
let milliseconds = 2000;
setInterval(function() {
  randomNumber = Math.floor(Math.random() * boxes.length);
  randomNumbers.push(randomNumber);
  boxes[randomNumber].className = boxes[randomNumber].className.replace(/(?:^|\s)dark(?!\S)/g, " animated");
  setTimeout(function() {
    boxes[randomNumbers[0]].className = boxes[randomNumbers[0]].className.replace(/(?:^|\s)animated(?!\S)/g, " dark");
    randomNumbers.shift();
  }, boxes.length * milliseconds);
}, milliseconds);
@keyframes animated_background_color {
  0% {
    background-color: #e66000;
  }
  25% {
    background-color: #ff9500;
  }
  50% {
    background-color: #ffcb00;
  }
  75% {
    background-color: #ff9500;
  }
  100% {
    background-color: #e66000;
  }
}

.box {
  height: 20px;
  margin-bottom: 4px;
  width: 20px;
}

.dark {
  background-color: black;
}

.animated {
  animation-name: animated_background_color;
  animation-duration: 3s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  background-color: #e66000;
}
<!DOCTYPE html>

  <title>Animation</title>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

A: Your starting and ending colors are not black, that's one reason why you see a shift. replace your 0% and 100% values by background-color: black;.
Once this problem is fixed, you will have a problem with your milliseconds variable because it's not a divider of your animation time (here 5*2000ms, which means the .animated class remove the class at 10s when your animation cycle is 3s)

Bonus: I have no idea why I cleaned and modified your code but I did it. (I'm tired and it was ugly)

const DARK_SELECTOR = ".dark";
const DARK_CLASS = "dark";
const ANIMATED_CLASS = "animated";
const ANIMATION_CYCLE_TIME = 2000;
const TOTAL_ANIMATION_TIME = 3 * ANIMATION_CYCLE_TIME;
const TIME_BETWEEN_ANIMATIONS = 1.5 * ANIMATION_CYCLE_TIME;

function animateRandomBox(animationTime) {
  const darkBoxes = document.querySelectorAll(DARK_SELECTOR);
  const numberOfDarkBoxes = darkBoxes.length;
  if (numberOfDarkBoxes === 0) {
    return;
  }
  const randomBoxNumber = Math.floor(Math.random() * numberOfDarkBoxes);
  const randomBoxClass = darkBoxes[randomBoxNumber].classList;
  randomBoxClass.remove('dark');
  randomBoxClass.add('animated');
  setTimeout(() => {
    randomBoxClass.add('dark');
    randomBoxClass.remove('animated');
  }, animationTime);
}

setInterval(() => animateRandomBox(TOTAL_ANIMATION_TIME), TIME_BETWEEN_ANIMATIONS);
@keyframes animated_background_color {
  0% {
    background-color: #000;
  }
  25% {
    background-color: #ff9500;
  }
  50% {
    background-color: #ffcb00;
  }
  75% {
    background-color: #ff9500;
  }
  100% {
    background-color: #000;
  }
}

body {
  display: grid;
  grid-auto-rows: min-content;
  row-gap: 0.25rem;
}

.box {
  height: 1rem;
  width: 1rem;
  border-radius: 0.5rem;
}

.dark {
  background-color: black;
}

.animated {
  animation-name: animated_background_color;
  animation-duration: 2s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}
<!DOCTYPE html>

  <title>Animation</title>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

A: According to the comment of devdgehog, I decided to add more keyframes. Now I switch from the dark state to the animated state and back again with the first and last keyframe setting the dark background and the other keyframes switching from orange to bright orange to yellow to bright orange to orange three times in a row.

const DARK_SELECTOR = ".dark";
const DARK_CLASS = "dark";
const ANIMATED_CLASS = "animated";
const ANIMATION_CYCLE_TIME = 6000;

function animateRandomBox(animationTime) {
  const darkBoxes = document.querySelectorAll(DARK_SELECTOR);
  const numberOfDarkBoxes = darkBoxes.length;
  if (numberOfDarkBoxes === 0) {
    return;
  }
  const randomBoxNumber = Math.floor(Math.random() * numberOfDarkBoxes);
  const randomBoxClass = darkBoxes[randomBoxNumber].classList;
  randomBoxClass.remove('dark');
  randomBoxClass.add('animated');
  setTimeout(() => {
    randomBoxClass.add('dark');
    randomBoxClass.remove('animated');
  }, animationTime);
}

setInterval(() => animateRandomBox(ANIMATION_CYCLE_TIME), ANIMATION_CYCLE_TIME);
@keyframes animated_background_color {
  0% {
    background-color: #000;
  }
  12% {
    background-color: #ff9500;
  }
  25% {
    background-color: #ffcb00;
  }
  37% {
    background-color: #ff9500;
  }
  50% {
    background-color: #ffcb00;
  }
  62% {
    background-color: #ff9500;
  }
  75% {
    background-color: #ffcb00;
  }
  87% {
    background-color: #ff9500;
  }
  100% {
    background-color: #000;
  }
}

body {
  display: grid;
  grid-auto-rows: min-content;
  row-gap: 0.25rem;
}

.box {
  height: 1rem;
  width: 1rem;
  border-radius: 0.5rem;
}

.dark {
  background-color: black;
}

.animated {
  animation-name: animated_background_color;
  animation-duration: 6s;
  animation-timing-function: linear;
}
<!DOCTYPE html>

  <title>Animation</title>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />


text:
Q: Do modern C++ compilers inline functions which are called exactly once? As in, say my header file is:
class A
{
    void Complicated();
}

And my source file
void A::Complicated()
{
    ...really long function...
}

Can I split the source file into
void DoInitialStuff(pass necessary vars by ref or value)
{
    ...
}
void HandleCaseA(pass necessary vars by ref or value)
{
    ...
}
void HandleCaseB(pass necessary vars by ref or value)
{
    ...
}
void FinishUp(pass necessary vars by ref or value)
{
    ...
}
void A::Complicated()
{
    ...
    DoInitialStuff(...);
    switch ...
        HandleCaseA(...)
        HandleCaseB(...)
    ...
    FinishUp(...)
}

Entirely for readability and without any fear of impact in terms of performance?

A: Depends on aliasing (pointers to that function) and function length (a large function inlined in a branch could throw the other branch out of cache, thus hurting performance).
Let the compiler worry about that, you worry about your code :)

A: A complicated function is likely to have its speed dominated by the operations within the function; the overhead of a function call won't be noticeable even if it isn't inlined.
You don't have much control over the inlining of a function, the best way to know is to try it and find out.
A compiler's optimizer might be more effective with shorter pieces of code, so you might find it getting faster even if it's not inlined.

A: You should mark the functions static so that the compiler know they are local to that translation unit.
Without static the compiler cannot assume (barring LTO / WPA) that the function is only called once, so is less likely to inline it.
Demonstration using the LLVM Try Out page.
That said, code for readability first, micro-optimizations (and such tweaking is a micro-optimization) should only come after performance measures.

Example:
#include <cstdio>

static void foo(int i) {
  int m = i % 3;
  printf("%d %d", i, m);
}

int main(int argc, char* argv[]) {
  for (int i = 0; i != argc; ++i) {
    foo(i);
  }
}

Produces with static:
; ModuleID = '/tmp/webcompile/_27689_0.bc'
target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64"
target triple = "x86_64-unknown-linux-gnu"

@.str = private constant [6 x i8] c"%d %d\00"     ; <[6 x i8]*> [#uses=1]

define i32 @main(i32 %argc, i8** nocapture %argv) nounwind {
entry:
  %cmp4 = icmp eq i32 %argc, 0                    ; <i1> [#uses=1]
  br i1 %cmp4, label %for.end, label %for.body

for.body:                                         ; preds = %for.body, %entry
  %0 = phi i32 [ %inc, %for.body ], [ 0, %entry ] ; <i32> [#uses=3]
  %rem.i = srem i32 %0, 3                         ; <i32> [#uses=1]
  %call.i = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([6 x i8]* @.str, i64 0, i64 0), i32 %0, i32 %rem.i) nounwind ; <i32> [#uses=0]
  %inc = add nsw i32 %0, 1                        ; <i32> [#uses=2]
  %exitcond = icmp eq i32 %inc, %argc             ; <i1> [#uses=1]
  br i1 %exitcond, label %for.end, label %for.body

for.end:                                          ; preds = %for.body, %entry
  ret i32 0
}

declare i32 @printf(i8* nocapture, ...) nounwind

Without static:
; ModuleID = '/tmp/webcompile/_27859_0.bc'
target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64"
target triple = "x86_64-unknown-linux-gnu"

@.str = private constant [6 x i8] c"%d %d\00"     ; <[6 x i8]*> [#uses=1]

define void @foo(int)(i32 %i) nounwind {
entry:
  %rem = srem i32 %i, 3                           ; <i32> [#uses=1]
  %call = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([6 x i8]* @.str, i64 0, i64 0), i32 %i, i32 %rem) ; <i32> [#uses=0]
  ret void
}

declare i32 @printf(i8* nocapture, ...) nounwind

define i32 @main(i32 %argc, i8** nocapture %argv) nounwind {
entry:
  %cmp4 = icmp eq i32 %argc, 0                    ; <i1> [#uses=1]
  br i1 %cmp4, label %for.end, label %for.body

for.body:                                         ; preds = %for.body, %entry
  %0 = phi i32 [ %inc, %for.body ], [ 0, %entry ] ; <i32> [#uses=3]
  %rem.i = srem i32 %0, 3                         ; <i32> [#uses=1]
  %call.i = tail call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([6 x i8]* @.str, i64 0, i64 0), i32 %0, i32 %rem.i) nounwind ; <i32> [#uses=0]
  %inc = add nsw i32 %0, 1                        ; <i32> [#uses=2]
  %exitcond = icmp eq i32 %inc, %argc             ; <i1> [#uses=1]
  br i1 %exitcond, label %for.end, label %for.body

for.end:                                          ; preds = %for.body, %entry
  ret i32 0
}

A: If you split up your code into logical groupings the compiler will do what it deems best: If it's short and easy, the compiler should inline it and the result is the same. If however the code is complicated, making an extra function call might actually be faster than doing all the work inlined, so you leave the compiler the option to do that too. On top of all that, the logically split code can be far easier for a maintainer to grok and avoid future bugs.

A: I suggest you create a helper class to break your complicated function into method calls, much like you were proposing, but without the long, boring and unreadable task of passing arguments to each and every one of these smaller functions. Pass these arguments only once by making them member variables of the helper class.
Don't focus on optimization at this point, make sure your code is readable and you'll be fine 99% of the time.


text:
Q: How to add reference to Visual project with NuGet package?
I'd like to add a dll to my nuget package... In fact I don't want it to be "added" but just "referenced".
I don't want this file to be copied into the project where I install my package, I just want to add a reference that point to the dll file store into an other folder in my PC or a shared folder.
I'm a real beginner in powershell so I don't really know if I can do that with it...
I tried to use dll.refresh files but it seems it's not the good way to do in Visual Studio 2013.
I also tried to specify my external path in a file tag in the nuspec file, but it seems it's not possible to reference a dll without copying it...
I looked for Powershell scripts to help me but nothing does what I want to do.

Thanks for your help!

A: Well, I'll answer my own question.
After digging a bit more into Powershell, here is the way to do that:
install.ps1:
param($installPath, $toolsPath, $package, $project)

$newRef = $project.Object.References.Add("PathToMyDLL");

uninstall.ps1:
param($installPath, $toolsPath, $package, $project)

Remove-LibraryReference  $project.Name MyDLLName


text:
Q: Are there higher dimensional equivalents of the Witt Algebra? The Witt algebra can be defined by:
$$L_n = -x^{n+1}\frac{d}{dx}$$
Giving the rules:
$$[L_n,L_m] = (n-m)L_{n+m}$$
And there is a central extension called the Virasoro algebra which has a more complicated representation.
It seems fairly straight forward to extend this into a higher dimensions, D. e.g. with $n$ and $x$ d-dimensional vectors:
$$L_{n} = -\prod\limits_{i=1}^d(x_i)^{n_i}\sum_{\mu=1}^dx_\mu\frac{\partial}{\partial x_\mu}$$
in which case the rules would be:
$$[L_n,L_m] = \sum_{i=1}^d (n_i-m_i)L_{n+m}$$
I was wondering if there is any use to higher dimensional Witt algebras, and whether they can have central extensions?


text:
Q: Conditional validation not firing Using a gem for validating date overlap, the attempt is to verify against existing records whether the new records overlaps for non-cancelled records. The class has attribute cancelled as boolean, default: false.
It appears the following syntax is erroneous as the application rollsback when hitting and existing cancelled object.
validates :start_time, :end_time, :overlap => {:scope => "instructor_id", :exclude_edges => ["start_time", "end_time"]}, if: -> {cancelled == false || require_validation}

what is the proper way to do this under rails 4.2 ?
Update
following the gem's conventions
validates :start_time, :end_time, :overlap => {:query_options => {:cancelled => nil}, :scope => "instructor_id", :exclude_edges => ["start_time", "end_time"]}
scope :cancelled, -> { where(:cancelled => false) }

does not fire either.


text:
Q: Upgrade to FirebaseCrashlytics and 'No such module FirebaseCrashlytics' I am trying to upgrade to FirebaseCrashlytics from Crashlytics. I am able to import Firebase but not FirebaseCrashlytics. Here is my podfile:
platform :ios, :deployment_target => "9.0"

def shared_pods
pod 'Firebase/Crashlytics'
pod 'Firebase/Analytics'
pod 'SVProgressHUD'
pod 'IGHTMLQuery'
pod 'OpenTok', '~>  2.16.3'

end

target 'MyApp' do
  #use_frameworks!

  shared_pods
end

I cannot uncomment use_frameworks! since it breaks other pods I am already using.
My bridging header:
#import "FirebaseCrashlytics/FirebaseCrashlytics.h"
#import "FirebaseCore/FirebaseCore.h"

This is what I am getting:

A: According to the firebase docs then you just have to import Firebase, not FirebaseCrashlytics.
https://firebase.google.com/docs/crashlytics/get-started?platform=ios

A: If you're using it as a Swift framework then make sure you add it to your target's Frameworks, Libraries, and Embedded Content


text:
Q: How to avoid concurrent operations(save/delete) in file operation I have met a question and need help.
I am designing a simple file service(Http), with which user can upload/download files, as well as deleting files in the file server.
The file service will store files in a single linux computer, under a parent folder(e.g. /data/fileserver/). An uploaded file(e.g. xxx.mp4) may be saved with the path in computer like /data/fileserver/demo/1/xxx.mp4.
The question is that:
How to avoid concurrent operations(save/delete) in this file service?
e.g.
User A is uploading file xxx.mp4 and file service is saving(haven't finished) it with path /data/fileserver/demo/1/xxx.mp4.
At the same time, user B call delete api of this file service to delete the folder /data/fileserver/demo. This delete operation will affect the save operation of User A.
I hope in this case the delete operation of User B will fail.
The model seems to lock branch of a tree, but I don't know how to handle.
The file server is based on java language.
Thanks.

A: Since HTTP may be asynchronous, I'd use a design pattern approach.
For instance, you may implement a singleton which handles operations over a determined path.
Let's suppose you don't want the 'fileserver' folder to have any change before the completion of any kind of operation.
Implement a map with the key as the foldername and the value as true or false (meaning on operation or not)
Seems like a simple solution.


text:
Q: Replace all values in tensor greater than zero I have a tensor X. If I just want to keep all values larger than zero I can use
X = tf.nn.relu(X)
But what do I do in the opposite case? I only can think of this solution:
X = tf.multiply(-1.0, tf.nn.relu(tf.multiply(-1.0, X)))
I wondered if there is a more sophisticated way to do that.
Any suggestions?

A: So you want to keep all the values less than zero. You can reverse the relu operation and use tf.minimum(X, 0) which "returns the min of x and y (i.e. x < y ? x : y) element-wise" and supports broadcasting, doc.


text:
Q: Merge nested objects in one list using Linq I have those two clases:
public class A
{
    public List<B> child { get; set; }
}

public class B
{
    public string Name {get; set;}
}

I want to get in just one List of objects from class "B",  which has the same name, so I did this:
IEnumerable<List<B>> result = manyA.Select<A, List<B>>(a => a.child.Where(b => b.Name == name).ToList());

But this is a List of List, and i would like to have just one list. Can I do this with Linq?

A: manyA.SelectMany(a => a.child)
     .Where(b => b.Name == name)
     .ToList();


text:
Q: requiring using /var/www works but using localhost doesnt work I am new to working on linux environment and i am also working on a php project on linux. And I faced a problem while requiring php files. I have two php files called test.php and database.php. Both this files are in /var/www/TEST/.
This the code in database.php
<?php echo("You have included the database");  ?>
And this is the code in test.php
<?php require("/var/www/TEST/database.php");?>

Then when i browse to test.php using firefox i get the expected output "you have included the database". but when I change test.php to
<?php require("localhost/TEST/database.php"); ?>

I get no out put when I browse to test.php. I have started the apache service and also changed the file access of /var/www/ to 755. I hope you could help me on why I am getting this kind of result. Thank you.

A: First you should enable error reporting:
<?php
// Put these lines to the top of your script
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('display_startup_errors', true);
ini_set('xmlrpc_errors', true);

Then you try to include a file via HTTP stream, but you forgot http:// or https:// before  localhost and including via stream is  disabled for security reason.
The configuration is allow_url_include. It's off by default and you should leave it off.
Try to get into composer / psr classmaps / psr autoloading. This is kinda "industry standard" mechanism. You should go for that.

A: To make it as a static reference you can code it like:
require($_SERVER['DOCUMENT_ROOT'] . '/TEST/database.php'); // $_SERVER['DOCUMENT_ROOT'] gets you '/var/www' or whatever your server root maybe

A: <?php require("database.php");?>

<?php require("database.php"); ?>

No Need To require Full Path When You Are Working in One Folder


text:
Q: Storing the return of a line from FINDSTR into a variable, it sets it two times I am trying to write a script that will check another batch script setup for a tool I am running.
Inside the batch file to be checked is the line:
set tooldir=D:\Folder
I want to be able to pull 'D:\Folder' out and check its validity, but I cannot even get my variable to store the right string.
As of now I have:
for /F "delims=" %%a in ('findstr /L tooldir= %batFileName%') do set batToolDir=%%a
echo %batToolDir%

Which outputs
C:\Users\me>for /F "delims=" %a in ('findstr /L tooldir toolBatch.bat') do set batToolDir=%a
C:\Users\me>set batToolDir=set tooldir=D:\Folder
C:\Users\me>set batToolDir=cd %tooldir%
C:\Users\me>echo cd %tooldir%
cd %tooldir%

It is setting my output variable twice, the first time is correct and then for some reason it does set batToolDir=cd %tooldir%

A: I'm not sure what your test data is but use quotes like this, to protect against spaces and things like the = in tooldir= in your case:
for /F "delims=" %%a in ('findstr /L "tooldir=" "%batFileName%" ') do set "batToolDir=%%a"
echo "%batToolDir%"


text:
Q: How to use shared prefrences to save data per id This code is only for testing, how to save existing client data when the save button is clicked and can still be used to view, update and delete using shared preferences so that when the application exits the data is not lost, here's the code:
package com.test.data;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.LayoutInflater;
import android.widget.TextView;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.List;
import android.view.Gravity;

class Client {
    private String clientID;
    private String clientName;
    private String clientAddress;
    private String clientEmail;
    private String clientPhone;

    public Client(String clientID, String clientName, String clientAddres, String clientEmail, String clientPhone) {
        this.clientID = clientID;
        this.clientName = clientName;
        this.clientAddress = clientAddres;
        this.clientEmail = clientEmail;
        this.clientPhone = clientPhone;
    }

    public String getclientID() {
        return clientID;
    }

    public void setclientID(String clientID) {
        this.clientID = clientID;
    }

    public String getclientName() {
        return clientName;
    }

    public void setclieantName(String clientName) {
        this.clientName = clientName;
    }

    public String getclientAddress() {
        return clientAddress;
    }

    public void setclientAddress(String clientAddress) {
        this.clientAddress = clientAddress;
    }

    public String getclientEmail() {
        return getclientEmail();
    }

    public void setclientEmail(String clientEmail) {
        this.clientEmail = clientEmail;
    }

    public String getclientPhone() {
        return clientPhone;
    }

    public void setclientPhone(String clientPhone) {
        this.clientPhone = clientPhone;
    }
}

public class MainActivity extends AppCompatActivity {

    private EditText etclientID, etclientName, etclientAddress, etclientEmail, etclientPhone;
    private Button btnSave, btnShow, btnUpdate, btnDelete;

    private List<Client> listClient = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etclientID = findViewById(R.id.et_id_client);
        etclientName = findViewById(R.id.et_nama_client);
        etclientAddress = findViewById(R.id.et_waktu_pendaftaran);
        etclientEmail = findViewById(R.id.et_jenis_perkara);
        etclientPhone = findViewById(R.id.et_status_perkara);

        btnSave = findViewById(R.id.btn_simpan);
        btnShow = findViewById(R.id.btn_lihat);
        btnUpdate = findViewById(R.id.btn_update);
        btnDelete = findViewById(R.id.btn_hapus);

        btnSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    saveClient();
                }
            });

        btnShow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showClient();
                }
            });

        btnUpdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateClient();
                }
            });

        btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteClient();
                }
            });
    }

    private void saveClient() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout, null);
        TextView text = layout.findViewById(R.id.text);

        String clientID = etclientID.getText().toString();
        String clientName = etclientName.getText().toString();
        String clientAddress = etclientAddress.getText().toString();
        String clientEmail = etclientEmail.getText().toString();
        String clientPhone = etclientPhone.getText().toString();

        boolean isIdExists = false;
        for (Client client : listClient) {
            if (client.getclientID().equals(clientID)) {
                isIdExists = true;
                break;
            }
        }

        if (isIdExists) {
            text.setText("Client ID is already in use");
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        } else {
            listClient.add(new Client(clientID, clientName, clientAddress, clientEmail, clientPhone));
            text.setText("Data saved successfully");
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
    }
}

    private void showClient() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout, null);
        TextView text = layout.findViewById(R.id.text);

        String clientID = etclientID.getText().toString();
        boolean found = false;
        for (Client client : listClient) {
            if (client.getclientID().equals(clientID)) {
                text.setText("Client ID : " + client.getclientID() + "\nClient Name : " + client.getclientName() + "\nClient Address : " + client.getclientAddress() + "\nClient Email : " + client.getclientAddress() + "\nClient Phone : " + client.getclientPhone());
                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.TOP, 0,30);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.setView(layout);
                toast.show();
                found = true;
                break;
            }
        }
        if (!found) {
            text.setText("Data with id " + clientID + " not found");
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        }
    }

    private void updateClient() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout, null);
        TextView text = layout.findViewById(R.id.text);

        String clientID = etclientID.getText().toString();
        String clientName = etclientName.getText().toString();
        String clientAddress = etclientAddress.getText().toString();
        String clientEmail = etclientEmail.getText().toString();
        String clientPhone = etclientPhone.getText().toString();

        boolean isUpdated = false;

        for (Client client : listClient) {
            if (client.getclientID().equals(clientID)) {
                client.setclieantName(clientName);
                client.setclientAddress(clientAddress);
                client.setclientEmail(clientEmail);
                client.setclientPhone(clientPhone);
                isUpdated = true;
                break;
            }
        }

        if (isUpdated) {
            text.setText("Data successfully updated");
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        } else {
            text.setText("Data not found");
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        }
    }

    private void deleteClient() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout, null);
        TextView text = layout.findViewById(R.id.text);

        String clientID = etclientID.getText().toString();

        int index = -1;
        for (int i = 0; i < listClient.size(); i++) {
            if (listClient.get(i).getclientID().equals(clientID)) {
                index = i;
                break;
            }
        }

        if (index != -1) {
            listClient.remove(index);
            text.setText("Data berhasil dihapus");
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        } else {
            text.setText("Data deleted successfully");
            Toast toast = new Toast(getApplicationContext());
            toast.setGravity(Gravity.TOP, 0, 30);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setView(layout);
            toast.show();
        }
    }
}

I want the data not to be lost when I exit the application, when I enter the application again the data can still be used per id, all functions saveclient, showclient, updateclient, deleteclient can still be used, maybe someone can help.