text:
Q: C++ Sorting a vector of tuple by numerical value, then lexicographically I have a vector<tuple<string, float> > vector that stores the euclidean distance between two nodes, and the node's name. I need to sort this vector by the distance value first, and then by string value. This is so in the instance where two nodes have the same euclidean distance, their sorted position resolves to being done by alphabetical (lexicographical) order of the node names. At the moment, I have a custom sorting helper function that sorts the vector by float value first.
bool sort_second(const tuple<string, float>& a, const tuple<string, float>& b) {
    return (get<1>(a) < get<1>(b));
}

and call sort(vec.begin(), vec.end(), sort_second) as such. But in the event where nodes foo and bar have the same distance, it's possible for foo to come before bar even though bar should be first. How would I go by sorting the vector a second time (or better yet, on the first pass through) such that I don't mess up the value order that I already computed? Thanks

A: Use std::tie to sort as if tuples were reversed:
bool sort_reversed(const tuple<string, float>& a, const tuple<string, float>& b)
{
    return std::tie(get<1>(a), get<0>(a)) < std::tie(get<1>(b), get<0>(b));
}

Or if you want it done manually:
bool sort_second(const tuple<string, float>& a, const tuple<string, float>& b)
{
    return (get<1>(a) < get<1>(b)) ||
           ((get<1>(a) == get<1>(b)) && (get<0>(a) < get<0>(b)));
}

A: Can be achieved simply by modifying the code:
bool sort_second(const tuple<string, float>& a, const tuple<string, float>& b) {

    if(get<1>(a) == get<1>(b))
        return get<0>(a) < get<0>(b);

    return (get<1>(a) < get<1>(b));
}

A: Recently I was in somewhat same situation but to lower down my burden I used different approach.
I just used an array to store all the vector elements , sorted that array, placed those array elements back in the vector. Try to catch an idea from this :)


text:
Q: D3 Animation Issue: ease Writing a function to animate some elements when it is called, however I cannot set any kind of transition.ease().
var circles = canvas.selectAll("circle")
        .data(orgs)
        .enter().append('circle')
        .attr('cx', function(d, i) {
            d = orgs[i][0];
            return d;
        })
        .attr('cy', function(d, i) {
            d = orgs[i][1];
            return d;
        })
        .attr('r', 5)
        .attr('fill', 'rgb(255, 0, 213)');

function update() {
    for (var i = 0; i < numBodies; i++) {
        var dx = 0;
        var dy = 0;
        for (var j = 0; j < numBodies; j++) {
            if (i!=j) {
                dx += orgs[j][0];
                dy += orgs[j][1];
            }
        }
        dx = dx/(numBodies - 1);
        dy = dy/(numBodies - 1);

        orgs[i][0]+= (dx-orgs[i][0])/100;
        orgs[i][1]+= (dy-orgs[i][1])/100;
    }
    circles.transition()
            .duration(200)
            .ease('linear') //THROWS AN ERROR
            .attr('cx', function(d, i) {
                d = orgs[i][0];
                return d;
            })
            .attr('cy', function(d, i) {
                d = orgs[i][1]
                return d;
            });
}

I want to just use the linear animation interpolation to improve performance.  I am following the exact syntax used in this example (shown below).  If I exclude the indicated line, my program functions perfectly.  What is going wrong?

<!doctype html>
<html lang="ja">
<head>
 <meta charset="UTF-8">
 <title>Easing Test</title>
 <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
 <script>
  var dataset = ["linear", "quad", "cubic", "sin", "exp", "circle", "elastic", "back", "bounce"]
   width = 960,
   height = 500,
   xPadding = 300,
   yPadding = 30,
   r = 20;

  var svg = d3.select("body").append("svg")
     .attr({
      width: width,
      height: height
     });

  svg.selectAll("text")
   .data(dataset)
   .enter()
   .append("text")
   .attr({
    x: xPadding,
    y: function(d, i){ return i * (height/dataset.length) + yPadding; },
    dx: -100,
    dy: 5,
    "font-size": 18
   })
   .style("text-anchor", "middle")
   .text(function(d){ return d; });

  svg.selectAll("line")
   .data(dataset)
   .enter()
   .append("line")
   .attr({
    x1: xPadding,
    y1: function(d, i){ return i * (height/dataset.length) + yPadding; },
    x2: width-xPadding,
    y2: function(d, i){ return i * (height/dataset.length) + yPadding; },
    stroke: "darkorange"
   })

  svg.selectAll("circle")
   .data(dataset)
   .enter()
   .append("circle")
   .attr("class", function(d){ return d; })
   .attr({
    cx: xPadding,
    cy: function(d, i){ return i * (height/dataset.length) + yPadding; },
    r: r,
    fill: "orange"
   })
   .on("mouseover", function(d){
    d3.select(this).attr("fill", "green");
   })
   .on("mouseout", function(d){
    d3.select(this).attr("fill", "orange");
   })
   .on("click", function(d){
    d3.select(this)
     .transition()
     .duration(1000)
     .ease(d)
     .attr("cx", width-xPadding)
     .each("end", function(){
      d3.select(this)
       .transition()
       .delay(500)
       .duration(500)
       .attr({
        cx: xPadding
       })
     })
   })

 </script>
</body>
</html>

A: What version of d3 are you using? If it's v4, replace it with
transition.ease(d3.easeLinear)

For changes between 3.x and 4.0, see this
API Reference

A: Just to add that transition(d3.easeLinear) worked for me in v5

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is VisualVM's profiler not "seeing" all classes/methods When i profile an app using OpenJDK's visualvm tool, i can not see methods which are called for sure. I see logging messages which are produced by them. Furthermore i can run the app within Eclipse in debug mode and set breakpoints in the code (while profiling is active) which are activated when execution arrives there. When i wait there for some minutes till i resume execution, i thought i should see those paused methods in the profiler. And when i run the app with my use case to initialize and instantiate all objects which are needed in the app before i connect with the profiler, even then i can not see all methods. Furthermore i noticed that it does not count all method invocations... sometimes it only counts a few calls, when in fact there have been thousands of calls which logged to the log file.
Does anybody know why classes/methods and its invocations are not "seen" in visualvm?
I checked many times and i did not apply any filters on the profiler, so every method call, even the Java API's methods should get profiled.
I too tried with -Djava.compiler=NONE, but the only impact besides the apps runtime increase was that the profiler seemed to stop collecting data after a few seconds and never resumed/updated its statistic.
When adding -Xint to the jvm, i can see more methods in the profiler, but it still does not show a lot of "relevant" methods.
With the behavior of visualvm, not showing classes / methods (with hotspot compiler active), not updating statistics, it looks to me that this tool is not very useful.
Did i miss something with visualvm?
I am using visualvm 1.3.8 (Build 140703); platform 20141108-debian-
with 1.7.0_95; OpenJDK 64-Bit Server VM (24.95-b01, mixed mode), but the app is executed with either Java 1.6 or Java 1.7.


text:
Q: PHP - How to check if Curl actually post/send request? I basically created a script using Curl and PHP that sends data to the website e.g. host, port and time. Then it submits the data. How would I know if the Curl/PHP actually sent those data to the web pages?
$fullcurl = "?host=".$host."&time=".$time.";

Any ways to see if they actually sent the data to those URLs on My MYSQL?

A: You can use curl_getinfo() to get the status code of the response like so:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

// execute the request, I'm assuming you don't care about the result content
curl_exec($ch);

if (curl_errno($ch)) {
    // this would be your first hint that something went wrong
    die('Couldn\'t send request: ' . curl_error($ch));
} else {
    // check the HTTP status code of the request
    $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($resultStatus == 200) {
        // everything went better than expected
    } else {
        // the request did not complete as expected. common errors are 4xx
        // (not found, bad request, etc.) and 5xx (usually concerning
        // errors/exceptions in the remote script execution)

        die('Request failed: HTTP status code: ' . $resultStatus);
    }
}

curl_close($ch);

For reference: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Or, if you are making requests to some sort of API that returns information on the result of the request, you would need to actually get that result and parse it. This is very specific to the API, but here's an example:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

// execute the request, but this time we care about the result
$result = curl_exec($ch);

if (curl_errno($ch)) {
    // this would be your first hint that something went wrong
    die('Couldn\'t send request: ' . curl_error($ch));
} else {
    // check the HTTP status code of the request
    $resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($resultStatus != 200) {
        die('Request failed: HTTP status code: ' . $resultStatus);
    }
}

curl_close($ch);

// let's pretend this is the behaviour of the target server
if ($result == 'ok') {
    // everything went better than expected
} else {
    die('Request failed: Error: ' . $result);
}

A: in order to be sure that curl sends something, you will need a packet sniffer.
You can try wireshark for example.
I hope this will help you,
Jerome Wagner


text:
Q: Tee requests with HAProxy I'm using HAProxy to loadbalance TCP service. I would like to "tee" the same request to a different cluster (dev instance).
Does HAProxy have the "tee" feature?
The dev, prod clusters and the HAProxy are different subnets, so I can't use the "tee" feature in iptables.

A: I have not done this myself but if you don't need real-time copying you could use tcpdump to capture the traffic and wireplay to send it to the dev instance.
Edit: the answer is no.


text:
Q: Use PHP and MySQL to add images to a gallery I'm trying to create a back-end to my photo gallery so it will make it easier for me to upload images to the gallery.
The Gallery consists of a thumbnail image, a one line description and the thumbnail is hooked up to a fancy box. Pretty basic. (The thumbnail and fancy box image are using the same image.)
I'm just starting to learn the basics of PHP and MySQL and would like to know how I can take this code: (FYI this is only part of the gallery.)

Lake of the Ozarks Tree Removal

Lake of the Ozarks Tree Trimming

and create an admin system that I can upload images to the gallery without having to manually go in and adjust the code every time a client sends me an image.
Pretty much, I want to create a form where I can set the parameters and uploaded the image(s) to the gallery page.
Using the above code how can I add more images to the list?
I guess what I'm asking is how to setup a database and table and add the appropriate php syntax to the html to get the results I'm looking for?
I understand how to create a form to upload the images into a ftp directory. I'm just lost on setting up the database and tables to retrieve the images and text and place them in the gallery
Would I set the database up like this? (FYI I have no clue as to what I'm doing at this point.)
Database name: maingallery
Table:
data-id: id ascending
( The data-id and data-type are very important as the gallery is connected to a filtering system. I would want the data-id to be auto generated and add the newest image to the top of the gallery.  )
data-type: treetrimming
data-type: treeremoval
rel: gallery1
rel: gallery2
image: ...???
title: Tree Removal Lake of the Ozarks
title: Osage Beach Tree Trimming
Then for the h5 tag
caption: Lake of the Ozarks Tree Removal
caption: Lake of the Ozarks Tree Trimming
For the images I'm using a max-img-border class because the site is responsive and I have all the images sized to 720px x 482px
The css looks like this:
.max-img-border {
 width:100%;
 height:auto;
 border:solid 2px #FFFFFF;
 margin-bottom:10px;
 }

By using this method I have it set up so I only have to deal with one image for the thumbnail and fancybox image.
I hope what I'm asking makes sense.
I know what I'm asking for is probably a lot to explain, but any help would be greatly appreciated.
Even some links to a good tutorial might help. I searched Google for a day or two, but can't really find exactly what I'm looking for.
Also If you look at the gallery and shuffle through the categories there is a large jump in the transition. I'm currently working on fixing this.
If you need anymore info from me please let me know and I will be more than willing to provide it.
Thank you!

A: You'll need a MySQL table containing the information about the image, and the file name of the image:
CREATE TABLE images (
    id int(3) not null auto_increment,
    data_type varchar(128) not null,
    title varchar(256) not null,
    file_name varchar(64) not null,
    primary key(id)
)

And you're going to have to make an image upload form, something like this:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
    Data type: <input type="text" name="dataType">

    Title: <input type="text" name="title">

    Image to upload: <input type="file" name="image">

    <input type="submit" value="Upload">
</form>

And a PHP script to handle the uploaded files and add database entries:
uploader.php
<?php
$dataType = mysql_real_escape_string($_POST["dataType"]);
$title = mysql_real_escape_string($_POST["title"]);
$fileName = basename($_FILES["image"]["name"]);
$target_path = "images/gallery/".$fileName);
if (file_exists($target_path))
{
    echo "An image with that file name already exists.";
}
elseif (move_uploaded_file($_FILES["image"]["tmp_name"], $target_path))
{
    // The file is in the images/gallery folder. Insert record into database by
    // executing the following query:
    // INSERT INTO images
    // (data_type, title, file_name) VALUES('$dataType','$title','$fileName')
    echo "The image was successfully uploaded and added to the gallery :)";
}
else
{
    echo "There was an error uploading the file, please try again!";
}
?>

Note that this script is not safe, it would allow people to upload for example .php files to the server. Something like this will be necessary:
$allowed_extensions = array("jpg","jpeg","png","gif");
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
if (!in_array($extension,$allowed_extensions))
{
    die("Only these file types are allowed: jpg, png, gif");
}

Now on the gallery page you'll want to loop through the images in the database.
<?php
$images = mysql_query("SELECT * FROM images");
while ($image=mysql_fetch_assoc($images))
{
    ?>
    <li data-id="id-<?=$image["id"] ?>" data-type="<?=$image["data_type"] ?>">

    <a class="fancybox" rel="<?=$image["data_type"] ?>" href="images/gallery/<?=$image["file_name"] ?>" title="<?=$image["title"] ?>">
    <img src="images/gallery/<?=$image["file_name"] ?>" alt="<?=$image["title"] ?>" class="max-img-border">

<?=$image["title"] ?>

    <?php
}
?>

Please note that the upload form will have to be protected, and only available to the right people. You don't want spammers to upload random files onto your server.


text:
Q: Ubuntu user access restrictions I want to create an user account for each users at our office, where 2 users can have the full permission, whereas other users have limited access, say /var/www/html/ or /home/username.

A: Might I humbly suggest that you find a Unix/Linux system administrator to help you, as I think the scope of security issues and configuration is orders of magnitude more complex then your post suggests.
One of the simplest ways to do this is to create accounts for everyone, and then provide the 2 administrators with the root password and let them use su.
A more appropriate way to handle the matter would be to add these users to the "adm" account
This answer only scratches the surface of the problem space though.
groupadd -a -G adm username

and then edit /etc/sudoers by using visudo and add a line
%adm ALL=(ALL) ALL

Then the admin users can do sudo COMMAND to execute the command as root, or sudo /bin/bash to get a root shell.


text:
Q: Avoiding null model in ASP.Net Web API when no posted properties match the model [HttpPost, Route("foo")]
public void DoStuff(FooModel args)
{
    if(args == null) args = new FooModel();

    // ...
}

public class FooModel
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

When a POST request is sent to a Web API method and the HTTP request does not include any of the arguments that would populate the model, instead of passing an empty model to the action, Web API instead just passes null to the action, necessitating a null check against the model argument at the start of every action.
I understand that the framework is probably trying to avoid an unnecessary object construction, but these are always lightweight classes with no specific functionality. It would save time and be more consistent if the model was constructed every time rather than trying to save some negligible fraction of a millisecond that would be the cost of just constructing the model object anyway and passing it to the action.
How can I get the framework to always pass a constructed (non-null) model object to my actions, even if none of the associated properties were able to be populated?
I'm using ASP.Net Web API 2.2.

A: The MVC Framework uses a system called model binding to create C# objects from HTTP requests in order to pass
them as parameter values to action methods. This is how the MVC framework processes forms, for example: it looks
at the parameters of the action method that has been targeted and uses a model binder to get the form values sent
by the browser and convert them to the type of the parameter with the same name before passing them to the action
method.
If you want to customize the way model binding works you can create a Custom Model Binder.
Parameter Binding in ASP.NET Web API
Creating a Custom Web API Model Binder


text:
Q: I tried decomposing my function, but I'm not sure if I did it right Originally, this function was embedded into the main function, creating a very cluttered main function. The program replaces tabs with the number of spaces. I'm still confused as to what goes inside the argument lists for my functions and how to pass argc/argv from main into these functions. Did I do this right?
There are some defined variables at the top of the file:
#define OUTFILE_NAME "detabbed"
#define TAB_STOP_SIZE 8
#define NUM_ARGS 2
#define FILE_ARG_IDX 1

Here's my second attempt at it:
void open_file(FILE *inf, FILE *outf, char *in[]) /*I feel like the arguments aren't right
{                                                   and this function is just opening
                                                    and reading files*/
   inf = fopen(in[1], "r");
   outf = fopen(OUTFILE_NAME, "w");

   if (inf == NULL)
   {
      perror(in[1]);
      exit(1);
   }

   else if (outf == NULL)
   {
      perror(OUTFILE_NAME);
      exit(1);
   }

   fclose(inf);
   fclose(outf);
}

void detab(FILE *infile, FILE *outfile, char *argument[]) /* Confused about argument list
{                                                           and this function actually
   char c;                                                  does the detabbing */
   int character_count = 0, i, num_spaces;

   open_file(infile, outfile, argument);                 /* I want to call the previous
                                                          function but again, confused
   while (fscanf(infile, "%c", &c) != EOF)                about the argument list */
   {
      if (c == '\t')
      {
         num_spaces = TAB_STOP_SIZE - (character_count % TAB_STOP_SIZE);

         for (i = 0; i < num_spaces; i++)
         {
            fprintf(outfile, " ");
         }

         character_count += num_spaces;
      }
      else if (c == '\n')
      {

         fprintf(outfile, "\n");
         character_count = 0;
      }
      else
      {
         fprintf(outfile, "%c", c);
         character_count++;
      }
   }

}

int main(int argc, char *argv[])
{
   if (argc < 1)
   {
      fprintf(stderr, "usage: prog file\n");
      exit(1);
   }

   else if (argc < NUM_ARGS)
   {
      fprintf(stderr, "usage: %s file\n", argv[0]);
      exit(1);
   }

   detab(argc, argv);   /* I want to pass argc and argv to the detab function, but I'm
                          having trouble with the argument list */
   return 0;
}

What I need help with, is figuring out what goes in the argument lists of the functions. I think what confuses me is how to get my argument types to match, so that I can pass variables from one function to the other.

A: Decomposition is not your biggest problem here. Rather careless error checking, the use of old overweighted fscanf() and fprintf() and global variables are. Furthermore, the lack of const correctness in the input filenames, the overly long and verbose variable names and your unawareness of the += and ++ operators are just the bonus. I suppose that's why your code looks like it's bloated (and it is, in fact).
I'd rewrite the function like this:
void detab(const char *in, const char *out, int tabstop)
{
    FILE *inf = fopen(in, "r");
    if (!inf) return;

    FILE *outf = fopen(out, "w");
    if (!outf) {
        fclose(inf);
        return;
    }

    int n = 0;
    int c;
    while ((c = fgetc(inf)) != EOF) {
        if (c == '\t') {
            int pad = tabstop - n % tabstop;

            for (int i = 0; i < pad; i++)
                fputc(' ', outf);

            n += pad;
        } else if (c == '\n') {
            fputc('\n', outf);
            n = 0;
        } else {
            fputc(c, outf);
            n++;
        }
    }

    fclose(inf);
    fclose(outf);
}

If you want to decompose this even further, then you may write a function taking two FILE * and the tab stop as its arguments and it shall contain the while loop only - doing that is left to you as an exercise.

A:
Note: This answer was given to an earlier edit of the question. It has changed in the meantime, so this answer may no longer seem relevant.

Coming from an OOP background, I will focus on one single issue that is there known as Single Responsibility Principle (SRP). I argue that detab (and every other function) should do only one specific thing, but do that thing well.
But it doesn't just "detab", as its name suggests; it also has to extract its actual arguments from the command-line variables argc and argv, which were forced upon it by main:
detab(argc, argv);

main has done some validation before that, but because the command-line is then simply passed to the function, you obviously felt like continuing validation in detab (I also make some additional remarks about violating the SRP below):
void detab(int arg_list, char *array[]) // why ask for arg_list if you don't need it?
{
   …
   infile = fopen(array[1], "r"); // not obvious to caller that only array[1] is relevant
   …
   if (infile == NULL)
   {
      perror(array[1]);
      exit(1); // should your function really have the power to terminate the program?
   }
   …
}

It would seem much more reasonable to concentrate all the command-line validation and value extraction logic in one place, and the detabbing in another; that is, draw clear boundaries of responsibility. Don't let logic of one function spill over into another!
To me, detab's signature should look more like e.g. this:
void detab(FILE *in, FILE *out);


text:
Q: Throwing a message to the user in SQL Server I need to have a nested if statement in an update trigger. How do I say with an If statement in sql -- if two columns don't equal each other - throw an error message (don't shut down the system - just throw a message alerting the user).
If(@order_tot_paid_amt > 0) -- that means that the user has entered a value. (and its calculated)

I've reviewed a few of the existing posts, and they differ from what I am asking. Do I need a catch statement? (I know in c++ you need a catch statement otherwise things shut down).
What I have so far is (and I know I'm missing data).
IF (@order_tot_paid_amt > 0)
   IF @order_tot_paid_amt <> (select pmt_rcvd_amt from LT_CHC_TOURS_RSV_CS where id_key = @id_key)
THROW  ...
CATCH  ...

I don't know where to get all the commands for throw and catch.


text:
Q: uwp override localized strings in resw files The idea is very straightforward, throughout uwp applications multiple controls will have their x:uid attribute defined on them and based on that we will have .resw localized file with default string values I know how that works.
However when the application loads we get a custom json or xml string from server side through an api and it will be like the "resw" string where it will have collection of keys and values and it is supposed to override the currently being used "resw" values, bcz the keys will be same in resw file and the json string which we get from server but the values might be different, so can we override those resw string values at runtime somehow?
if that isnt possible can we get a List of all x:UIDs on a given page when the page loads? and then loop through them and update their properties based on the values we have coming from our server side json?
<AppBarButton
            x:Name="appbar2"
            x:Uid="appbar2"
            Width="200"
            Height="56"
            Icon="Accept"
            Style="{ThemeResource AppBarButtonNavigationStyle}" />

I am aware on any given control we have the .Name property but we dnt have .uid property which is why I was wondering if there is a workaround way to get it?

Ive looked into official documentation but apparently we cannot set values on "resw" resources they r readonly, which is a bummer, in our case we will only need english language so we always will have 1 resw file.

The aim is that all controls can have all of their default property values already set on xaml or with x:uid but when we get our values from server side only those controls with only their properties which exist in the "server side json" should be updated.
What Ive tried:
Ive tried to create a class with all dynamic properties I need and each of these properties have a default value to it, and then I bind it to UI with x:Bind, and when we get json from server side I just convert it to that class so all its values get updated and it works as expected only limitation here is everytime I have to add a new control or a new property of the same control I have to add it to json as well as client side xaml code and that model class as well, which is not ideal because we want to only update or add new properties from server side without updating the client side.
Example
for the code give above, we have a control with x:UID=appbar2 now we only have to assign this once on xaml, then in resw resource file it will have values like "appbar2.Label=Label1" this will be its default value, but then server side json comes in and we have key, value pair as "appbar2.Label-Label2" this will update its label to "label2" and if the json also has "appbar2.Header=h1" it should also update header of appbar2 button, assuming this control had a property "header" on it.
Thanks.

A: If you retrieve the resources at runtime, it doesn't make much sense to use the x:Uid directive to localize your app. You'd better come up with something else to "mark" the elements and localizable, for example using an attached property, and then set the properties once you have received the resources.

I am aware on any given control we have the .Name property but we dnt have .uid property which is why I was wondering if there is a workaround way to get it?

I am afraid not:
Set value of x:Uid programmatically

A: Some other resources about alternatives to doing resource loading.
See this blog here for using a Markup Extension instead. And beyond that there's the ReswPlus project.
I don't know if either will do what you want. Why is all your localization coming from a server-side resource instead of shipping with the app itself? Dynamically updating things sounds like you're trying to exploit the x:uid system as it wasn't designed for this scenario.
If you really need to do it this way, I'd suggest instead just creating a static class which exposes dependency properties (or uses INotifyPropertyChanged) and use {x:Bind local:MyStaticClass.MyPropertyNameForThisLabel, Mode=OneWay} (or set OneWay for all above for the page using x:DefaultBindingMode.
Then when your server resource is downloaded, it can update all the properties on this static class and all the bound properties on it will be automatically updated through their bindings like anything else would be.


text:
Q: Library/Framework for Parsing Output from Commandline (C#)? My application needs to:

*

*Run an external command-line application

*Capture the standard output/error during execution

*Parse the data from the output/error and use it for status display in the main app

While it's not hard to do it, it seems to me it's a very common task, and I was wondering if there's a library or framework simplifying this task in C#.
Edit: Here's a "Mono.Options inspired" example of the kind of thing I'm looking for:
ProcessWithParser proc= new ProcessWithParser(filename, arguments);
proc.AddWatch("percent=??", v => this.percent = Convert.ToInt32(v));
proc.Start();

In the "concept" above, it would locate "percent=" in the output, read the next two characters as a string, and call the delegate using this string as a parameter.

A: The base class library provides the tools for this already - there isn't much a framework would really need to add to it.
Redirection of the process standard input and output streams is trivial.  RegEx and using streams makes parsing this fairly easy, as well.
The framework pretty much does what any (flexible) custom library would normally do in other languages.


text:
Q: Why is jQuery's .val() returning null? I'm a bit boggled by this...  Why is .val() returning null when there clearly is an option selected for the <select>?
These commands were executed via Chrome's console on the page with the issue.

A: I think this may be a bug in Chrome.  Maybe a bug between my specific version of Chrome and this specific version of jQuery?  The select in question (which was previously hidden, but unhidden for further testing) appears like so:

This suggests that an option is not selected.
However, clicking on it (to open the select element and display the options, not actually clicking on an option) reveals this:

Weird.  Very weird.  Soooo if the GUI is reflecting the state of things, part of Chrome thinks that the select element has an option selected, while another part of the code thinks the select element does not have an option selected?  Weird.


text:
Q: How to apply two patches against the same git revision? This is a imaginary problem, but I'm having real problems with patches. Let's say I have a project with the following git history:
A - B - C

Now if I receive two patches, C1 and C2, that are meant to be applied on C, how should I handle them? If I apply patch C1 first, then I will not be able to apply patch C2 because the repository has become:
A - B - C - C1

Is it possible to apply them both, or do I have to reply to the person sending C2 telling him/her to update the patch?
Now suppose I go offline and work and commit so that the repository becomes:
A - B - C - D - E

Then I check my email and receive a patch for C. Again, is it possible to simply apply that patch, or do I have to ask for an update to the patch?

A: The classic way is to:

*

*apply the received first patch,

*refuse any patch which isn't fast-forward and ask the sender to rebase his/her repo first, then re-check the patch, and resend it.

The general idea is that it isn't up to you to solve merge conflicts: only the creator of the patch has the necessary knowledge to solve any conflict with the current source code.
As Linus Torvalds (creator of Git) said in his 2007 Google talk:

So what happens is, remember, distribution means nobody is special.
  So instead of me merging, I just push out my first tree, that did not have any merge issues, and I tell the second person:
"hey, I tried to pull from you, but I had merge conflicts and they weren't completely trivial, so I decided you get to do the honors instead."
And they do. And they know what they are doing because it's their changes. So they can do the merges and they probably think I am a moron because the merge was so easy and it is obvious I should have taken their code, but they do the merge and they update their tree, and say "hey, can you pull from me now", and I pull from them and they did all the work for me.
That's what is all about: they did all the work for me. So,... and I take the credit. Now I just need to figure out the step 3: profit.

A: Most of the time, C2 will apply on top of C1.  It's only if they're edits to overlapping sections of the same files that you'll get a merge conflict.  Git will take all the parts of the patch that don't conflict, and insert conflict markers that help you resolve the merge.
As for what to do, it depends how large your project is and how competent you are in that section of the code -- I've always just fixed up the conflicts myself, as long as the submitter used a reasonably recent checkout as the base for their patch.
Another commenter mentioned Linus' quote saying that he always makes other people resolve conflicts, but even this isn't quite true; he often asks people to leave conflicts unresolved when sending pull requests so he gets a shot at them.

A: You can totally at least try to apply all these patches. You may potentially get merge conflicts, and as VonC suggests, you might want the patch submitters to solve them, or you might do it yourself as cjb says! In any case, here's what you want to do.
First case: two patches, C1 and C2.
# apply C1
git am C1.patch
# create a temporary branch (use a real name instead of C2)
git checkout -b C2 C
# apply C2
git am C2.patch
# return to master
git checkout master
# merge the other branch
git merge C2
# and delete the other branch
git branch -d C2

You can handle the second case similarly; it's just that instead of applying C1 you've made commits D and E yourself.
And of course, if the merge fails, and it looks too scary for you to sort through yourself, just blow it away and tell the submitter of C2 to fix it on their end. (git reset --merge; git branch -D C2)


text:
Q: React-native component's componentDidMount() is not called under NavigatorIOS I create a component with ListView under the structure: TabBarIOS > NavigatorIOS > ListView. I try to fetch data in componentDidMount(). But it didn't work unless I fetch it in componentWillMount(). Why?
I've put my work here https://github.com/chiakie/MyAwesomeProject
In MotorcycleList.js, componentDidMount() seem to never be called.

A: The componentWillMount() life cycle event is actually the correct place to call fetchData() because it is invoked once before the component mounts, this way you can setState do that the data is there when it mounts.

Mounting: componentWillMount
void componentWillMount()
Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method,render() will see the updated state and will be executed only once despite the state change.

Whereas componentDidMount() renders after the component had already mounted.

Mounting: componentDidMount
void componentDidMount()
Invoked once, only on the client (not on the server), immediately after the initial rendering occurs. At this point in the lifecycle, you can access any refs to your children (e.g., to access the underlying DOM representation). The componentDidMount() method of child components is invoked before that of parent components.


text:
Q: Points displacement - capture new coordinates? I have a vector layer of points - say, rooms for rent in a city. Definitely, several rooms are up for rent in one building, so these would share the same coordinates. I need all my rooms to have unique coordinates (say, rooms 1 and 2 in the same building just a few meters apart), so I try points displacement.
Points displacement seems to work visually, but how will I get the new coordinates of the displaced points? "Add geometry column" still exports the original coordinates.
/Edit: I just learned the term, so: what I want is to get the coordinates of the digitized points. I end up with a ring of points (rooms) around the original point (building), but the coordinates of those rooms still end up the same as the original building.

A: There are two point displacement options, one is the renderer Point Displacement, found in the Styles tab, and the other is the geoprocessing Points Displacement, found in the Processing Toolbox.
First one will be just a visual change, the second one will be permanent (but not on the original data, you save your changes to a new layer). Use the second one, and you should have your new coordinates.

A: I ran into this problem too – and found that exporting with AS_XY as GEOMETRY on layer options exported the displaced points correctly.


text:
Q: Index for VARCHAR column has low efficiency I have two tables with relationship one to many.
create table locations
(
  id bigint
     auto_increment
     primary key,
  location_id varchar(128)
     null,
  constraint locations_location_id_uindex
     unique (location_id)
);

create table links
(
  id bigint
     auto_increment
     primary key,
  location_id varchar(128)
     null,
  loc_id bigint
     null,
  constraint links_location_id_fk
     foreign key (loc_id)
     references locations (id)
);

create index links_location_id_index
   on links (location_id);

The locations table has 596_752 records and links table has 1_221_450 ones.  Both tables are very often updated with a new data, there is no a deletion process. The location_id in both tables has size 30 characters.
When a new data appear in links table I have to find all links.location_id that do not exist in locations.location_id. In order to do so I execute the following query:
SELECT links.location_id
FROM links
LEFT JOIN locations l
   ON links.location_id = l.location_id
WHERE l.location_id IS NULL

The log output says:
34 rows retrieved starting from 1 in 1 m 11 s 678 ms (execution: 1 m 11 s 668 ms, fetching: 10 ms)

As you can see, it works too long and I am looking for a way how to improve it, can You help me?
EDIT
The info about MySQL server, it's db.t2.micro AWS instance:
innodb_version  8.0.13
protocol_version    10
slave_type_conversions  ""
tls_version TLSv1,TLSv1.1,TLSv1.2
version 8.0.13
version_comment Source distribution
version_compile_machine x86_64
version_compile_os  Linux
version_compile_zlib    1.2.11

A: Would you try this and let me know if this improves your performance:
SELECT links.location_id FROM links
WHERE NOT Exists(
select location_id from locations);

A: VARCHAR is not the villain.  Having to scan 1.2M rows and do 1.2M lookups is the killer.
Why do you need to do this repeatedly?  You say you check the entire table every time you add one row?  Can't you just check the new row that you are adding?  Please elaborate on this -- it is the key to shrinking the time from a minute to a few milliseconds.
And what do you do with the resulting 34 rows?
Why have a PRIMARY KEY of a id BIGINT?  You may as well have location_id be the PRIMARY KEY in locations.  And, since a PRIMARY KEY is a UNIQUE key, you can then get rid of the unique clause.


text:
Q: MSSQL: Table Partitioning Key Given the following table structure, which would be the best key candidate for partition key? I've got 500million records and have partitioned by month using the eventDate which is static, however, the lastUpdated could be updated up to a week later, if not up to x number of weeks post eventDate.
Could lastUpdated also be a good candidate or not? and why.

The table has x5 non-clustered indexes on lastUpdated and no keys exist referencing eventDate

*

*key 1 (id)

*key 2 (lastUpdated)

*key 3 (id, lastUpdated)

*key 4 (recipient,lastUpdated)

*key 5 (delivery, lastUpdated)

Current issue:

*

*The current table is being constantly queryed for marketing segmentation, so a single select could fetch hundreds of thousands if not millions and multiple processes could be also running multiple selects on the same table with different criteria

*During high traffic days, there could be millions of rows of data to be inserted and/or updated; all this whilst step 1 is also taking place.

Current performance: The inserts/updates and selects to this table is very slow. I thought by introducing table partitioning could enhance performance in some way.


text:
Q: Why is the scroll listener in flutter calling twice when i scroll to the end I get duplicate results every time the data at the end of a scroll delays to fetch. This is a problem since I assume users may scroll down more than once whenever there is a delay and that causes duplicate results
 Future<void> _scrollListener() async {
if (scroll_controller.offset >=
        scroll_controller.position.maxScrollExtent &&
    !scroll_controller.position.outOfRange) {

  getdat();
}

}

A: That's true - this condition will trigger the function every time you get to the bottom of the list. To cope with this, you should handle the state explicitly. For instance, have a local variable (boolean flag) that you would switch to true/false based on whether the data is loading or not. This way, you could ensure that you are not triggering the data load multiple times.
For instance, depending on your state management solution, you could implement some kind of throttling solution. Here is the infinite list example that uses BLoCs for state management. And here you could notice how throttling is implemented to cope with overlaying requests in a short period.


text:
Q: Caption of subtable breaks into several lines I'm quite new in latex and have (at least for you) a maybe rather simple question, but i did not find anything that helped me after some research. I want to do a table with certain subtables, however my caption for the subtables breaks into several lines. I would prefer just one line above the table, position otherwise is fine.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{lscape}
\usepackage{subcaption}

\begin{document}

\begin{landscape}

\begin{table}[h]
\caption{Effects}
\begin{subtable}
\small
\caption{A subtable}
\label{tab:1a}
\begin{tabular}{l*{16}{c}}
\hline\hline
&\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}&\multicolumn{1}{c}{(3)}&\multicolumn{1}{c}{(4)}&\multicolumn{1}{c}{(5)}&\multicolumn{1}{c}{(6)}&\multicolumn{1}{c}{(7)}&\multicolumn{1}{c}{(8)}&\multicolumn{1}{c}{(9)}&\multicolumn{1}{c}{(10)}&\multicolumn{1}{c}{(11)}&\multicolumn{1}{c}{(12)}&\multicolumn{1}{c}{(13)}&\multicolumn{1}{c}{(14)}&\multicolumn{1}{c}{(15)}\\
\hline
\# months    &       0.192\sym{*}  &       0.139         &       0.190\sym{*}  &       0.168         &      -0.019         &       0.070         &       0.065         &       0.139\sym{*}  &       0.185         &       0.072         &       0.018         &       0.047         &      -0.088         &       0.000         &     -17.812                 \\
            &      (1.65)         &      (1.28)         &      (1.71)         &      (1.13)         &     (-0.17)         &      (0.94)         &      (0.48)         &      (1.78)         &      (1.26)         &      (0.70)         &      (0.21)         &      (0.26)         &     (-0.86)         &         (.)         &     (-1.03)                \\
[1em]
\# quartals  &       0.557         &       0.406         &       0.525         &       0.485         &      -0.068         &       0.227         &       0.175         &       0.437\sym{*}  &       0.539         &       0.206         &       0.063         &       0.107         &      -0.244         &       0.000         &     -55.164             \\
            &      (1.63)         &      (1.25)         &      (1.58)         &      (1.09)         &     (-0.20)         &      (1.02)         &      (0.43)         &      (1.87)         &      (1.23)         &      (0.69)         &      (0.24)         &      (0.19)         &     (-0.80)         &         (.)         &     (-1.03)                \\
[1em]
\# years     &       2.508\sym{*}  &       1.999         &       2.282\sym{*}  &       2.556         &      -0.405         &       0.951         &       1.366         &       1.750\sym{*}  &       1.923         &       1.004         &       0.573         &       0.756         &      -1.194         &       0.000         &    -234.503              \\
            &      (1.85)         &      (1.54)         &      (1.68)         &      (1.45)         &     (-0.31)         &      (1.12)         &      (0.86)         &      (1.87)         &      (1.09)         &      (0.87)         &      (0.54)         &      (0.35)         &     (-0.95)         &         (.)         &     (-1.04)               \\
\hline\hline
\end{tabular}
\end{subtable}

\hfill

\begin{subtable}
\centering
\small
\caption{A subtable}\label{tab:1b}
\begin{tabular}{l*{16}{c}}
\hline\hline
            &\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}&\multicolumn{1}{c}{(3)}&\multicolumn{1}{c}{(4)}&\multicolumn{1}{c}{(5)}&\multicolumn{1}{c}{(6)}&\multicolumn{1}{c}{(7)}&\multicolumn{1}{c}{(8)}&\multicolumn{1}{c}{(9)}&\multicolumn{1}{c}{(10)}&\multicolumn{1}{c}{(11)}&\multicolumn{1}{c}{(12)}&\multicolumn{1}{c}{(13)}&\multicolumn{1}{c}{(14)}&\multicolumn{1}{c}{(15)}\\
\hline
\# months    &       0.396\sym{*}  &      -0.017         &       0.008         &       0.197         &       0.056         &       0.032         &       0.202         &       0.131         &       0.461\sym{*}  &       0.174         &       0.299         &      -0.310         &       0.283         &       0.000         &       0.398\sym{*}       \\
            &      (1.83)         &     (-0.52)         &      (0.03)         &      (0.97)         &      (0.78)         &      (0.71)         &      (1.47)         &      (0.79)         &      (1.74)         &      (1.29)         &      (1.34)         &     (-1.15)         &      (1.06)         &         (.)         &      (1.78)               \\
[1em]
\# quartals  &       1.178\sym{*}  &      -0.057         &       0.018         &       0.593         &       0.172         &       0.098         &       0.610         &       0.400         &       1.329\sym{*}  &       0.490         &       0.918         &      -0.985         &       0.862         &       0.000         &       1.156\sym{*}          \\
            &      (1.82)         &     (-0.58)         &      (0.02)         &      (0.98)         &      (0.80)         &      (0.72)         &      (1.49)         &      (0.80)         &      (1.68)         &      (1.25)         &      (1.39)         &     (-1.22)         &      (1.08)         &         (.)         &      (1.78)             \\
[1em]
\# years     &       4.416\sym{*}  &      -0.317         &      -0.509         &       0.981         &       0.399         &       0.318         &       1.595         &       1.341         &       4.897         &       2.038         &       4.193         &      -4.298         &       3.354         &       0.000         &       4.519               \\
            &      (1.71)         &     (-0.83)         &     (-0.18)         &      (0.41)         &      (0.46)         &      (0.67)         &      (0.96)         &      (0.70)         &      (1.55)         &      (1.37)         &      (1.59)         &     (-1.36)         &      (1.04)         &         (.)         &      (1.64)               \\
\hline\hline
\end{tabular}
\end{subtable}
\end{table}

\end{landscape}

\end{document}

A: Upon trying to compile your document, you should get a bunch of error messages. Once you receive error messages, do not look at the resulting pdf file, but try to fix the errors first.
The first error message  you get is
Missing number, treated as zero.

This is because you forgot the argument of \begin{subtable}{<width>}.You could for example use \begin{subtable}{\linewidth}.
Additionally, \sym currently is undefined. I guess, the following line of code is missing in your preamble, so I added it:
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}

With the above mentioned changes, your code now is compilable without error messages, but still throws some overfull box warnings since your tables are wider than the available space. I therfore added \setlength{\tabcolsep}{0pt} and used \begin{tabular*}{\linewidth}{@{\extracolsep{\fill}}l*{16}{c}} instead of \begin{tabular}{l*{16}{c}} in order to make sure your tables are a) equally wide and b) fit into the available space.
Here is the full MWE:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{lscape}
\usepackage{subcaption}

\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}

\begin{document}

\begin{landscape}

\begin{table}[h]
\setlength{\tabcolsep}{0pt}
\caption{Effects}
\begin{subtable}{\linewidth}
\small
\caption{A subtable}
\label{tab:1a}
\begin{tabular*}{\linewidth}{@{\extracolsep{\fill}}l*{16}{c}}
\hline\hline
&\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}&\multicolumn{1}{c}{(3)}&\multicolumn{1}{c}{(4)}&\multicolumn{1}{c}{(5)}&\multicolumn{1}{c}{(6)}&\multicolumn{1}{c}{(7)}&\multicolumn{1}{c}{(8)}&\multicolumn{1}{c}{(9)}&\multicolumn{1}{c}{(10)}&\multicolumn{1}{c}{(11)}&\multicolumn{1}{c}{(12)}&\multicolumn{1}{c}{(13)}&\multicolumn{1}{c}{(14)}&\multicolumn{1}{c}{(15)}\\
\hline
\# months    &       0.192\sym{*}  &       0.139         &       0.190\sym{*}  &       0.168         &      -0.019         &       0.070         &       0.065         &       0.139\sym{*}  &       0.185         &       0.072         &       0.018         &       0.047         &      -0.088         &       0.000         &     -17.812                 \\
            &      (1.65)         &      (1.28)         &      (1.71)         &      (1.13)         &     (-0.17)         &      (0.94)         &      (0.48)         &      (1.78)         &      (1.26)         &      (0.70)         &      (0.21)         &      (0.26)         &     (-0.86)         &         (.)         &     (-1.03)                \\
[1em]
\# quartals  &       0.557         &       0.406         &       0.525         &       0.485         &      -0.068         &       0.227         &       0.175         &       0.437\sym{*}  &       0.539         &       0.206         &       0.063         &       0.107         &      -0.244         &       0.000         &     -55.164             \\
            &      (1.63)         &      (1.25)         &      (1.58)         &      (1.09)         &     (-0.20)         &      (1.02)         &      (0.43)         &      (1.87)         &      (1.23)         &      (0.69)         &      (0.24)         &      (0.19)         &     (-0.80)         &         (.)         &     (-1.03)                \\
[1em]
\# years     &       2.508\sym{*}  &       1.999         &       2.282\sym{*}  &       2.556         &      -0.405         &       0.951         &       1.366         &       1.750\sym{*}  &       1.923         &       1.004         &       0.573         &       0.756         &      -1.194         &       0.000         &    -234.503              \\
            &      (1.85)         &      (1.54)         &      (1.68)         &      (1.45)         &     (-0.31)         &      (1.12)         &      (0.86)         &      (1.87)         &      (1.09)         &      (0.87)         &      (0.54)         &      (0.35)         &     (-0.95)         &         (.)         &     (-1.04)               \\
\hline\hline
\end{tabular*}
\end{subtable}

\hfill

\begin{subtable}{\linewidth}
\centering
\small
\caption{A subtable}\label{tab:1b}
\begin{tabular*}{\linewidth}{@{\extracolsep{\fill}}l*{16}{c}}
\hline\hline
            &\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}&\multicolumn{1}{c}{(3)}&\multicolumn{1}{c}{(4)}&\multicolumn{1}{c}{(5)}&\multicolumn{1}{c}{(6)}&\multicolumn{1}{c}{(7)}&\multicolumn{1}{c}{(8)}&\multicolumn{1}{c}{(9)}&\multicolumn{1}{c}{(10)}&\multicolumn{1}{c}{(11)}&\multicolumn{1}{c}{(12)}&\multicolumn{1}{c}{(13)}&\multicolumn{1}{c}{(14)}&\multicolumn{1}{c}{(15)}\\
\hline
\# months    &       0.396\sym{*}  &      -0.017         &       0.008         &       0.197         &       0.056         &       0.032         &       0.202         &       0.131         &       0.461\sym{*}  &       0.174         &       0.299         &      -0.310         &       0.283         &       0.000         &       0.398\sym{*}       \\
            &      (1.83)         &     (-0.52)         &      (0.03)         &      (0.97)         &      (0.78)         &      (0.71)         &      (1.47)         &      (0.79)         &      (1.74)         &      (1.29)         &      (1.34)         &     (-1.15)         &      (1.06)         &         (.)         &      (1.78)               \\
[1em]
\# quartals  &       1.178\sym{*}  &      -0.057         &       0.018         &       0.593         &       0.172         &       0.098         &       0.610         &       0.400         &       1.329\sym{*}  &       0.490         &       0.918         &      -0.985         &       0.862         &       0.000         &       1.156\sym{*}          \\
            &      (1.82)         &     (-0.58)         &      (0.02)         &      (0.98)         &      (0.80)         &      (0.72)         &      (1.49)         &      (0.80)         &      (1.68)         &      (1.25)         &      (1.39)         &     (-1.22)         &      (1.08)         &         (.)         &      (1.78)             \\
[1em]
\# years     &       4.416\sym{*}  &      -0.317         &      -0.509         &       0.981         &       0.399         &       0.318         &       1.595         &       1.341         &       4.897         &       2.038         &       4.193         &      -4.298         &       3.354         &       0.000         &       4.519               \\
            &      (1.71)         &     (-0.83)         &     (-0.18)         &      (0.41)         &      (0.46)         &      (0.67)         &      (0.96)         &      (0.70)         &      (1.55)         &      (1.37)         &      (1.59)         &     (-1.36)         &      (1.04)         &         (.)         &      (1.64)               \\
\hline\hline
\end{tabular*}
\end{subtable}
\end{table}

\end{landscape}

\end{document}


text:
Q: Memory conservative maximal independent set of vertices I want to find a memory conservative yet efficient algorithm for maximal independent vertices set in a undirected graph.
The traditional algorithms use auxiliary data structures (a copy of the original graph) to implement it. I would like to avoid such parallel structure because the memory allocations are slow for a realtime implementation on and I have some memory boundaries.
I just want to mark the nodes in the MIS with a boolean label.
Is it possible?
Note that I don't want the maximum independent but a maximal independent set.
P.S.
I know that this problem is language independent but I'm coding in C++ and STL.

A: Here is a solution if you have only your boolean label(i) for each node i. It takes time O(|V|+|E|), where |V| is the number of nodes and |E| is the number of edges in your input graph.
For all nodes v
   set label(v)=false;
For all nodes v
   if (all neighbors w of v have label(w)=false)
      set label(v)=true

The nodes v with label(v)=true are a maximal independent set. They are independent, since, per construction any labeled node v cannot have a labeled neighbor. And they are a maximal set, since you are only activating labels and only leave a node v unlabeled if another already labeled neighbor w prevented it.
Optimization note: If the nodes are numbered 1...n you only need to check neighbors w=1..v-1, since any other w cannot have label(w)=true.

A: It's difficult to answer this kind of question without knowing exactly what your data structures are. The usual tricks for near in-place graph operations are stealing two bits that would otherwise be zero from pointers and making reversible changes to the graph structure, but I'm not sure how they apply here.
From reading what you've written, it seems that there is no way to iterate through the nodes in the graph without a traversal. How are you representing the stack for, e.g., DFS?

A: I use a scratch vector or deque<bool> used to indicate which vertices are used by elements, or edges, or facets, ...
std::deque<bool> used(vertex.size(), false);
for (size_t e = 0; e < edge.size(); ++e)
{
    used[edge[e].v1] = true;
    used[edge[e].v2] = true;
}

Now used == true indicates all the used vertices.  The others could be collapsed out if you wanted.


text:
Q: using less instead of css totally and attach .less to head tag im new to less framework
i wanna know can i use less instead of css totally ?
and i attached less.js and my style.less to head tag like
<link rel="stylesheet/less" type="text/css" href="style.less" />
<script src="less.js" type="text/javascript"></script>(correctly url and names)

and in my style.less i have been write
@color: #5B83AD;

body { backgorund : @color  }

but i had'nt been see any changes . now whats the problem ? im using Wamp
thanks

A: backgorund : @color
You should try  background : @color
If you'd use a compiler you'd have receive a notification about the typo error


text:
Q: Java Web Start: unsigned cglib I am using hibernate on the server side with a client application started via Java Web Start.
I can't sign the jars (I'd like to but I can't). I get a permission exception when I get a POJO with lazy fields.
Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission cglib.debugLocation read)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
    at java.lang.System.getProperty(Unknown Source)
    at net.sf.cglib.core.DebuggingClassWriter.(DebuggingClassWriter.java:35)
    ... 44 more
How can I avoid that? I thought about setting the collection to null before returning the pojo to the client but I'd like to find a better solution.

A: You have two options:

*

*sign all jars in you application;

*change bytecode provider from cglib
to javassist which doesn't such
behavior (i.e. you can sign only
necessary jars).-

See also news regarding the issue here.

A: Since you can't use the unresolved lazy Hibernate fields on the client side anyway (accessing them, would cause the client to try to load the fields from the db) I would choose on of two options:

*

*If you need the data on the client side, you must make sure that the lazy fields are resolved by the server before returning the POJO to the client.

*If you don't need the fields, I would set them to null.


text:
Q: MVC4 WebApi Controller Post Action with Dispose Pattern causes Multiple Actions Found Exception I think I've spotted a problem with the MVC4 WebApi Controller in conjunction with the Dispose Pattern. The problem is with the Post Action Method, the response is a description of the Exception:
Multiple actions were found that match the request:
Void Post(System.String) on type MVC4Api.Controllers.ValuesController
Void Dispose() on type MVC4Api.Controllers.ValuesController

The dispose pattern is sourced from this article. I've reduced the problem to just the boiler plate code below. Its worth pointing out that this problem does not occur with the Get method, I have confirmed it only with the Post method. Please try it out by Posting to the path /api/values.
public class ValuesController : ApiController
{
    public void Post([FromBody]string value)
    {
    }

    private bool _disposed;

    protected override void Dispose(bool disposing)
    {
        if (_disposed)
        {
            return;
        }

        _disposed = true;

        base.Dispose(disposing);

        if (disposing)
        {
            // dispose of dependencies
        }
    }

    public new void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

My question is how can I call the Post Method? And what is causing this problem?
EDIT:
As the error is about routing I have added below the WebApiConfig which controls the routing. This is loaded as normal at start up in the Global.asax and has not changed since starting a new WebApi project.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

A: Its much easier to understand the solution when you correctly interpret the error message: When making the choice to the request, the WebApi Action Selector cannot decide between the Dispose() and Post() methods. (Which seems pretty daft in itself). So the error is effectively asking us to help make this decision for it.
My preferred option is to use the NonActionAttribute class on the Dispose() Action method. This is a clear and transparent instruction to the Action Selector to not consider the Dispose method in deciding where to route the request.
[NonAction]
public new void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

The other option is to change the accessor of the Dipose() method to protected, but that's just not as obvious.


text:
Q: Translating an Excel concept into SQL Let's say I have the following range in Excel named MyRange:

This isn't a table by any means, it's more a collection of Variant values entered into cells. Excel makes it easy to sum these values doing =SUM(B3:D6) which gives 25. Let's not go into the details of type checking or anything like that and just figure that sum will easily skip values that don't make sense.
If we were translating this concept into SQL, what would be the most natural way to do this? The few approaches that came to mind are (ignore type errors for now):

*

*MyRange returns an array of values:
-- myRangeAsList = [1,1,1,2, ...]
SELECT SUM(elem) FROM UNNEST(myRangeAsList) AS r (elem);

*MyRange returns a table-valued function of a single column (basically the opposite of a list):
 -- myRangeAsCol = (SELECT 1 UNION ALL SELECT 1 UNION ALL ...
 SELECT SUM(elem) FROM myRangeAsCol as r (elem);

*Or, perhaps more 'correctly', return a 3-columned table such as:
 -- myRangeAsTable = (SELECT 1,1,1 UNION ALL SELECT 2,'other',2 UNION ALL ...
 SELECT SUM(a+b+c) FROM SELECT a FROM myRangeAsTable (a,b,c)

Unfortunately, I think this makes things the most difficult to work with, as we now have to combine an unknown number of columns.
Perhaps returning a single column is the easiest of the above to work with, but even that takes a very simple concept -- SUM(myRange) and converts into something that is anything but that: SELECT SUM(elem) FROM myRangeAsCol as r (elem).
Perhaps this could also just be rewritten to a function for convenience, for example:

A: Just possible direction to think
create temp function extract_values (input string)
returns array<string> language js as """
  return Object.values(JSON.parse(input));
""";
with myrangeastable as (
  select '1' a, '1' b, '1' c union all
  select '2', 'other', '2' union all
  select 'true', '3', '3' union all
  select '4', '4', '4'
)
select sum(safe_cast(value as float64)) range_sum
from myrangeastable t,
unnest(extract_values(to_json_string(t))) value

with output

Note: no columns explicitly used so should work for any sized range w/o any changes in code
Depends on specific use case, I think above can be wrapped into something more friendly  for someone who knows excel to do

A: I'll try to pose, atomic, pure SQL principles that start with obvious items and goes to the more complicated ones. The intention is, all items can be used in any RDBS:

*

*SQL is basically designed to query tabular data which has relations. (Hence the name is  Structured Query Language).

*The range in excel is a table for SQL. (Yes you can have some other types in different DBs, but keep it simple so you can use the concept in different types of DBs.)

*Now we accept a range in the excel is a table in a database. Then the next step is how to map columns and rows of an excel range to a DB table. It is straight forward. An excel range column is a column in DB. And a row is a row. So why is this a separate item? Because the main difference between the two is usually in DBs, adding new column is usually a pain, the DB tables are almost exclusively designed for new rows not for new columns. (But, of course there are methods to add new columns, and even there exists column based DBs, but these are out of the scope of this answer.)

Items 2 and 3 in Excel and in a DB:

/*
Item 2: Table
    the range in the excel is modeled as the below test_table
Item 3: Columns
    id keeps the excel row number
    b, c, d are the corresponding b, c, d columns of the excel
*/

create table test_table
(
    id integer,
    b varchar(20),
    c varchar(20),
    d varchar(20)
);

-- Item 3: Adding the rows in the DB
insert into test_table values (3 /* same as excel row number */ , '1', '1', '1');
insert into test_table values (4 /* same as excel row number */ , '2', 'other', '2');
insert into test_table values (5 /* same as excel row number */ , 'TRUE', '3', '3');
insert into test_table values (6 /* same as excel row number */ , '4', '4', '4');

*Now we have similar structure. Then the first thing we want to do is to have equal number of rows between excel range and db table. At DB side this is called filtering and your tool is the where condition. where condition goes through all rows (or indexes for the sake of speed but this is beyond this answer's scope), and filters out which does not satisfy the test boolean logic in the condition. (So for example where 1 = 1 is brings all rows because the condition is always true for all rows.

*The next thing to do is to sum the related columns. For this purpose you have two options. To use sum(column_a + column_b) (row by row summation) or sum(a) + sum(b) (column by column summation). If we assume all the data are not null, then both gives the same output.

Items 4 and 5 in Excel and in a DB:

select sum(b + c + d) -- Item 5, first option: We sum row by row
    from test_table
    where id between 3 and 6; -- Item 4: We simple get all rows, because for all rows above the id are between 3 and 6, if we had another row with 7, it would be filtered out
+----------------+
| sum(b + c + d) |
+----------------+
|             25 |
+----------------+

select sum(b) + sum(c) + sum(d) -- Item 5, second option: We sum column by column
    from test_table
    where id between 3 and 6; -- Item 4: We simple get all rows, because for all rows above the id are between 3 and 6, if we had another row with 7, it would be filtered out
+--------------------------+
| sum(b) + sum(c) + sum(d) |
+--------------------------+
|                       25 |
+--------------------------+

*At this point it is better to go one step further. In the excel you have got the "pivot table" structure. The corresponding structure at SQL is the powerful group by mechanics. The group by basically groups a table according to its condition and each group behaves like a sub-table. For example if you say group by column_a for a table, the values are grouped according to the values of the table.

*SQL is so powerful that you can even filter the sub groups using having clauses, which acts same as where but works over the columns in group by or the functions over those columns.

Items 6 and 7 in Excel and in a DB:

-- Item 6: We can have group by clause to simulate a pivot table
insert into test_table values (7 /* same as excel row */ , '4', '2', '2');

select b, sum(d), min(d), max(d), avg(d)
    from test_table
    where id between 3 and 7
    group by b;
+------+--------+--------+--------+--------+
| b    | sum(d) | min(d) | max(d) | avg(d) |
+------+--------+--------+--------+--------+
| 1    |      1 | 1      | 1      |      1 |
| 2    |      2 | 2      | 2      |      2 |
| TRUE |      3 | 3      | 3      |      3 |
| 4    |      6 | 2      | 4      |      3 |
+------+--------+--------+--------+--------+

Beyond this point following are the details which are not directly related with the questions purpose:

*

*SQL has the ability for table joins (the relations). They can be thought like the VLOOKUP functionality in the Excel.

*The RDBSs have the indexing mechanisms to fetch the rows as quick as possible. (Where the RDBMSs start to go beyond the purpose of excel).

*The RDBSs keep huge amount of data (where excel the max rows are limited).

*Both RDBSMs and Excel can be used by most of frameworks as persistent data layer. But of course Excel is not the one you pick because its reason of existence is more on the presentation layer.

The excel file and the SQL used in this answer can be found in this github repo: https://github.com/MehmetKaplan/stackoverflow-72135212/
PS: I used SQL for more than 2 decades and then reduced using it and started to use Excel much frequently because of job changes. Each time I use Excel I still think of the DBs and  "relational algebra" which is the mathematical foundation of the RDBMSs.

A: So in Snowflake:
Strings as input:
if you have your data in a "order" table represented by this CTE:
and the data was strings of comma separated values:
WITH data(raw) as (
select * from values
    ('null,null,null,null,null,null'),
    ('null,null,null,null,null,null'),
    ('null,1,1,1,null,null'),
    ('null,2, other,2,null,null'),
    ('null,true,3,3,null,null'),
    ('null,4,4,4,null,null')
)

this SQL will select the sub part, try parse it and sum the valid values:
select sum(nvl(try_to_double(r.value::text), try_to_number(r.value::text))) as sum_total
from data as d
    ,table(split_to_table(d.raw,',')) r
where r.index between 2 and 4 /* the column B,C,D filter */
    and r.seq between 3 and 6 /* the row 3-6 filter */
;

giving:

SUM_TOTAL

25

Arrays as input:
if you already have arrays.. here I am smash those strings into STRTOK_TO_ARRAY in the CTE to make me some arrays:
WITH data(_array) as (
select STRTOK_TO_ARRAY(column1, ',') from values
    ('null,null,null,null,null,null'),
    ('null,null,null,null,null,null'),
    ('null,1,1,1,null,null'),
    ('null,2, other,2,null,null'),
    ('null,true,3,3,null,null'),
    ('null,4,4,4,null,null')
)

thus again with almost the same SQL, but not the array indexes are 0 based, and I have used FLATTEN:
select sum(nvl(try_to_double(r.value::text), try_to_number(r.value::text))) as sum_total
from data as d
    ,table(flatten(input=>d._array)) r
where r.index between 1 and 3 /* the column B,C,D filter */
    and r.seq between 3 and 6 /* the row 3-6 filter */
;

gives:

SUM_TOTAL

25

With JSON driven data:
This time using semi-structured data, we can include the filter ranges with the data.. and some extra "out of bounds values just to show we are not just converting it all.
WITH data as (
    select parse_json('{ "col_from":2,
                      "col_to":4,
                      "row_from":3,
                      "row_to":6,
                      "data":[[101,102,null,104,null,null],
                   [null,null,null,null,null,null],
                   [null,1,1,1,null,null],
                   [null,2, "other",2,null,null],
                   [null,true,3,3,null,null],
                   [null,4,4,4,null,null]
                   ]}') as json
)
select
   sum(try_to_double(c.value::text)) as sum_total
from data as d
    ,table(flatten(input=>d.json:data)) r
    ,table(flatten(input=>r.value)) c
where r.index+1 between d.json:row_from::number and d.json:row_to::number
  and c.index+1 between d.json:col_from::number and d.json:col_to::number
;

A: Here is another solution using Snowflake scripting (Snowsight format) . This code can easily be wrapped as a stored procedure.
declare
    table_name := 'xl_concept';  -- input
    column_list := 'a,b,c';      -- input
    total resultset;             -- result output
    pos int := 0;                -- position for delimiter
    sql := '';                   -- sql to be generated
    col := '';                   -- individual column names
begin
    sql := 'select sum(';  -- initialize sql
    loop -- repeat until column list is empty
        col := replace(split_part(:column_list, ',', 1), ',', ''); -- get the column name
        pos := position(',' in :column_list); -- find the delimiter
        sql := sql || 'coalesce(try_to_number('|| col ||'),0)'; -- add to the sql
        if (pos > 0) then -- more columns in the column list
            sql := sql || ' + ';
            column_list := right(:column_list, len(:column_list) - :pos); -- update column list
        else -- last entry in the columns list
            break;
        end if;
    end loop;
    sql := sql || ') total from ' || table_name||';'; -- finalize the sql
    total := (execute immediate :sql); -- run the sql and store total value
    return table(total); -- return total value
end;

only these two variables need to be set table_name and column_list
generates the following sql to sum up the values
select sum(coalesce(try_to_number(a),0) + coalesce(try_to_number(b),0) + coalesce(try_to_number(c),0)) from xl_concept
prep steps
create or replace temp table xl_concept (a varchar,b varchar,c varchar)
;
insert into xl_concept
with cte as (
  select '1' a, '1' b, '1' c union all
  select '2', 'other', '2' union all
  select 'true', '3', '3' union all
  select '4', '4', '4'
)
select * from cte
;

result for the run with no change
TOTAL
25

result after changing column list to  column_list := 'a,c';
TOTAL
17

Also, this can be enhanced setting columns_list to * and reading the column names from information_schema.columns to include all the columns from the table.

A: In PostgreSQL regular expression can be used to filter non numeric values before sum
select sum(e::Numeric) from (
  select e
    from unnest((Array[['1','2w','1.2e+4'],['-1','2.232','zz']])) as t(e)
    where e  ~ '^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$'
) a

expression for validating numeric value was taken from post Return Just the Numeric Values from a PostgreSQL Database Column
More secure option is to define function as in PostgreSQL alternative to SQL Servers try_cast function
Function (simplified for this example):
create function try_cast_numeric(p_in text)
   returns Numeric
as
$$
begin
  begin
    return $1::Numeric;
  exception
    when others then
       return 0;
  end;
end;
$$
language plpgsql;

Select
select
  sum(try_cast_numeric(e))
from
  unnest((Array[['1','2w','1.2e+4'],['-1','2.232','zz']])) as t(e)

A: Most modern RDBMS support lateral joins and table value constructors. You can use them together to convert arbitrary columns to rows (3 columns per row become 3 rows with 1 column) then sum. In SQL server you would:
create table t (
    id int not null primary key identity,
    a  int,
    b  int,
    c  int
);

insert into t(a, b, c) values
(   1,    1, 1),
(   2, null, 2),
(null,    3, 3),
(   4,    4, 4);

select sum(value)
from t
cross apply (values
    (a),
    (b),
    (c)
) as x(value);

Below is the implementation of this concept in some popular RDBMS:

*

*SQL Server

*PostgreSQL

*MySQL

*Generic solution, ANSI SQL

*Unpivot solution, Oracle

A: Using regular expression to extract all number values from a row could be another option, I guess.
DECLARE rectangular_table ARRAY<STRUCT<A STRING, B STRING, C STRING>> DEFAULT [
  ('1', '1', '1'),  ('2', 'other', '2'), ('TRUE', '3', '3'), ('4', '4', '4')
];

SELECT SUM(SAFE_CAST(v AS FLOAT64)) AS `sum`
  FROM UNNEST(rectangular_table) t,
       UNNEST(REGEXP_EXTRACT_ALL(TO_JSON_STRING(t), r':"?([-0-9.]*)"?[,}]')) v

output:
+------+------+
| Row  | sum  |
+------+------+
|    1 | 25.0 |
+------+------+

A: You could use a CTE with a SELECT FROM VALUES
with xlary as
(
  select val from (values
                   ('1')
                   ,('1')
                   ,('1')
                   ,('2')
                   ,('OTHER')
                   ,('2')
                   ,('TRUE')
                   ,('3')
                   ,('3')
                   ,('4')
                   ,('4')
                   ,('4')
                  ) as tbl (val)
)
select sum(try_cast(val as number)) from xlary;


text:
Q: How to do unlike the wall post which is like by the user in facebook using the graph API I want to do unlike the wall post which is like by the user in facebook..
and I am using the graph API in android for mobile Application...

A: It is really simple and worked for me in past. Fire a id_of_comment_you_already_liked/unlike request.


text:
Q: Stored Procedure delete statement after return So I'm tracking down a potential bug in a sync process I'm in charge of (written by someone else). When viewing one of the stored procedures that is being called, I noticed something peculiar. Based on my understanding of returns, anything after the return will not be returned. However, I am not positive if this is the case in SQL. Based on the chunk of SQL below, will the delete statement ever run? Or does the SP return information to signify whether rows were deleted (such as how many rows, whether it was successful, etc.)? I am assuming this is a bug in the SP, but want to confirm before taking action. Thanks in advance.
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[DeleteSalesforce_Contacts]
AS
Return
Delete From dbo.Contacts Where IsDeleted = 1

GO

A: The documentation is pretty clear on this:

"Exits unconditionally from a query or procedure. RETURN is immediate
  and complete and can be used at any point to exit from a procedure,
  batch, or statement block. Statements that follow RETURN are not
  executed."

The delete statement won't be executed.
The return statement takes an optional parameter, but to use a query as value you would need to use a select in parentheses. Example:
return (select top 1 id from SomeTable)

A: The delete would never happen when the proc is executed.
The only time a statement after the return is ever executed when a proc is run is if it was related to a goto process and the code was sent there and bypassed the return. This kind of code sometimes used to be written before Try Catch blocks were allowed in SQL Server to do something with errors.


text:
Q: How do I get the values in PROGRAM 2 to apply to printing in the console? Okay so I technically have everything working in the program, but I need to permanently change the values of the array that I create in PROGRAM 2 and add -blip and -clang. What do I call upon to change the values so that I can call them to the console in PROGRAM 3? I can't have anything in the body so innerHTML and document.write are out of the question(which sucks). Problem area is marked with a comment on line 37 to make it easier to find.
<!DOCTYPE html>

<title>Project 1 – Michael Fiorello</title>

A: It was so simple that I feel like an idiot. All I had to do was change the document.write lines to
res[i] = (res[i]+"-blip ");

and it changes the values to what I need.


text:
Q: Stream to Windows Media Player with c++ I have to read encrypted music or video from USB drive, decrypt it on the fly as a stream, and send it to mp3 player.
I can already read the file from the USB and decrypt it on the fly in chunks, but now I need to send the chunked data somewhere to play it, for example windows media player (WMP).
WMP requires a URL to the music/video source, so I figure I would create a stream in memory and give that to WMP as the URL. Then when WMP starts reading from the stream, it would somehow call my function which would then read a chunk of data from the USB, decrypt it, and put it to the stream to be played by WMP.
Anybody knows how to create a URL stream, and then get notified when the stream wants data?
Im using Visual C++ MFC/Win32.
Thanks

A: The WMP requires an URL, which can be the name of a file or a HTTP(S) URL that delivers the file data. In your case, the HTTP option would seem a good choice so you get notified when data is needed. For this to work you have to implement your own tiny HTTP server, preferably on an ephemeral port. So, you have your music file in memory and set up a HTTP server to deliver the file data. The URL for example will be something like http://127.0.0.1:5432/MusicFile.mp3, which you specify to WMP. Your web server will then receive a request for the file and you can start sending it.
As a note, using a (non-persisted) memory-mapped file should also work. However, you indicate that you want to be notified and it's not clear if that's just to be able to deliver data.


text:
Q: attribute aligned crossplatform Is GCC's
union uint128_t {
    uint64_t q[2];
    uint64_t w[8];
    char b[16];
} __attribute__((aligned (16)));

is the same as (crossplatform):
union alignas(16) uint128_t {
    uint64_t q[2];
    uint64_t w[8];
    char b[16];
};

?

A: Yes.  See __attribute__((aligned)) and alignas.
If you are asking "why does <some library> use __attribute__ rather than alignas?"  I suspect the the answer is "because alignas is relatively new, but __attribute__ has been supported for much longer."


text:
Q: Correct Scope for vaadin 8 and spring I have a project, work with Vaadin 8.6 and Spring 5, and vaadin-spring 3.1.1
In this, there is MainUI extends UI that a bean with scope="prototype" initialized in web-application-context.xml
Problem: when we connect to project from more than one client (browser), there is only one session available.
we search and find some manuals, but we can not use it in our project
<bean id="mainUI" class="ir.fanap.fanitoring.ui.MainUI" scope="prototype">

Vaadin Spring Add-on
how can we solve this problem? we did not use annotations for beans and all beans initialized in web-application-context.xml


text:
Q: Azure Automation Powershell I trying to automate to retrieve data from azure SQL database from azure automation run book power shell. I found that the SQL Server module was missing in the modules of azure automation account. I have imported that module. But still that command is not working.
SQL server module has been imported to azure automation run book . I've attached the modules image below.

But when I run the command "Invoke-Sqlcmd" from the azure automation run book test pane it throws the below error.

A: If I import default SqlServer version(21.0.17224) from Modules gallery, I also can reproduce the issue you mentioned.

The term 'Invoke-Sqlcmd' is not recognized as the name of a cmdlet

Please have a try to use the SqlServer 21.0.17199, it works correctly on my side.

A: Invoke-Sqlcmd was not working in azure automation runbook powershell.
So I used to powershell workflow to execute that query. It executed successfully. The below command is a powershell work flow runbook which connects to a database and executes the query.
workflow "runbookValue"
{
inlinescript
{
    $MasterDatabaseConnection = New-Object System.Data.SqlClient.SqlConnection
    $MasterDatabaseConnection.ConnectionString = "ConnectionStringValue"

    # Open connection to Master DB
    $MasterDatabaseConnection.Open()

    # Create command
    $MasterDatabaseCommand = New-Object System.Data.SqlClient.SqlCommand
    $MasterDatabaseCommand.Connection = $MasterDatabaseConnection
    $MasterDatabaseCommand.CommandText = "<execute the query>"

    # Execute the query
    $MasterDatabaseCommand.ExecuteNonQuery()

    # Close connection to Master DB
    $MasterDatabaseConnection.Close()
}
}


text:
Q: Combinations of features using Python NumPy For an assignment I have to use different combinations of features belonging to some data, to evaluate a classification system. By features I mean measurements, e.g. height, weight, age, income. So for instance I want to see how well a classifier performs when given just the height and weight to work with, and then the height and age say. I not only want to be able to test what two features work best together, but also what 3 features work best together and would like to be able to generalise this to n features.
I've been attempting this using numpy's mgrid, to create n dimensional arrays, flattening them, and then making arrays that use the same elements from each array to create new ones. Tricky to explain so here is some code and psuedo code:
import numpy as np

def test_feature_combos(data, combinations):
    dimensions = combinations.shape[0]
    grid = np.empty(dimensions)
    for i in xrange(dimensions):
        grid[i] = combinations[i].flatten()
    #The above code throws an error "setting an array element with a sequence" error which I understand, but this shows my approach.

    **Pseudo code begin**
    For each element of each element of this new array,
    create a new array like so:
    [[1,1,2,2],[1,2,1,2]] --->  [[1,1],[1,2],[2,1],[2,2]]
    Call this new array combo_indices
    Then choose the columns (features) from the data in a loop using:
    new_data = data[:, combo_indices[j]]

combinations = np.mgrid[1:5,1:5]
test_feature_combos(data, combinations)

I concede that this approach means a lot of unnecessary combinations due to repeats, however I cannot even implement this so beggars can not be choosers.
Please can someone advise me on how I can either a) implement my approach or b) achieve this goal in a much more elegant way.
Thanks in advance, and let me know if any clarification needs to be made, this was tough to explain.

A: To generate all combinations of k elements drawn without replacement from a set of size n you can use itertools.combinations, e.g.:
idx = np.vstack(itertools.combinations(range(n), k)) # an (n, k) array of indices

For the special case where k=2 it's often faster to use the indices of the upper triangle of an n x n matrix, e.g.:
idx = np.vstack(np.triu_indices(n, 1)).T


text:
Q: ERR_CONNECTION_REFUSED to Apache2 server on same network
*

*So here is the scenario I've set up a phabricator server in house and
I can connect to it from other computers on the network just fine
using the internal IP address. "http://172.20.26.122/"

*I can also connect to it via the
domain name from outside the network without any issues
"phabricator.example.com"

*I can, on the machine itself, load up
"phabricator.example.com" without any issues
But I cannot go to "phabricator.example.com" from another computer on
the same network without getting the error message
"ERR_CONNECTION_REFUSED".
I am stumped on this problem and have looked all over for an answer. Does anyone have any ideas?

A: I solved my own question basically I had to alter the DNS settings on the LAN router to point to the specified internal IP address for the selected URL (FQDN).


text:
Q: ApiController routing seems to ignore action With routing like this defined in RouteConfig.cs
  routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Durandal", action = "Index", id = UrlParameter.Optional }
    );

I expected http://localhost:50441/api/Induction/GetIntro/4108 to parse as
Controller = InductionController
Action = "GetIntro"
Id = 4108

and call into the GetIntro method of this class
using System.Web.Http;

namespace MyMvcApp.Controllers
{
  public class InductionController : ApiController
  {
    public object GetIntro(int inductionId)
    {
      //simplified for brevity
      return new {
        Title = "foo",
        Text = "Some introductory blather"
      };
    }
  }
}

But it doesn't. I get a 404 Not Found, and the burning question is why.
Most samples seem to use MapHttpRoute instead of MapRoute, MapRoute being an extension method that wraps MapHttpRoute.

A: I was confused by the existence of RouteConfig.cs which also defines routes. It works like this:

*

*WebApi routes are configured by WebApiConfig.cs

*MVC routes are configured by RouteConfig.cs

*You get both because it's an MVC project with support for WebApi.

In my project the route defined in WebApiConfig.cs was api\{controller}\{id} and preceding this with another route api\{controller}\{action}\{id} resolved the problem.
The template generated CRUD methods worked because they match api\{controller}\{id}

A: You are trying url http://localhost:50441/api/Induction/GetIntro/4108
but you missed to add 'api' to your route definition
Change your route to this
 routes.MapRoute(
        name: "Default",
        url: "api/{controller}/{action}/{id}",
        defaults: new { controller = "Durandal", action = "Index", id = UrlParameter.Optional }
        );


text:
Q: EKS - Step function This question is about how to do this process. I have created a cluster named Python-Cluster with a nodegroup of 2 nodes. I wanted to deploy a python code into this pods.
import json
response = {}
def main(message):
    user_input = message['Payload']['Input']

    if user_input == 'Invoke':
        response['Output'] = "Invoked"
        response['Message'] = "First Job invoked based on the input"
        return response

I made this as an image and deployed using yaml as follows
apiVersion: apps/v1
kind: Deployment
metadata:
  name: python
spec:
  selector:
    matchLabels:
      app: python
  replicas: 2
  template:
    metadata:
      labels:
        app: python
    spec:
      containers:
      - name: python
        image: python-img:latest
        imagePullPolicy: Never
        ports:
        - containerPort: 5000

apiVersion: v1
kind: Service
metadata:
  name: python
spec:
  selector:
    app: python
  ports:
  - protocol: "TCP"
    port: 6000
    targetPort: 5000
  type: LoadBalancer

Now i wanted to use step function to give input to the python image. So i created an step function to run EKS job.
{
  "Comment": "A Hello World example of the Amazon States Language using Pass states",
  "StartAt": "Run a job on an EKS Cluster",
  "States": {
    "Run a job on an EKS Cluster": {
  "Type": "Task",
  "Resource": "arn:aws:states:::eks:runJob.sync",
  "Parameters": {
    "ClusterName": "Python-Cluster",
    "CertificateAuthority": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvakNDQWVhZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1Ea3lPREF6TlRnd01Wb1hEVE15TURreU5UQXpOVGd3TVZvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBSzFWCjhldTRxWEVoVk8xazcyNVkyeHd3ZUtMYzRoZUp2RXhqSzFybXNMYmhmcGw0aTV6Ni9kVThtdUZZNzRXRlB4SDUKTWpoeXlTeStoTnZSdWlaNnFZR21XcTZ0akZBUHZhMkR1dlBGTm5rVW5rN0hKcm5qRHR6dHIvWHNKZWNuRWFXegowdzIxM1NTdm1mSlpmUGZmWXUwQjVJTjVKVXJoTTE5UG9KTHg5WHNjeWpSZCsvUXVaSzMvd1dHcmpEc2ZkM3VDCllkeWNNUklTeGt5MHB1cEltcEdINkxPOS9NSnJCU0h1eGhlNzdlRUVpMlFZaTlZU1lXTnVzZkNVZVJvbUx5NDUKY0RDdnh4YlFmUk5FcUZSUnZURDR4V0ZpR2EzN0RrZkZ3Uzk3bWVxM2JwTkNwbDBLTTZtTlR1VEMwcTliRXlrbQpmNFZzbTB0Y29oMExGd0UySEpVQ0F3RUFBYU5aTUZjd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0hRWURWUjBPQkJZRUZLandYckdKc2xlTjFFbFVBRkNhb1czdjVYNWpNQlVHQTFVZEVRUU8KTUF5Q0NtdDFZbVZ5Ym1WMFpYTXdEUVlKS29aSWh2Y05BUUVMQlFBRGdnRUJBRkJQSi9vaUZuc3VoMHQyNVZrMgovcyt3T1JrWWJGWjFEQnA0SmxLZ2dlT2tkR05QRkxtNkwrbXVaY3JxYUpiNml2OHdjVUNjQkROTEVLMEpGa3BsCjhYTklRaW9nTlpoQklJYzdSbm5HK2NpMUNLazhzOFNacUNNM210ZmdhYmwxVDNYem9zc0hFMkRaZGdLSUYya0QKMHpZUkM0L3NFMUtQVkU5NVB3VkFwVDN0eE1WYmdDRkdYV3huNmlPK1RSWWwvN1ZlWjRSUUZCaXJCSm01L1NGUQpmMkk0V3lWZTkvK2k1Q3k1WW1qQWdYYXd3VVBKM2cwU0pNRUhDV0VvVmhFK0VudEJDTFEvL0I0UTUrNlRacXFFCi9GSURsejJZY3BsMDJ1ZnlkTU5TR2ZGdi9XU01QU21YWVdHbWp0MzZmb1lvd1A1WDRJVVc0MlhVbG5NZSt0L0EKY0hNPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==",
    "Endpoint": "https://82EDCAF2DEA2FD8AF20E184476B547CB.gr7.us-east-1.eks.amazonaws.com",
    "Job": {
      "apiVersion": "batch/v1",
      "kind": "Job",
      "metadata": {
        "name": "my-example-job"
      },
      "spec": {
        "template": {
          "metadata": {
            "name": "my-example-job"
          },
          "spec": {
            "containers": [
              {
                "name": "python-7f7c9cdbc6-fvtvl",
                "image": "python-7f7c9cdbc6-fvtvl",
                "command": [
                  "python"
                ]
              }
            ],
            "restartPolicy": "Never"
          }
        }
      }
    },
    "LogOptions": {
      "RetrieveLogs": true,
      "RawLogs": true
    }
  },
  "End": true
  }
  }
}

When running the state machine i get EKS.401 error, i have given step function admin access. I have added the IAM role in the config file as well... What should i do?
Thanks and regards


text:
Q: Create symlink to the final target of another symlink Suppose a have a symlink named A
If I execute this:
ln A B -s

then B points to A, having created a chain of symlinks: B->A->some
Is there any option for ln to link directly to the final target, without writing it explicitly? to get B->some?
I would do that with readlink like this:
ln "$(readlink A -f)" B -s

But I think it should exist some option do it just with ln.

A: That option doesn't exist in "standard" ln; the target path is always taken as a literal string with no other processing.
However, if the symlink points to an absolute path (i.e. readlink A == readlink -f A), you can copy the symlink instead:
cp -a A B

(This will also happen to work with relative symlinks if both symlinks are in the same directory, and in some other limited situations.)
Additionally, in GNU Coreutils' ln, you can use the -r/--relative option to achieve this:
ln -s -r A B

(As the name implies, this will always result in a relative symlink being made – even if the original was pointing to an absolute path. It would be nice if there was also an opposite option for converting relative inputs into absolute targets, but currently there isn't one.)


text:
Q: How do you zoom in/out inside an app on ARC welder? APK is installed and game is working. How do you zoom in or out inside the app?

A: For most apps the answer will be "you cant", especially if you are not using a touchscreen Chromebook. One way around this for developers, would be to add zoom functionality by handling KeyEvents.
I am unsure if there is a way to programmably catch chromebook gestures in android code.


text:
Q: Wrongly documented TI LM324 unity-gain bandwidth? I was reading the datasheet of the LM324 from TI (http://www.ti.com/lit/ds/symlink/lm324.pdf).
They specify a generic GBW of 1.2MHz. This is usually done with no output applied, from what I understand.
Then there is the \$ A_{vd} \$ which is max 100K (100 V/mV). This is the open-loop gain measured with a load, so taking into account loading effects, if I get it right.
Is this gain really reducing by a factor of 10 with few \$ k \Omega \$ on the output?
To understand this better, I read the SLOA11 from TI. They mention \$ B_1 \$ to be the bandwidth at unity-gain with a load specified under the \$ A_{vd} \$ measurement, which should result in a BW of 100kHz. Making it different from the GBP measurement with no load (resulting in unity BW of 1.2 MHz). But in the LM324 datasheet, \$ B_1 = 1.2MHz\$ instead of \$ 100kHz \$. So I am not sure here what are the correct terms and how to use them.

A:
They specify a generic GBW of 1.2MHz. This is usually done with no output applied, from what I understand. Then there is the Avd which is max 100K (100 V/mV). This is the open-loop gain measured with a load, so taking into account loading effects, if I get it right

Having a GBW product of 1.2 MHz doesn't mean that there is any frequency where the gain is 1.2 million. Having an open-loop DC gain of 100 V/mV doesn't mean that the gain must drop to 0 dB at or below 100 kHz.
Assuming this is an old-fashioned dominant-pole-compensated design, you could imagine that the DC gain is 100 V/mV and the dominant pole in the open loop response is at about 3-4 Hz, so that the response falls of at 20 dB/decade to reach 0 dB at 1.2 MHz.

A: I would reckon that the 100k figure is the gain at DC. Now if the dominant pole is at 12 Hz, then the GBW product above this frequency will be approximately 1.2 MHz. The output impedance of an opamp is normally of the order of 100 ohm so a load of a few k is not significant.