Circle of prisoners

Question: I do not know if the following game is well-defined:
Suppose that there are $n$ prisoners standing in a circle one after other $n\geq 2$ everyone holding a silent gun.
When a bulb lights all either kill the one standing before him or not in some time interval of a few seconds. You are the $1st$, w.l.o.g.W hat are all Nash Equlibria of this game on $n$ players the strategy for each $p\in[0,1]$ killing the one before you with probability $p$. If $n=2$ the one NE is $(1,1)$ i.e. hoping that you will kill your enemy first. If $n=3$ it is good not to kill the one in front of you hoping that she will kill the one behind you. So I think one NE is $(0,0,0).$ What are all NE in general for $n$ arbitrary (in mixed strategies) ?
If the definition of the game leaks somewhere someone may fix it.
EDIT
A less macabre way:
All $n$ free people have hats on their heads. Everything goes like above but with taking off their heads instead of shooting. If your hat remains you win 1$. If someone has n hat she is not allowed to take off the hat in front of him.
Comment: Couldn't you have illustrated the problem in a less macabre way ?
Comment: Yeah, I don't see it.  The moment anyone fires (be they successful or not) everyone loses any  motive for firing (since even success has no impact on the only person who poses a direct threat).  Nash games don't do well with a timing element, they tend to devolve either into inertia or into instant actions.  Anyway, good luck!
Comment: If a person can only shoot once and has either successfully eliminated their neighbor or has wasted their shot, then there is no point in any one else shooting.   After all, the only point of shooting is in a domino situation but dominos don't work after one domino is removed.
Comment: @Peter Oh yes, with hats or something ? It is based of a veru nice but brutal film I saw yesterday. Please, suggest some other setting.
Comment: The hat-version is nice.
Comment: Not sure I understand the rules.  What is $p$?  Do you mean that if I try to shoot my clockwise neighbor they are eliminated with probability $p$ and they survive with probability $1-p$?  If my immediate clockwise neighbor is gone, can I shoot the next one or are my options done with?  At the end of the allotted time, are all survivors freed?  What advantage do I get from eliminating my neighbor?  In the $n=3$ case, don't I profit from leaving them be (on hopes they eliminate my counterclockwise neighbor)?
Comment: @lulu No you are not allowed to shoot the next one. And yes after that time all remaining are freed.And yes, they are eliminated with probability $p$ and missed with $1-p$. That is exactly my question if the only NE is to leave your clockwise neighbor with $p=0$. It may be the case that you may profit from killing your neighbor because he might have eliminated someone next who will actually save you.
Comment: So...I gain nothing from the death of my clockwise neighbor?  Why would I shoot them?  I had assumed that you were trying for a Last Man Standing sort of thing, though of course that just becomes a speed contest.
Comment: @lulu For the first question read my comment above. For the second the game should be fixed somehow so as it doesn't become speed quest.
Comment: I don't get it.  Absent the speed component, I don't see how I profit (I am assuming that my utility function doesn't see an abstract positive in killing for its own sake).  Given the speed component, maybe you could argue that I'd like my counterclockwise neighbor, $X$,  to be gone (as I don't trust him) so I would like to eliminate the person who might eliminate the person who might eliminate $X$ but if we all fire (or not) at the same instant, even this does me no good.
Comment: @lulu Yes, you are beginning to understand what I mean. Your first sentence is correct whith what you say "no killing for it's own shake". So how to incorporate into the game that thing that solution will be based on this:  you want to eliminate the person who might eliminate the person who might eliminate 1st ? So how to fix the presence of the time interval ? You may suggest a completely other setting , perhaps not so macabre.
Comment: As I say, I think the rules need to be substantially rewritten or at least clarified.  Usually in these cases, inertia doesn't guarantee freedom.  But if you change the rules to say "this scenario repeats until we've got a Last Man Standing, or until everyone is gone" then of course I must fire whenever I can (as must everyone else).
Comment: @lulu The fixing of the time argument might be this: what if you have a missing your neighbor option which is high if you shoot too early ? So if you shoot at the time of the bulb lights oh, you miss with probabiloity $q=1$.
Comment: @lulu This is not Last Man Standing. All are freed right after 1st round who survived.
Comment: @lulu So the rules are: one round, missing is a differenatiable function of the time interval $q:[0,1]\to [0,1]$ (the bulb lights at 0) with $q(0)=0$ and $q(1)=1$ and a probability $p\in [0,1]$ that it is a NE that ith shoots.The task find all situations (strategy profiles for all n players) with $q$ commonly known.Shall I include this comment into the OQ ?
Comment: @lulu Could you please elaborate more your last comment ? Why "even success has no impact on the only person who poses a direct threat" ?
Answer: I'm not sure the discussions in the comments have really clarified the time element. I'll interpret the question to mean that the players shoot at different times and the order in which they shoot is random. The exact distribution of the possible shooting orders is irrelevant as long as there's a non-zero probability for each of the $n$ orders where the shooting goes around the table in the "forward" direction.
Everyone not shooting is always a Nash equilibrium, as nothing is to be gained if no one else shoots. In fact, any strategy profile in which two consecutive players don't shoot is a Nash equilibrium, as neither of them can gain from shooting instead (one because she won't get shot anyway, and the other because his target won't shoot anyway) and no one can influence their own chance of being shot if these two break the chain.
For odd $n$, the strategy profiles in which a single player shoots with probability $0$ are also Nash equilibria, since that player would only be making it worse for themselves (making it worse? how could it be worse?!) if they increase that probability, and no one else can influence their own chance of being shot because of the break in the chain. If all players shoot with non-zero probabilities, they can all gain from lowering their probability, so such a strategy profile isn't a Nash equilibrium.
However, for even $n$, a single player with probability $0$ gains by increasing that probability, and once they close the chain, everyone gains from increasing their probability, so in this case the only Nash equilibrium in addition to the ones with two consecutive non-shooters is the one where everyone shoots with probability $1$.

Circle of prisoners


Oracle PL/SQL Parameter value from parameter name in String

Question: Hi I need to retrieve a parameter value where the parameter name is in different parameter.
Lets say the proc is as below
PROCEDURE findValue
(
    p_date             IN VARCHAR2,
    p_name             IN VARCHAR2,
    p_class             IN VARCHAR2,
    p_paramname             IN VARCHAR2,
)
IS

Now lets say i want to pass p_paramname as p_date and further use the value of p_date parameter in PL/SQL block, how do i use it ?
Comment: What is the business problem that you are trying to solve?  Obviously, you could have an `IF` block that looks at different values of `p_paramname` and executes different bits of code depending on the value.  I'm guessing, however, that isn't what you're asking...
Comment: What is the relationship among the various procedures that your wrapper procedure would be calling?  If you're trying to build something very dynamic, you're probably approaching the problem incorrectly.  But if the procedures that the wrapper procedure would be calling are all very similar in nature, their signatures should be similar as well.
Comment: How many possible parameter sets are you trying to support?  You could get into dynamic PL/SQL but that will generally produce pretty complicated code that is pretty difficult to support, maintain, and debug.
Comment: Hi Justin, I am trying to make a wrapper procedure that can call different types of functions having each different number of parameters. They way i am thinking is to get the order of parameters (`p_name,p_class`) to be passed in lets say `p_paramname` and further use the values in the function call.
Comment: The signature of various procedure being called is different and i cannot change it now for backward compatibility. The various functions being called are independent and i want to use this wrapper to be able to call any of them dynamically so i can use it with other application.
Comment: I am trying to support 5 parameters whose order and number would come in one parameter, and am open to dynamic sql as well, but still not able to implement it.
Answer: If you can afford PL/SQL table inputs then try the logic below:
CREATE TYPE param_tbl_type IS TABLE OF VARCHAR2(255);

CREATE OR REPLACE FUNCTION
    (p_param_names param_tbl_type,
     p_param_values param_tbl_type)
RETURN VARCHAR2
IS
    l_dyn_func_str VARCHAR2(4000);
    l_ret_val VARCHAR2(4000);
    vCursor integer;
    fdbk PLS_INTEGER;
BEGIN

   -- make sure you have equal number of params and currespondin values.
   -- Index much match too. i.e. if p_param_names(0) is 'p_currency' then p_param_value(0) must be 'USD' (value of currency)
   IF p_param_names.COUNT <> p_param_values.COUNT THEN
      raise_application_error(-2000,'Incorrect number of arguments');
   END IF;

   -- use this variable to generate anonymous block code
   l_dyn_fun_str:='BEGIN :retval :=  function_tobe_called (';

   -- loop through each parameter and add to the parameter list
   FOR i in 1..p_param_names.COUNT LOOP
      IF i=0 THEN
        l_dyn_fun_str:=l_dyn_fun_str||':'||l_param_name(i);
      ELSE
        l_dyn_fun_str:=l_dyn_fun_str||','||':'||l_param_name(i);
      END IF;
   END LOOP;

   l_dyn_fun_str:=l_dyn_fun_str||'); END;'

   -- open cursor and associate with function call string (l_dyn_fun_str)
   vCursor:=DBMS_SQL.OPEN_CURSOR;
   DBMS_SQL.PARSE(vCursor,l_dyn_fun_str);

   -- loop through parameter values and associate them with bind variables
   DBMS_SQL.BIND_VARIABLE(vCursor,':retval',l_ret_val);
   FOR j in 1..p_param_values.COUNT LOOP
      DBMS_SQL.BIND_VARIABLE(vCursor, ':'||l_param_names(j), l_param_values(j));
   END LOOP;
   -- execute function
   fdbk := DBMS_SQL.EXECUTE (vCursor);

   -- get output of function
   DBMS_SQL.VARIABLE_VALUE (vCursor, 'retval', l_ret_val);
   RETURN l_ret_val;

END;

Note: The code syntax may not be perfect but the pseudo should still work for your requirement.
Comment: Thanks Brainhash, If you look at my comment above for what i am trying to accomplish , this solution could get very big and difficult to implement .
Comment: @user3842265 how exactly the above will be difficult? can you provide more examples/sample code with expected output.
Comment: Edited my answer. Please review.  You may need some minor tweaks but hope it helps
Comment: Thanks, this helped me out to plan for how i could handle this.
Answer: Just check the value of P_PARAMNAME against the possible parameter names and branch accordingly.  E.g.,
CREATE OR REPLACE PROCEDURE matt_test1 (p_date        IN VARCHAR2,
                                        p_name        IN VARCHAR2,
                                        p_class       IN VARCHAR2,
                                        p_paramname   IN VARCHAR2) IS
BEGIN
  CASE p_paramname
    WHEN 'P_NAME' THEN
      DBMS_OUTPUT.put_line ('Did something with P_NAME.  Value was ' || p_name);
    WHEN 'P_DATE' THEN
      DBMS_OUTPUT.put_line ('Did something with P_DATE.  Value was ' || p_date);
    WHEN 'P_CLASS' THEN
      DBMS_OUTPUT.put_line ('Did something with P_CLASS.  Value was ' || p_class);
    ELSE
      raise_application_error (-20001, 'Invalid parameter name: ' || p_paramname);
  END CASE;
END matt_test1;

begin
  matt_test1(SYSDATE,'Fred','English 101', 'P_DATE');
  matt_test1(SYSDATE,'Fred','English 101', 'P_NAME');
  matt_test1(SYSDATE,'Fred','English 101', 'P_CLASS');
end;

Output:
Did something with P_DATE.  Value was 11-Aug-2015
Did something with P_NAME.  Value was Fred
Did something with P_CLASS.  Value was English 101


Can't access specific data in jsonfile - Flutter

Question: I have this json file :
{
projects: [
    {
        projectId: 3
        projectName: "Complexe hotelier croisette",
        workflow: "en cours",
        realCalendars: [
            {
                id: 29,
                start: 1630590443000
                end: 1648475243000
                type: 0
                remark: NULL
                status: 0
                calendarId: NULL
            }
        ],
        scheduledCalendars: [
            {
                id: 30,
                start: 1630590443000
                end: 1646059643000
                type: 0
                remark: NULL
                status: 0
                calendarId: NULL
            }
        ],
        lastPlanningModif: 1639320443000
        planned: 164,
        actual: 142,
        remaining: 25,
        resourceTaskNumber: 1,
        projectTaskNumber: 18,
        leaderId: 8,
        resourceIds: [8, 7, 6],
        dashbordField: 3,
        dashbordTendency: 1,
        weatherComments: [
            {
                message: "weather 5",
                date: 1645195643000
                source: 1
                taskId:0
                projectId: 3
                authorId: 8,
                messageId: 31,
                messageParentId: 32
            },
            {
                message: "weather 6",
                date: 1643813243000
                source: 1
                taskId: 0
                projectId: 3
                authorId: 8,
                messageId: 33,
                messageParentId: 34
            },
            {
                message: "weather 7",
                date: 1642776443000
                source: 1
                taskId: 0
                projectId: 3
                authorId: 7,
                messageId: 35,
                messageParentId: 36
            },
        ],
        projectComments: [
            {
                message: "Time 3",
                date: 1642776443000
                source: 4
                taskId: 3789
                projectId: 3
                authorId: 7,
                messageId: 37,
                messageParentId: 38
            },
            {
                message: "Time 4",
                date: 1639838843000
                source: 4
                taskId: 3876
                projectId: 3
                authorId: 8,
                messageId: 39,
                messageParentId: 40
            },
            {
                message: "Time 5",
                date: 1638888443000
                source: 2
                taskId: 3258
                projectId: 3
                authorId: 8,
                messageId: 41,
                messageParentId: 42
            },
        ],
    },
    {
        projectId: 2
        projectName: "Festival de la moutarde de Dijon",
        workflow: "objectif",
        realCalendars: [
            {
                id: 23,
                start: 1682689643000
                end: 1696686443000
                type: 0
                remark: NULL
                status: 0
                calendarId: NULL
            }
        ],
        scheduledCalendars: [
            {
                id: 24,
                start: 1682689643000
                end: 1696686443000
                type: 0
                remark: NULL
                status: 0
                calendarId: NULL
            }
        ],
        lastPlanningModif:  1646059643000
        planned: 150,
        actual: 0,
        remaining: 150,
        resourceTaskNumber: 2,
        projectTaskNumber: 10,
        leaderId: 4,
        resourceIds: [4, 6, 7, 8],
        dashbordField: 4,
        dashbordTendency: 2,
        weatherComments: [
            {
                message: "weather 4",
                date: 1674744443000
                source: 1
                taskId: 0
                projectId: 1
                authorId: 4,
                messageId: 25,
                messageParentId: 26
            }
        ],
        projectComments: [
        ],
    },
    {
        projectId: 1
        projectName: "Red Is Dead",
        workflow: "en cours",
        realCalendars: [
            {
                id: 9,
                start: 1642430843000
                end: 1669387643000
                type: 0
                remark: NULL
                status: 0
                calendarId: NULL
            }
        ],
        scheduledCalendars: [
            {
                id: 10,
                start: 1642430843000
                end: 1666705643000
                type: 0
                remark: NULL
                status: 0
                calendarId: NULL
            }
        ],
        lastPlanningModif: 1645109243000
        planned: 280,
        actual: 58,
        remaining: 222,
        resourceTaskNumber: 5,
        projectTaskNumber: 36,
        leaderId: 4,
        resourceIds: [4,5,6],
        dashbordField: 2,
        dashbordTendency: 3,
        weatherComments: [
            {
                message: "weather 1",
                date:  1645800443000
                source: 1
                taskId: 0
                projectId: 1
                authorId: 4,
                messageId: 11,
                messageParentId: 12
            },
            {
                message: "weather 2",
                date: 1643986043000
                source: 1
                taskId: 0
                projectId: 1
                authorId: 4,
                messageId: 13,
                messageParentId: 14
            },
            {
                message: "weather 3",
                date: 1643122043000
                source: 1
                taskId: 0
                projectId: 1
                authorId: 4,
                messageId: 15,
                messageParentId: 16
            },
        ],
        projectComments: [
            {
                message: "Time 1",
                date: 1642862843000
                source: 4
                taskId: 1234
                projectId: 1
                authorId: 5,
                messageId: 17,
                messageParentId: 18
            },
            {
                message: "Time 2",
                date: 1642258043000
                source: 4
                taskId: 1235
                projectId: 1
                authorId: 5,
                messageId: 19,
                messageParentId: 20
            },
            {
                message: "Task 1",
                date:  1641826043000
                source: 2
                taskId: 1234
                projectId: 1
                authorId: 5,
                messageId: 21,
                messageParentId: 22
            },
        ],
    }

],
avatars: [
    {
        resourceId: 8,
        idSource: 81,
        resourceName: "Alain Martoni",
        trigram: "AMO",
        imgBase64: ""
    },
    {
        resourceId: 4,
        idSource: 41,
        resourceName: "Odile Deray",
        trigram: "ODE",
        imgBase64: ""
    },
    {
        resourceId: 7,
        idSource: 71,
        resourceName: "Patrick Bialès",
        trigram: "PBI",
        imgBase64: " "
    },
    {
        resourceId: 5,
        idSource: 51,
        resourceName: "Serge Karamazov",
        trigram: "SKA",
        imgBase64: ""
    },
    {
        resourceId: 6,
        idSource: 61,
        resourceName: "Simon Jérémi",
        trigram: "SJE",
        imgBase64: ""
    }
]

}
Here I try to display specific data from the json (here I want to display what's in "projects")
var resp = response.body;
print("mydata : " + resp['projects'].toString());

Then I tried adding a jsonDecode :
var resp = jsonDecode(response.body);
print("mydata : " + resp['projects'].toString());

Then jsonEncode :
var resp = jsonEncode(response.body);
print("mydata : " + resp['projects'].toString());

Then both :
var resp = jsonDecode(jsonEncode(response.body));
print("mydata : " + resp['projects'].toString());

When I try display only "resp" it works, but it's the access to a specific part (like "projects") of the JSON that doesn't work. The only thing that work is with an int and it display the specific caractere of the index as if the JSON was read as a String.
var resp = jsonDecode(jsonEncode(response.body));
print("mydata : " + resp[0].toString());
//display the first caracter of the JSON

The thing is when I read the response of POST HTTP requests, using jsonEncode then jsonDecode works perfectly, I can then easily access any part of the JSON :
    var response = await http.post(
            Uri.parse(url),
            body: jsonEncode({
                "jsonrpc": "2.0",
                "id": "10",
                "method": "method",
                "params": [someParams]
            })
          );
          var resp = jsonDecode(response.body);
          print("response body : " + resp['projects'].toString());
//display the "project" part of the JSON response

But all this doesn't work when trying to access specific parts of my first JSON file.
Is there something wrong with my JSON file ?
Thanks for helping.
Update : commas are missing in the json, I corrected it but still the same probleme
Answer: I ran your JSON through a JSON formatter / validator and yes, your json was missing some commas and whatnot.
Check out this Gist I created for your decoding - run it through DartPad.Dev and check out.
I made sure the JSON was a proper string before I ran it through the jsonDecode, then I just simply access its values like this:
  var decodedJSON = jsonDecode(json);

  print(decodedJSON['projects'].length);
  print(decodedJSON['projects'][0]['projectName']);
  print(decodedJSON['avatars'].length);
  print(decodedJSON['avatars'][0]['resourceName']);

I got the values I expected:
3
Complexe hotelier croisette
5
Alain Martoni

I think your issue was just badly formatted JSON coming out of the pipe. Check out the Gist and let me know.
Comment: Yes, I was missing the apostrophes to make it a proper string, I still don't get why we need to encapsulate the json with 3 pairs of apostrophes and why 1 pair couldn't make it... (I mean I get that with 3 pairs it works but I don't really get the why)


Is there any way to go straight to the bottom of the tower?

Question: I have noticed that tapping the icon for the number of floors in the top right hand corner takes you straight to the top of the tower, but I can't find any way to go to the bottom.  Has anyone found a way to do this?
Answer: To go directly to the top of your tower, tap the very top of your screen ( above the zoom button or on the floor count icon)
You can go directly to the bottom of your tower - to my knowledge- only by the notification short cut, such as: restock on a lower floor, VIP, or someone in the elevator.
Answer: In the current version (march 2017) you can go to the bottom by tapping on the status bar (where your balance is shown).
Going to the top remained the same - tap on upper screen border.


Deploying a Rails app on an Ubuntu server using Git

Question: I'm completely new to Linux, but today I find myself setting up a server (Ubuntu 10.04 LTS lucid) from scratch to host a Rails application.
Anyway, I managed to get a Rails app up and running on the server itself, but I had to scrap that because I want to use Git. So I setup a git repository on the server, then pushed all the code from my local machine to the repository. Buuuut, of course Git doesn't actually store the files themselves in the repository -- all the code for my Rails app is now only on my local machine. How am I supposed to tell the server to host that?
Right now my solution is to have the server use git to pull the code from its own repository. That's the code I'll host for all the world to see. In order to update the code, I guess I'll have to do something like this:

Update the code on my local machine.
Do some git adds, git commits, and a git push.
On the server, do a git pull to update the code.

So my question is, am I doing this the right way?
Answer: I recommend that you use Capistrano to deploy your application to your slice. Slicehost have some excellent guides available on this.
Comment: +1 for this. Capistrano is absolutely the way to go - especially as a starting point.
Answer: Cap is solid and is common practice for Rails apps. Check it out for sure.
I also highly suggest Github to host your repo. It's really inexpensive and provides a ton of value. The simplest workflow for the situation you described would be to push the repo you have on your development machine up to github. Then, from your server, clone the github repo onto your server.
As you develop, keep pushing incremental changes up to github. When you're ready to release an update, simply git pull from your server and it will pull in all the changes you've made.


Proving that $|z-1|-|z+1|=1$ its an hyperbola, and $\Re(1-z)=|z|$ its an ellipse.

Question: Proving that $|z-1|-|z+1|=1$ its an hyperbola, and $\Re(1-z)=|z|$ its an ellipse.
If $z\in \mathbb C$
I cant see why there are a hyperobla and an ellipse respct.
Comment: I think you have a hyperbola and a parabola there.
Comment: I think you have to write out the imaginary and real part then do some squaring.
Answer: To show that $|z-1|-|z+1|=1$ is a hyperbola
Let $a=|z-1|, b=|z+1|$ where $z=x+iy$.
Hence
$a^2=(x-1)^2+y^2$ and $ b^2=(x+1)^2+y^2$.
Given equation:
$\qquad \qquad\qquad \qquad \qquad a-b=1\qquad\qquad $
Multiply by $a+b$ and swapping sides:
$\qquad a+b=a^2-b^2\qquad $
Adding:
$\qquad\qquad\qquad \qquad\qquad \qquad \qquad 2a=1+a^2-b^2=1-4x$
  Squaring:
$$4a^2=(1-4x)^2\\
4((x-1)^2+y^2)=1-8x+16x^2\\
12x^2-y^2=4\\
\frac{x^2}{\left(\frac 1{\sqrt{3}}\right)^2}-\frac {y^2}{2^2}=1$$
which is a hyperbola.
NB - the method above avoids messy square roots
To show that $\Re (1-z)=|z|$ is a parabola
Squaring both sides: $(1-x)^2=x^2+y^2\Rightarrow y^2=-2ax+1$ which is a parabola.
Answer: I'll give you an idea :
$Re(1-z) = Re (1 - x - iy) = 1 - x $
On the other hand,  $ |z| = \sqrt{x^2 + y^2} $
So, we can write :
$ (1-x)^2 = x^2 + y^2 $
Then you can rearrange the last part..
Answer: The set of points whose difference of distances to  fixed points, the foci ($(-1,0),(1,0)$ respectively here )is constant, is a hyperbola. Here $|z-1|$ is the distance to -1 and $|z+1|$ is the distance to $-1$.


What is the simplest solution to this elementary geometry problem?

Question: The Problem
Given a triangle $ABC$, points $M$ and $N$ are chosen in such way that the midpoint of segment $BM$ is coincident with the midpoint of side $AC$, and the midpoint of segment $CN$ is coincident with the midpoint of side $AB$. Prove that points $M$, $N$, $A$ are collinear.
The drawing is provided.

The Solution
Below I provide my own solution of the stated problem.
Let $P$ be the midpoint of $AB$, and $Q$ the midpoint of $AC$. We are going to prove that $A\in MN$.

$\overline{CP}=\overline{PN}$, $\overline{AP}=\overline{PB}$ (by statement of the problem), $\angle CPB = \angle APN$ (these angles are vertical by definition) $\Rightarrow _\Delta BPC\cong _\Delta APN$ (SAS congruence).

$_\Delta BPC\cong _\Delta APN\Rightarrow \angle PCB=\angle PNA\Rightarrow BC\parallel AN$ (from the congruence of alternate angles).

$\overline{BQ}=\overline{QM}$, $\overline{AQ}=\overline{QC}$ (by statement of the problem), $\angle BQC = \angle AQM$ (these angles are vertical by definition) $\Rightarrow _\Delta BQC\cong _\Delta MQA$ (SAS congruence).

$_\Delta BQC\cong _\Delta MQA\Rightarrow \angle CBQ=\angle AMQ\Rightarrow BC\parallel AM$ (from the congruence of alternate angles).

$BC\parallel AN$ and $BC\parallel AM$, so $BC$ is parallel to two line segments with a common endpoint. Clearly, as $ABC$ is a triangle, point $A$ is not on line $BC$. But by Playfair's axiom, at most one line parallel to the given line can be drawn through the point not on this line. Thus, two segments with a common endpoint can be parallel to the same line if and only if they are on the same line. So we conclude that $\overline{AM}$ and $\overline{AN}$ are collinear, and thus, $A$, $M$, $N$ are collinear, QED.

The Question
I'm looking for the simplest solution of this problem you can find. By simplest I mean the most elementary, using only basic facts of geometry, preferrably more elementary than the one I came up with above.
Answer: $ACBN$ and $ABCM$ are parallelograms, because their diagonals are bisected by the point of intersection. So, $AN \parallel BC$ and $AM \parallel BC$.
Comment: A clever observation indeed, thanks for it! So instead of proving triangle congruency, you just straight out to proving parallelograms, which is nice. Let's see what others would come up with, too!
Answer: Let $X$ be the intersection of $BM$ and $AC$, and similarly for $CN$ and $AB$ with $Y$.
Rotate $\triangle BCX$ by $180^{\circ}$ about $X$ (and the same with $\triangle BCY$ about $Y$) to get the result.
Answer: As JMP does, we'll call $ \ X \ $ the midpoint of $ \ \overline{AC} \ $ and $ \ Y \ $ the midpoint of $ \ \overline{AB} \ \ . \ $  Then $ \ \overline{BX} \ $ and $ \ \overline{CY} \ $ are medians of $ \ \Delta ABC \ \ . \ $  These intersect at the centroid $ \ P \ $ of the triangle and thus  $ \ \overline{BP} \ $ and $ \ \overline{CP} \ $ have $ \ \frac23 \ $ of the length of  $ \ \overline{BX} \ $ and $ \ \overline{CY} \ \ , \ $  respectively.  Hence,   $ \ \overline{MP} \ $ and $ \ \overline{NP} \ \   $  have $ \ \frac43 \ $ the length of   $ \ \overline{BX} \ $ and $ \ \overline{CY} \ \ , \ $  respectively, making triangles $ \ \Delta MPN \ $ and $ \ \Delta BPC \ $ similar (the two triangles having vertical angles at $ \ P \ ) \ . $ So $ \ \overline{MN} \ $ and $ \ \overline{BC} \ $ are parallel, as we have pairs of alternate interior angles among the two triangles.
If we call $ \ Q \ $ the midpoint of $ \ \overline{BC} \ \ , \ $ then $ \ \overline{AQ} \ $ is also a median of  $ \ \Delta ABC \ \ . $  The similarity of $ \ \Delta MPN \ $ and $ \ \Delta BPC \ $ places $ \ A \ $ on the line $ \ \overline{MN} \ \ . $
[The proposition is very simple to prove analytically:  placing $ \ A \ $ at the origin (and $ \ B \ $ and $ \ C \ $ at arbitrary coordinates) and finding the coordinates of the midpoints $ \ X \ $ and $ \ Y \ \ , \ $ and thence those of $ \ M \ $ and $ \ N \ \ , \ $ it is straightforward to show that the slope of side $ \ \overline{BC} \ $ is the same as the line containing $ \ \overline{MN} \ \ . \ $ It is then found that the equation of said line passes through the origin.]


How to serialize custom arraylist object and save it to sqlite database?

Question: I want to save custom arraylist object in sqlite database when i search about it on internet i got to know that i need to make my class serialize. But problem is that my that class is Parcelable and i,m sending values from one activity to another with the help of Parcelable.
Medicine.class
public class Medicine implements Parcelable {

// Private Variables

int _id;
String _product_Code;
String _product_name;
String _type;
int _price;
int _quantity;

//empty constructor
public Medicine(){

}

//constructor
public Medicine(int id, String product_code,String product_name, String type, int price, int quantity){
    this._id = id;
    this._product_Code = product_code;
    this._product_name = product_name;
    this._type = type;
    this._price = price;
    this._quantity = quantity;
}

public Medicine(String product_code,String product_name, String type, int price, int quantity){
    this._product_Code = product_code;
    this._product_name = product_name;
    this._type = type;
    this._price = price;
    this._quantity = quantity;
}

public String get_product_Code() {
    return _product_Code;
}

public void set_product_Code(String _product_Code) {
    this._product_Code = _product_Code;
}

public Medicine(Parcel p){
    set_id(p.readInt());
    set_product_name(p.readString());
    set_type(p.readString());
    set_price(p.readInt());
    set_quantity(p.readInt());
}

public int get_id() {
    return _id;
}

public void set_id(int _id) {
    this._id = _id;
}

public String get_product_name() {
    return _product_name;
}

public void set_product_name(String _product_name) {
    this._product_name = _product_name;
}

public String get_type() {
    return _type;
}

public void set_type(String _type) {
    this._type = _type;
}

public int get_price() {
    return _price;
}

public void set_price(int _price) {
    this._price = _price;
}

public int get_quantity() {
    return _quantity;
}

public void set_quantity(int _quantity) {
    this._quantity = _quantity;
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub

    dest.writeInt(get_id());
    dest.writeString(get_product_name());
    dest.writeString(get_type());
    dest.writeInt(get_price());
    dest.writeInt(get_quantity());
}

public static final Parcelable.Creator<Medicine> CREATOR  = new Creator<Medicine>() {

    public Medicine createFromParcel(Parcel source) {

        return new Medicine(source);
    }

    public Medicine[] newArray(int size) {

        return new Medicine[size];
    }

};

}
In this class ShowMedicineList i,m saving the values in arraylist named as "nextValuesOf" and passing to next activity SelectedMedicineList
    Button btnAddMedicine = (Button) findViewById(R.id.buttonAddSelectedMed);
    btnAddMedicine.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(ShowMedicineList.this, SelectedMedicineList.class);
            //intent.putExtra("ccode", o._product_name);
            //intent.putExtra("cname", o._quantity);
            //intent.putExtra("caddress", amount);
            intent.putParcelableArrayListExtra("myArrayL", nextValuesOf);
            startActivity(intent);

        }
    });

Here is the onCreate Method of SelectedMedicineList class where i,m receiving the intent. Now i want to this selectedProducts arraylist in my database. Please advice me the solution or code for it
public ArrayList<Medicine> selectedProducts = new ArrayList<Medicine>();

DatabaseHandler db = new DatabaseHandler(this);

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

     selectedProducts = getIntent().getParcelableArrayListExtra("myArrayL");
     LinkedHashSet<Medicine> hs = new LinkedHashSet<Medicine>();
     hs.addAll(selectedProducts);
     selectedProducts.clear();
     selectedProducts.addAll(hs);
}

Answer: You can use Gson library to save and retrieve the data in any of your data structure. The Idea is that the library converts(serialize and deserialize) your object to/from JSON  format
So create a database column with the field type as TEXT and convert your arraylist to JSON object as
Gson gson = new Gson();
String arrayList = gson.toJson(yourArraylist);

and save this string into database.
and while retrieving take a string from database and convert into your original list as
Type listType = new TypeToken<ArrayList<YourClass>>() {
                    }.getType();
 List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);

Hope this one helps
Comment: I tried your this method but i,m getting error its not saving it in string format


How to determine if the application is an MFC program?

Question: I have a compiled GUI application. I need to learn whether it is programmed using MFC libraries. Depends.exe does not return any dependency to MFC42*.dll. Is there any tool to get additional information about executables? (If possible not just the libraries, but the compiler being used, etc..)
Comment: You might check to see if any of the Standard MFC Resources are in the executable.
Answer: If the applicartion is written using MFC it will generally be made up of windows that have class names that are prefixed with the Afx: string.
And if you have access to the Spy++ utility it is very easy to query the class names details of any executable.
Answer: If the application you are concerned with was dynamically linked to MFC it will have a dependancy on MFCXX.dll where XX is the version number. For instance, our application is dependant on MFC80.dll.
However, if the application was statically linked, all the source for MFC will be compiled straight into the app.
Comment: I already said in the question, that it does not return any dependency. And I think it is possible that MFC applications can be statically build.
Comment: Not if MFC was statically linked to the application.
Answer: Also beware that the MFC application could have been statically linked to the MFC libraries rather than using a Shared Library - A statically linked MFC application won't show a dependency on MFCXXX.dll as an immediate dependency in Depends.
Answer: dumpbin is the tool you want, if it's statically linked. MFC symbols tend to be named '...Afx...' or '...MFC...', so if you see those, it's probably using MFC. This utility can also tell you the linker version, OS it's compiled for, etc.
Answer: You could try running the dumpbin utility on the file (part of the SDK or a VS install).
If you run "dumpbin /exports" you could look for any telltale MFC-isms.  I'm not sure if there would be any though, so the test would only confirm MFC is statically linked, not refute it.
Answer: If you can run the application, get it running and then use the Sysinternals tool ProcessExplorer to view the loaded DLL's.
Or do you need a programatic way of determining if the app is using MFC?
Also, I'm a bit suprised that Depends is not showing what you expect.  Compare the Depends output with ProcessExplorer and see what you can learn.
Answer: Babak Farrokhi once wrote a very handy little program named "Language 2000" that scans exes looking for libraries and frameworks binary signatures. It used to detect statically linked MFC programs two fingers up the nose.
The program was already old when I used it a few years ago though. You'd have to check the web is a newer version is available or if the signature still work. Who knows!
Answer: SysInternals (recently purchased by Microsoft) published depends.  Regardless of whether it's dynamically linking to DLLs or statically linked, you'll see the import/export symbols referenced (might be mangled for C++ entry point signatures).
This tool is also extremely beneficial for detecting circular references (using dependency tree).  And in those rare instances when you're absolutely certain you exported the entry point but the linker still fails, you can examine the DLL for the "missing" entry point.
Also aids in discovering hidden secrets of a DLL.


Java dropping half of UDP packets

Question: I have a simple client/server setup. The server is in C and the client that is querying the server is Java.
My problem is that, when I send bandwidth-intensive data over the connection, such as Video frames, it drops up to half the packets. I make sure that I properly fragment the udp packets on the server side (udp has a max payload length of 2^16). I verified that the server is sending the packets (printf the result of sendto()). But java doesn't seem to be getting half the data.
Furthermore, when I switch to TCP, all the video frames get through but the latency starts to build up, adding several seconds delay after a few seconds of runtime.
Is there anything obvious that I'm missing? I just can't seem to figure this out.
Comment: Are you sure it's "Java" and not your network?  Also, UDP makes no guarantees about packet delivery, order, or duplicates - unlike TCP.
Comment: The fact that the use of TCP results in latency tells me that you're trying to pour into your network more data than it can carry. Since you have logs from the server side sending packets, you should be able to get a general idea how much data you're sending per second. Is it compatible with the capacity of your network?
Answer: Get a network tool like Wireshark so you can see what is happening on the wire.
UDP makes no retransmission attempts, so if a packet is dropped somewhere, it is up to the program to deal with the loss.  TCP will work hard to deliver all packets to the program in order, discarding dups and requesting lost packets on its own.  If you are seeing high latency, I'd bet you'll see a lot of packet loss with TCP as well, which will show up as retransmissions from the server.  If you don't see TCP retransmissions, perhaps the client isn't handling the data fast enough to keep up.
Comment: I opened up wireshark and dumped the packets using TCP. I didn't see any dropped packets. The RTT to ACK (round trip time to ACK) was ~40ms. My Java client uses a dedicated thread to parse the bytes.
Comment: Thanks for your help, it has been solved. It was a problem in the java receiver thread (the thread was blocked for a short time not listening for packets). Your TCP dropped packet monitor suggestion was good.
Answer: Any UDP based application protocol will inevitably be susceptible to packet loss, reordering and (in some circumstances) duplicates.  The "U" in UDP could stands for "Unreliable" as in Unreliable Datagram Protocol.  (OK, it really stands for "User" ... but it is certainly a good way to remember UDP's characteristics.)
UDP packet losses typically occur because your traffic is exceeding the buffering capacity of one or more of the "hops" between the server and client.  When this happens, packets are dropped ... and since you are using UDP, there is no transport protocol-level notification that this is occurring.
If you use UDP in an application, the application needs to take account of UDP's unreliable nature, implementing its own mechanisms for dealing with dropped and out-of-order packets and for doing its own flow control.  (An application that blasts out UDP packets with no thought to the effect that this may have on an already overloaded network is a bad network citizen.)
(In the TCP case, packets are probably being dropped as well, but TCP is detecting and resending the dropped packets, and the TCP flow control mechanism is kicking in to slow down the rate of data transmission.  The net result is "latency".)
EDIT - based on the OP's comment, the cause of his problem was that the client was not "listening" for a period, causing the packets to (presumably) be dropped by the client's OS.  The way to address this is to:

use a dedicated Java thread that just reads the packets and queues them for processing, and
increase the size of the kernel packet queue for the socket.

But even when you take these measures you can still get packets dropped.  For example, if the machine is overloaded, the application may not get execution time-slices frequently enough to read and queue all packets before the kernel has to drop them.
EDIT 2 - There is some debate about whether UDP is susceptible to duplicates.  It is certainly true that UDP has no innate duplicate detection or prevention.  But it is also true that the IP packet routing fabric that is the internet is unlikely to spontaneously duplicate packets.  So duplicates, if they do occur, are likely to occur because the sender has decided to resend a UDP packet.  Thus, to my mind while UDP is susceptible to problems with duplicates, it does not cause them per se ... unless there is a bug in the OS protocol stack or in the IP fabric.
Comment: If two packets end up taking different routes to the client, could you not then end up with reordered packets (from the client's point of view)?
Comment: @Eric  Yes with UDP, no with TCP.
Comment: Why not duplicates? AFAIK, duplicates are indeed possible.
Comment: A duplicate should only occur if the sender sends two packets with identical contents (e.g. resends).  And in that case, the packets are conceptually different, even if there is no way for the receiver to detect this.  AFAIK, a router will not resend a given UDP packet.
Comment: UDP != "Unreliable" Datagram Protocol (even though it is unreliable) - it's "User" Datagram Protocol - http://www.faqs.org/rfcs/rfc768.html
Comment: @Fred: That's what I thought :-)
Comment: 'the IP packet routing fabric that is the internet is unlikely to spontaneously duplicate packets'. I don't know about that. Surely the mere presence of multiple paths makes it possible that the same packet can arrive twice via different paths? Quite a lot of the TCP specification is there to protect against duplicate packets.
Comment: TCP needs to do that because it *retransmits* packets.
Comment: @EJP - "Surely the mere presence of multiple paths makes it possible that the same packet can arrive twice via different paths?"  I don't see the logic in that.  The mere existence of multiple paths does not imply that a single packet will be sent by more than one of them.
Comment: (a) It doesn't imply that it *will* but it does imply that it *can.* (b) RFC 793 #1.5: 'The TCP must recover from data that is damaged, lost, duplicated, or delivered out of order by the internet communication system.' #3.7: 'Duplicate segments may arrive due to network or TCP retransmission.'
Answer: Although UDP supports packets up to 65535 bytes in length (including the UDP header, which is 8 bytes - but see note 1), the underlying transports between you and the destination do not support IP packets that long.  For example, Ethernet frames have a maximum size of 1500 bytes - taking into account overhead for the IP and UDP headers, that means that any UDP packet with a data payload length of more than about 1450 is likely to be fragmented into multiple IP datagrams.
A maximum size UDP packet is going to be fragmented into at least 45 separate IP datagrams - and if any one of those fragments is lost, the entire UDP packet is lost.  If your underlying packet loss rate is 1%, your application will see a loss rate of about 36%!
If you want to see less packets lost, don't send huge packets - limit your data in each packet to about 1400 bytes (or even do your own "Path MTU discovery" to figure out the maximum size you can safely send without fragmentation).

Of course, UDP is also subject to the limitations of IP, and IP datagrams have a maximum size of 65535, including the IP header.  The IP header ranges in size from 20 to 60 bytes, so the maximum amount of application data transportable within a UDP packet might be as low as 65467.
Comment: Several inaccuracies there, see my answer.
Comment: Good practical advice - even if there is some debate over the size of the UDP header (eight bytes, from memory). For most streaming applications, keeping UDP datagram size small enough to fit in an ethernet frame has a number of advantages: minimises data loss when a frame is lost; reduces latency as don't need to wait for the whole datagram; and - for some applications - processing load can be reduced by turning off UDP checksumming for the stream  and relying on ethernet error detection to discard faulty frames/datagrams. MPEG is often sent as 7 x 188 byte TS frames per UDP datagram.
Answer: The problem might be to do with your transmit buffer getting filled up in your UDPSocket. Only send the amount of bytes in one go indicated by UDPSocket.getSendBufferSize(). Use setSendBufferSize(int size) to increase this value.

If #send() is used to send a
  DatagramPacket that is larger than the
  setting of SO_SNDBUF then it is
  implementation specific if the packet
  is sent or discarded.
Answer: IP supports packets up to 65535 bytes including a 20 byte IP packet header. UDP supports datagrams up to 65507 bytes, plus the 20 byte IP header and the 8 byte UDP header. However the network MTU is the practical limit, and don't forget that that includes not just these 28 bytes but also the Ethernet frame header. The real practical limit for unfragmented UDP is the minimum MTU of 576 bytes less all the overheads.
Comment: Ethernet has frames, not packets. The Ethernet MTU is 1500 bytes of **payload**, which defines the maximum size of an IP fragment; it doesn't include the frame header and trailing. 576 is the minimum MTU a node must support in order to transmit IP fragments, it is not the real practical limit for unfragmented UDP. This limit have to be determined via a path MTU discovery. Also, it is possible to send datagrams bigger than the MTU without making it unpractical, until either datagrams or packet loss get too big.

Java dropping half of UDP packets


How to fix ' missing google-api-python-client'? Using Python, Jupyter Notebook and SpeechRecognition

Question: I'm trying to perform speech recognition on some audio files I have using python 3.x, jupyter notebook and SpeechRecognition library but I get:
'RequestError: missing google-api-python-client module: ensure that google-api-python-client is set up correctly.'

when using recognize_google_cloud even though I already installed it and see 'google-api-python-client when running
conda list

Things run smoothly when using the default google speech API key.
Code being used is as follows:
import speech_recognition as sr

r = sr.Recognizer()

with open('file_with_keys.json') as f:
GOOGLE_CLOUD_SPEECH_CREDENTIALS = f.read()

test_audio = sr.AudioFile('audio_file.wav')
with test_audio as source:
    audio = r.record(source)

r.recognize_google_cloud(audio, language = 'es-MX',
credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS)

Expected result consists of transcription of my current file.
Thanks a lot in advance.
Comment: https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/
Answer: Can you publicly share the notebook?  Did you try this in a console rather than notebook, and what are the results if you do?
Also, when you say

"Things run smoothly when using the default google speech API key."

Can you be more specific as to what that means or how it relates to the problem?  Your not getting an API key error.
For me, I could only get my python code working if I was running in a virtual environment.  Is that happening for your notebook?
See: https://cloud.google.com/python/setup
And: https://anbasile.github.io/programming/2017/06/25/jupyter-venv/


Batch loop doesn't loop

Question: Totally new to scripting, but this should work.
Instead I get a single txt file when it should produce up to 10.
thanks in advance!
<code>@echo off
setlocal enabledelayedexpansion
goto :main
:main

setlocal
set /a current=0
set /a total=10

:loop
if !current! lss !total! (
echo stuffstuffstuffstuff.!current! > supercrap.txt
set /a current=!current!1+

goto :loop
)
endlocal
goto :eof
</code>
Comment: what are you expecting by `set /a current=!current!1+`?
Comment: Besides the typo in your `SET /A` command, why are you expecting 10 different files?  You do not have any code that would create 10 different files.  The code only ever writes to one file and overwrites it every time. Without knowing all of the technical specifications of what you are doing it seems like you would be better off using a `FOR /L` command instead.
Comment: the current=!current!1+ should enumerate the total till it reached 10.. I thought.. I'm guessing +1 would've done it.
Comment: the set /a.. does it not have to be an integer in order to enumerate/ count up?
Answer: Here's a couple of quick examples to assist you:
<code>@Echo Off
SetLocal EnableExtensions
Set /A current=0,total=10
:Loop
If %current% Lss %total% (
    Echo stuffstuffstuffstuff.%current%
    Set /A current+=1
    GoTo loop
)>>"supercrap.txt"
Pause
EndLocal
GoTo :EOF
</code>
<code>@Echo Off
SetLocal EnableExtensions
(For /L %%G In (0,1,9) Do Echo stuffstuffstuffstuff.%%G)>"supercrap.txt"
Pause
EndLocal
GoTo :EOF
</code>
Please note: delayed expansion is not necessary, so has been omitted.
Comment: Thanks tons! I'll have a look at this.. I kind of got fed up with batch and moved to powershell.. hoping it would be more streamlined and user friendly. I wanted to get a strong grasp of batch for  a strong learning foundation.. so I will come back to it.

Batch loop doesn't loop


JS using a closure replicate an private set object only available through get/accessor method

Question: I'm trying to create a function that uses a closure to replicate an object.
accessing the getter property within a private function.
 function Container(param) {
      var person = {
      firstName: 'Jimmy',
      lastName: 'Smith',
      get fullName() {
      return this.firstName + ' ' + this.lastName;
      },
    set fullName (name) {
       var words = name.toString().split(' ');
       this.firstName = words[0] || '';
       this.lastName = words[1] || '';
   }
  }
 }

  // Attempting to clone private getter don't know how to access it.

     function objectClone(person) {

       var orginal = person //Trying to access the private method

       var clone = function cloneObj { Object.assign({}, original); }

       clone.prototype.spillSecret = function() { alert(this.getfullName()); }

     ;}

Comment: Neither of your functions makes any sense. For example why are you creating a person object that is neither referenced nor returned from `Container` function? `objectClone` doesn't return anything. `cloneObj` neither returns nor affects `original` object (other than calling getter which might have some side-effects but usually doesn't)
Comment: I agree the original question's concept was hard for me to grasp, I thought I had to clone a regular object with Object.assign, that's the reason why I created the person object to try to set the getter properties within that object. All in all in my attempt I have no idea how to structure so the getter properties are private and clone method only copies those private properties.
Comment: `get fullName` != `getfullName`
Answer: It seems like you're trying to create a new instance of a Container. Firstly, we should fix up that code:
function Container(param) {
  this.firstName = 'Jimmy';
  this.lastName = 'Smith';
  Object.defineProperty(this, 'fullName', {
    get: function() {
      return this.firstName + ' ' + this.lastName;
    },
    set: function(name) {
      var words = name.toString().split(' ');
      this.firstName = words[0] || '';
      this.lastName = words[1] || '';
    }
  });
}

Now, to create a new Container object, we use new:
var person = new Container();

person will have the get and set methods for fullName on it.
Comment: Thank you so from above, do I tie in the same cloning function I attempted originally basically how would I copy the full name property.
Comment: You use the `person` object you just created: `var person = new Container(); person.fullName = 'John Doe'; console.log('person.firstName');` => `John`
Comment: Thank you! I've updated your answer and accept it, just making sure I have it correct.


Elasticsearch - cleaning but no analyzer

Question: I'm working on a problem, which requires us to do exact word matching in Elasticsearch.
For example, if you want to search on the term 'Brighton Pier', it should match when searching 'brighton pier', but not on 'brighton' nor 'pier'.
I've worked out how to do this simply, by turning the fields I want to search to not_analyzed.
However when not analysing it means stopwords, casing etc. will impact the results.
So is there a way to not analyse but still clean? Of course you can do cleaning prior to adding to the index, and with the search term itself, but this is tedious!
Answer: I think you can get what you want with the keyword tokenizer and the lowercase filter.
I'll give you a simple example. I set up an index like this, with a custom analyzer:
PUT /test_index
{
   "settings": {
      "number_of_shards": 1,
      "analysis": {
          "analyzer": {
              "my_analyzer": {
                  "type": "custom",
                  "tokenizer": "keyword",
                  "filter": ["lowercase"]
              }
          }
      }
   },
   "mappings": {
       "doc": {
           "properties": {
               "text_field": {
                   "type": "string",
                   "analyzer": "my_analyzer"
               }
           }
       }
   }
}

Then I added a couple of documents:
POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"text_field":"Brighton Pier"}
{"index":{"_id":2}}
{"text_field":"West Pier"}

It's helpful to take a look at the terms that are generated by the analyzer:
POST /test_index/_search?search_type=count
{
   "aggs": {
      "text_field_terms": {
         "terms": {
            "field": "text_field"
         }
      }
   }
}
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "text_field_terms": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "brighton pier",
               "doc_count": 1
            },
            {
               "key": "west pier",
               "doc_count": 1
            }
         ]
      }
   }
}

Since the custom analyzer is used both for indexing and searching (since I didn't specify them separately), as long as I use a match query, either of the following two queries will work:
POST /test_index/_search
{
   "query": {
      "match": {
         "text_field": "Brighton Pier"
      }
   }
}
...
{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "1",
            "_score": 1,
            "_source": {
               "text_field": "Brighton Pier"
            }
         }
      ]
   }
}

POST /test_index/_search
{
   "query": {
      "term": {
         "text_field": "brighton pier"
      }
   }
}
...
{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "1",
            "_score": 1,
            "_source": {
               "text_field": "Brighton Pier"
            }
         }
      ]
   }
}

However, if I use a term query (or filter), only the lowercase version will return a result.
Here is some code I used to play around with it:
http://sense.qbox.io/gist/d13a463af383c6fc5ad00d86bc27947c0016cf8f


Can I take text which is in a csv and make it the name of the csv file

Question: I really hope I can explain my issue. Your help will be much appreciated.
I have over 1000 csv files which looks exactly the same.
Example
Malian Aero Company,,,,,Aircraft,TZ-DDG,(Seed 1),,,Block-on (Z),18:19,      Landing (Z),,18:14,Date,06/06/16
2016  MALI  WEATHER  MODIFICATION  PROGRAM,,,,,,,,,,Block-off (Z),16:35,        Takeoff (Z),,16:41,Page,1
,Pilot:,Daniel Chacon,,Co-Pilot:,Malik,,Observer: ,,,Total Time,01:44,    Flight  Time    ,,01:33,Type,Seed
,,,,,,,,,,,,,,,,
Time,Cell,Event,LAT,LON,Alt.,Ejectable (Glacio),,BIP (Hygro),,Remarks,,,,,,
(UTC),No.,No.,(VOR),(DME),(Kft),0,Recycle,Burn,Recycle,,,,,,,
17:03,1,,12.55,-9.03,"8,000",,,1,,,,,,,,
17:06,,,12.67,-9.13,"8,000",,,1,,Updraft 500/900 ft/m,,,,,,
17:11,,,12.56,-9.11,"8,000",,,1,,,,,,,,
17:13,,,12.74,-9.07,"8,000",,,1,,,,,,,,
17:35,2,,13.31,-9.07,"9,000",,,1,,,,,,,,
17:39,,,13.53,-9.05,"9,000",,,1,,,,,,,,

The problem is I want the name of the csv file to be the date that the flight took place which is in line 2. In this example, the date is 06/06/16. Therefore, I want the name of the csv file to be 20160606. Note the change in order which probably makes it a bit more confusing.
How can I do this automatically?
Comment: OK, I *think* my last edit is correct and represents your actual data. Please let me know if it isn't. Also don't ask multiple questions in a single post and make sure to explain how we can know how to find the date.
Comment: Hi @suraj, the edit was incorrect, this is no code, the landing date ended on the wrong line :)
Comment: Please use the [formatting tools](https://askubuntu.com/help/formatting) and [edit] your question making sure the example data is correct. Ideally, format the example data as code (`{}`) so it uses a fixed-width font and we can understand better. Is that supposed to be one long line or many? What is the format of the file? Will the data always be a specific field? Which field? Are fields defined by commas?
Comment: @JacobVlijm oops sorry I approved suraj's edit - and now I think I've screwed up your rollback as well. I will go drink some coffee now.
Comment: @JacobVlijm I see. apologies.. Block quotes for  csv data then
Comment: @suraj no problem, I could have done the same, until I read the question :)
Comment: @terdon You can find the date by parsing the last comma delimited field of the first line of the cvs file.
Comment: @L.D.James only if all files have the date as the last field of the first line. That's what I had wanted the OP to clarify. Is it always the last field? Or is it the 17th field? Or something else?
Comment: I was referring to the part of his message, the second line which specified the format of all the files are exact, if which he showed one of the files.  When answering questions, I often miss details like that in a question.  When reading your command, I happened to notice that it appeared to have already been addressed in the question.  Of course, I understand what appears very apparent to me, might not necessarily appear the same way to the next person.
Answer: This script has two arguments.  One for the directory for your csv files.  The other for the new files corrected.
In case you have more than one flight on the same day, I added the time as part of the filename to ensure there is a unique name for each outfile.
The script:
#!/bin/bash

indir=$HOME/indir
outdir=$HOME/outdir

[[ -d $outdir ]] || (echo "Outdir doesn't exist... Exiting..." ; exit)

process() {
    file=$1
    datetime=$(head -1 $file|awk -F, '{print $NF"/"$(NF-2)}' | sed s#/#:#g)

    IFS=':' read -r -a arr <<< "$datetime"
    newname=$(printf "20${arr[2]}${arr[0]}${arr[1]}-${arr[3]}${arr[4]}.csv\n")
    echo "Name Change: $file -> $newname"
    sed -e '1,7d' < $file > $outdir/$newname
}

for i in "$indir"/*.csv; do
    process "$i"
done

Script Summary
Variables and commands of the script:

indir: The script using the variables indir for the directory of your csv files.
oudir: Create this directory for the new files to be copied.
First line: Verifies the out directory exist before continuing the script.
arr: An array variable for splitting the date and creating the new filename.
sed: A commandline text editor used for deleting the unwanted lines.
Comment: I personally can read your script but OP probably not. Since they did not mention any tried commands, for example, I guess they could not read your code with pipelines, a command substitution, `sed`, `awk` and so on. And last but not least, the explanation should be a part of the answer, not a comment.
Comment: An explanation of the script would be nice.
Comment: @Melebius I tried to use self-explanatory variables.  Originally the array variable was named **array**, I shortened to `arr` to avoid horizontal scroll for viewing the whole script.  The first line verifies the output directory before continuing.  The Second section creates the new name out of the date.  The **sed** command deletes the first 7 lines (lines - through 7).
Answer: It's probably going to make Baby Jesus (or at least, Larry Wall) cry, but:
prename -n '
  use Text::CSV;
  use Time::Piece;
  open my $fh, "<", $_ or die "$_ : $!";
  eval {
    my $r = Text::CSV->new()->getline($fh);
    s{.*(?=\.csv)}{Time::Piece->strptime($r->[-1], "%d/%m/%y")->strftime("%Y%m%d")}e  if ($r);
    1;
  }
  or do {
    print "$_ skipped (no valid date field found)\n"
  }
' *.csv
file1.csv renamed as 20160606.csv
file2.csv renamed as 20160623.csv
file3.csv skipped (no valid date field found)
file.csv : Permission denied at (eval 8) line 4.

NOTE:

it assumes that the date is in the last column of the first line of each file
it assumes the original date format is "%d/%m/%y" but the example you've given could be read as "%m/%d/%y" - you will need to check and adjust if necessary

It should skip files from which it is unable to parse a valid date in the expected location: the error handling for the date parsing is taken from Exception handling in Perl: How to deal with fatal errors in external modules.
Remove the -n only if/when you are convinced it is doing the right thing.
Answer: You could use cut to select the exact column you need, then you could use date (for instance, in combination with sed) to set the filename.
Put this in a loop to go through all your files and you're done.
To help you on the way:
cut --delim="," -f17 yourfile.csv | head -n1

This will select the date, now it's your turn to transform it.
Comment: In that case, please don't post "answers" that don't even attempt to actually provide an answer and only give a first approximation for only one of the many steps needed. And how do you know that the date is always the 17th field of the first line? How will the OP take this to rename their file? Come on. Either answer the question or don't.
Comment: Put what in a loop? You aren't actually providing any command here.
Comment: @terdon See edit, but also note I am here to provide an answer, not to code the whole thing up. I don't do other people's homework :)
Comment: Disagreed, so I'll take that downvote with pride. The OP might not know  of the command line tools that are available and am pointing him/her towards them: cut, date, and a for loop. Work done.
Comment: Also, @terdon if the date is not always in the same column, then that is a completely different question. This *is* an answer.
Comment: Not column, *line*. The OP states that "the date [. . .] which is in line 2". Which is not very clear and quite confusing, but there it is.
Comment: @terdon, he referred to line 2 in his original post which you edited. If the assumption is wrong that the data is structured, you should close the question.
Comment: True. I'm hoping the OP will confirm. My was based on the source of what the OP [had posted](https://askubuntu.com/revisions/b7f67c2f-bd6a-4be1-896b-3f8513263b05/view-source) (where the date was on the first line) and I am assuming (possible incorrectly) that the OP only mentioned the second line because of how the data appeared after posting.


numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

Question: While installing SciPy on PyCharm IDE, I got stuck with the error saying

numpy.distutils.system_info.NotFoundError: no lapack/blas resources found

I have installed correct version of pip. I don't know where went wrong.
Comment: Possible duplicate of [Windows Scipy Install: No Lapack/Blas Resources Found](http://stackoverflow.com/questions/28190534/windows-scipy-install-no-lapack-blas-resources-found)
Answer: Blas and lapack are linear algebra packages which will need to be installed before scipy will work (check the dependencies). For windows 8.1 you may find help on http://icl.cs.utk.edu/lapack-for-windows/lapack/.
Also check out this answer which may help Windows Scipy Install: No Lapack/Blas Resources Found


Evaluate the integral $\int_0^1 \frac{\ln(1 - x)}{x} {\mathrm dx}$ by contour integration

Question: $$
\int\limits_{0} ^{1}
\frac{\ln\left(1−{x}\right)}{{x}}\:{\mathrm dx}
$$
I am trying to evaluate the above definite integral by contour integration. I have tried computing the above integral using a square box contour of unit sides viz. $([0,1];[1,(1+i)];[(1+i),i];[i,0])$ with small quater circle intendations at $z=0$ and $z=1$, in order to avoid the pole and branch point on the real axis. But this contour is not giving fruitful results to evaluate the integral. It would be my pleasure if you all can suggest ways to evaluate the given integral by contour integration.
Comment: A much easier way to evaluate this integral is by expanding it as a power series. You get $-\zeta(2)$, which is $-\pi^2/6$.
Comment: @Accelerator Thanks a lot in advance. It would be extremely helpful for me .
Comment: How did this integral arise?
Comment: You asked this [same question](https://math.stackexchange.com/questions/4729907/evaluate-the-integral-int-01-frac-ln1-xx-dx-by-contour-integratio) yesterday.
Comment: @Accelerator Yes , today I posted this question to mathoverflow to get some other opinions . But they found this question inappropriate for that site and so they migrated the question here . Moreover I have tried your approach of unit quater circle but I am ending up getting wrong answer . It will be helpful if you can work out the problem in answer .
Comment: My answer would be identically the same as the other answerer who came up with the quarter-pie idea. The only difference would be that I parameterize that smaller circular arc and show its contour integral converges to $0$. Other than that, my answer would practically be a duplicate.
Comment: @Accelerator I had doubts in some of his steps...which I have asked him there but are still unanswered.
Comment: In that Desmos link from yesterday, I defined any path $z(t)$ as $(x(t), y(t))$ where $t \in \mathbb{R}$. So $\int_{\text{smaller circular arc}} f(z)dz = \int_{\text{the bounds of t you saw}} f(z(t)) z'(t)dt$. There should be some small radius $r$ when you write it out, and so you would have to let $r$ approach $0$. That's one option. Another is using the ML-inequality by finding an upper bound for the integral in absolute values and the arc length of the path, then using the Squeeze Theorem, and maybe a few things here and there.
Comment: I'll see if I can find a nice way to use that unit square contour idea, per this post, and share the answer on yesterday's post. Also, even though it's mathematically valid to have a quarter-circle indentation at $z=0$, you don't need that indentation and you can just have the contour directly on it, but you would need one at $z=1$.
Answer: Denote $x=t^2$, this gives
$$
I:=\int_0^1 \frac{\ln(1-x)}{x}dx=\int_0^1 \frac{\ln(1-t^2)}{t^2}2tdt=2I+2\int_0^1\frac{\ln(1+t)}tdt.
$$
Thus $$J:=\int_{-1}^1 \frac{\ln(1-x)}xdx=I-\int_0^1\frac{\ln(1+x)}xdx=\frac32I,$$
and we proceed with computing $J$.
For this end, we change the contour $[-1,1]$ to the upper semicircle to get
$$
J=-\int_{0}^\pi \frac{\ln(1-e^{is})}{e^{is}}d(e^{is})
=-i\int_{0}^\pi \ln(-2i\sin(s/2)e^{is/2})d(s)\\=-i\int_0^\pi \ln(2\sin(s/2))ds-i\int_0^\pi i(s/2-\pi/2)ds\\=
-i\int_0^\pi \ln(2\sin(s/2))ds-\pi^2/4=-\pi^2/4,
$$
the last equality since $J$ is real. Thus $I=-\pi^2/6$.


C++ std::forward vs static_cast

Question: From what I understand, std::forward<T>(x) is equivalent to static_cast<T&&>(x).
But from what I saw, static_cast<T>(x) seems to do the same thing, as can be seen in the following code
My question is therefore why std::forward<T> is implemented as static_cast<T&&>(x), and not static_cast<T>(x), if both have the same effect?
Comment: You didn't try with `int&`.
Comment: @Quentin In that case, it always returns an lvalue.
Comment: `static_cast` would create a copy of rvalues
Comment: because you want to forward references but not values
Comment: Try it with a class where you will instrument the copy and move ctors to produce output, and observe the differences.
Answer: Because perfect forwarding allows to pass both r-value references and l-value references. This is done via reference collapsing:
T = int    --> T&& = int&&
T = int&   --> T&& = int& && = int&
T = int&&  --> T&& = int&& && = int&&

In your example with static_cast<T> you're simply losing r-value references. It works fine for primitive types (because passing int is usually copying a CPU register value), but awful for complex types because it leads to creating temporary object through copy ctors.
Comment: `static_cast` can return a reference: the answer above implies it cannot.  Can you clarify that the problem only occurs in one "case"?
Comment: I just checked it, and it is in fact calls the copy constructor for rvalue's.

But why? I read that if we call func() with an rvalue, T is deduced to be int&&, so static_cast(x) would become static_cast(x).

So why it creates a copy?
Comment: @Mikrosaft: no, `T` cannot be deduced to `int&&`, it only can be either `int` or `int&`.
Comment: @myaut It makes perfect sense now. Thank you!
Answer: If T&& is an rvalue reference, then T is a value, then static_cast<T> makes a copy not a rvalue reference.
That copy will bind to rvalue references (just like the reference), but copy/move ctors could be needlessly called, and it is not a candidate for elision.
static_cast<T&&> will meanwhile just cast to an rvalue reference.
They are otherwise identical.
Answer: I agree with Yakk, but it's worse than that.
void foo(const std::vector<int> &vec);

template<typename T>
void callFoo(T &&data)
{
    foo(static_cast<T>(data));
}

int main()
{
    callFoo(std::vector<int>{/*...*/});
}

This will always create a copy. The vector is not moved because data, as an expression, is an lvalue of type std::vector<int>, even though the substituted type is std::vector<int>&&. Note that T is std::vector<int>, not std::vector<int> &&. Moral of the story: Use the standard library, it does the right thing and the name forward also captures the intention far better than static_cast<something>.
Comment: Remark: when either [xvalue or prvalue](https://stackoverflow.com/q/3601602/5267751) is used as the argument `T` is `std::vector` and `T&&` (or `decltype(data)`) is `std::vector&&`. So `static_cast(data)` can be used, which is occasionally useful, see e.g.
 [c++ - Perfect forwarding in a lambda? - Stack Overflow](https://stackoverflow.com/q/42799208/5267751)

C++ std::forward vs static_cast


Python parsing 'True' and 'False' as strings

Question: Is there a way in python to parse the string 'True' as True (boolean) and 'False' as False (boolean)?
I know I could do bool('True') or bool('False') but each would be True
Comment: Take a look at `ast.literal_eval()`.
Comment: Can't test because I'm on my phone, can you use eval()?
Comment: Look at @Austin's answer.
Comment: Why not simply use `string == 'True'`?
Answer: Use ast.literal_eval:
>>> import ast
>>> ast.literal_eval('False')
False

If you do type(ast.literal_eval('False')), you see <class 'bool'>:
>>> type(ast.literal_eval('False'))
<class 'bool'>

You could also write your own function that returns 'True' as boolean True, 'False' as boolean False and if you supply any other input, it returns the same back:
def parse(string):
    d = {'True': True, 'False': False}
    return d.get(string, string)

Now, you call as:
>>> parse('True')
True
>>> parse('False')
False
>>> parse('Anything')
'Anything'

Answer: In this case I would not recommend ast.literal_eval or eval. The best thing to do is probably this:
def parse_boolean(b):
    return b == "True"

"True" will return True and "False" will return False.


How can I update my BIOS on my Intel NUC6i7KYK for proper internet connection?

Question: I am running Ubuntu 16.04 on an Intel NUC6i7KYK ("Skull Canyon" model).
Recently the wireless internet connection (wifi) performance has been horrendous - very slow around 1mbps or less download speed when my laptop chromebook gets 12mbps or more. Have run speedtests on the laptop & smartphone to confirm its just my NUC that's problematic. Really stressful as I play Dota 2 online for both casual and research (university) reasons. Often my ping in game jumps to 350-700 and stays there for 10+ minutes, sometimes it will be around 40ms but spike sporadically up to 350+. Loading basic pages like Google can take 30 seconds or more but sometimes its instant.
After hours of googling it seems one likely cause is an out-of-date BIOS - most recent version from Intel is 48 but I have 46.
I just tried updating using an 8GB SD card with the latest bios on it following instructions from this site https://www.intel.com/content/www/us/en/support/boards-and-kits/000005532.html
However, I recieved the error message:
"BIOS has detected unsuccessful post attempt(s).
Possible causes include recent changes to BIOS performance Options or a recent hardware change.
Press 'Y' to enter Setup or 'N' to cancel and attempt to boot with the previous settings."
I've also tried hitting F4 in the bios menu to do a BIOS Recovery, but when I check the version in terminal its still 46, AKA it hasn't updated.
So my questions are:

(1) What can I do to successfully update my BIOS?
(2) How likely is it that a BIOS update will restore proper internet connectivity to my Ubuntu NUC?
(3) What software package(s) are available for Ubuntu 16.04 that might be able to automate this update process for me and make it easier?

Relevant notes:

My wireless modem is the NetComm Wireless NF4V; I live in New Zealand and am using the ISP www.orcon.net.nz . They have no reported service issues currently
I have not yet tried plugging into my router with ethernet but plan on doing it ASAP (don't have long enough cable!)
The SD card I'm using to try update BIOS is not, as far as I can tell, a "bootable" drive (though I might be wrong!? I took it out of my digital camera since don't have any spare USB sticks lying around)
Other threads I found while googling the issue suggest that Intel NUCs are intrinsically bad with internet, AKA the metal casing or the wifi chip or something else adversely affect their internet connectivity - so could this be an issue with me as well and what can I do to fix it?
Comment: It is possible that a BIOS update could help, but I doubt it. network connectivity is determined by how well your drivers fit your card. yes, some wifi cards are notoriously bad, especially in laptops.  the manufacturer tweaks the card to get it in their machine, which requires a tweak to the driver, (ie you have to use their driver)
Comment: If Intel provides a process to update my bios of my nuc, and that process doesn't work, I doubt there is much we can do.
Comment: @ravery Thanks very much for the response and info. So, to confirm, you are suggesting the following points? (1) an update of my wireless internet-related drivers may help the issue and (2) since some wifi cards can be notoriously bad, testing an ethernet cable instead could be a potential fix as well
Comment: yes to both statements. unfortunately, many manufactures provide little support for linux, which leaves you hunting through solutions to find a tweak that works for you. searching with wifi card model can help provide fixes or newer drivers
Comment: @ravery Intel is not one of those: 5 methods and 4 of them are supported through Linux https://www.intel.com/content/www/us/en/support/boards-and-kits/000005636.html?eu-cookie-notice using a bootable usb and 3 using a none-bootable usb.
Comment: @Rinzwind @ravery thank you both for your help. Regarding wifi drivers, I have just run in terminal the following code `sudo modprobe iwlwifi` followed by `dmesg | grep iwl` which yielded messages including `Direct firmware load for iwlwifi-8000C-24.ucode failed with error -2` and `loaded firmware version 21.302800.0 op_mode iwlmvm
[    3.755937] iwlwifi 0000:03:00.0: Detected Intel(R) Dual Band Wireless AC 8260, REV=0x208` . What do these outputs mean? Sorry, I'm new to Linux, learning as I go.
Comment: @ivan make it a new question ;) Oh and we have someone on AU that can be considered The Ultimate Master of Wifi problems (chili555) so make sure to tag it "wifi")
Comment: he means [wireless] since there's no [wifi] tag (afaik)
Answer:
(1) What can I do to successfully update my BIOS?

Nowadays my bios allows updating from bios itself.
Did you see this on the Intel site on upgrading NUC? It shows 3 options for Linux with video's. Your link points to 1 of those options but the more easier method to me seems to be Power Button Menu BIOS Update Instructions for Intel® NUC.
Pick the bootable USB version and not one through an SD card. Those through a bootable USB work a lot better since it is done through a normal USB boot.

(2) How likely is it that a BIOS update will restore proper internet connectivity to my Ubuntu NUC?

Unlikely. Unless that system has a seriously flawed design where the wireless is messed with by the systems hardware (metal casing with a badly placed NIC is not unheard of).

(3) What software package(s) are available for Ubuntu 16.04 that might be able to automate this update process for me and make it easier?

See https://help.ubuntu.com/community/BIOSUpdate for specific methods per manufacturer. Option 5 (using freedos has always been my best working method) IF the normal Intel methods with a bootable usb fail. Always go for a method by the manufacturer instead of a method by the OS.

Other threads I found while googling the issue suggest that Intel NUCs are intrinsically bad with internet, AKA the metal casing or the wifi chip or something else adversely affect their internet connectivity - so could this be an issue with me as well and what can I do to fix it?

Yes, that could be the issue and the most efficient method would be to get a WLAN dongle and stop using your internal wireless. The more expensive ones are 50 euro (roughly 80 NZD acc. to google ;) ). That is besides returning the machine and getting another one ;)
Comment: Thanks very much for your detailed reply.  I had actually already tried the Power Button Menu method - sorry, didnt explain that clearly. I will give the BIOS update another go soon using a Bootable USB. Purchasing a WLAN dongle seems a potentially easy solution, thanks, I've just seen one for $27 NZD!
Comment: Yeah I said "more expensive" ones. Mind that the cheapest often work but are not the best. And make sure you get a Linux friendly one ;) But I am betting you went wrong using an SD and not a bootable USB. Good luck ! :)
Comment: an excellent reminder... appreciate that!


YouTube Data API - Members: list Code 403

Question: The request https://www.googleapis.com/youtube/v3/members fails with code 403 "Access forbidden. The request may not be properly authorized." even in the Google OAuth 2.0 Playground while all other requests succeed. Does that mean I am missing the approval from YouTube? I have completed the forms to request the approval several weeks ago, but I have yet to get any response from  YouTube.

API request with parameters used
https://youtube.googleapis.com/youtube/v3/members?part=snippet

Result

<code>{
  "code" : 403,
  "errors" : [ {
    "domain" : "youtube.common",
    "message" : "Access forbidden. The request may not be properly authorized.",
    "reason" : "forbidden"
  } ],
  "message" : "Access forbidden. The request may not be properly authorized."
}
</code>

Expected result
Response body with Members List

Is it 100% reproducible?
Yes

Reproducible API explorer link
https://developers.google.com/oauthplayground/
Comment: I think you forgot your question. is this supposed to be a bug report or something?
Comment: Welcome to stack please read [ask] edit your quest describe your issue, include any code and or error messages.
Comment: Hello there! I have the same problem! Have you found a solution?
Answer: approval
If you check the top of the page for
members.list you will see that this method has been replaced by sponsors.list

So calling Members.list isnt going to work.  You ened to call sponsors.list and you need permission from google inorder to call that
authorization
Assuming you have summited the form and requested access to the new sponsors.list method and have been granted access you should know that calling memebers.list wont work. As its been deprecated you need to call sposors.list and it needs to be authorized. I would guess with the same scope as before.

The message is telling you that you have summited the request without being properly authorized to access the data.

Access forbidden. The request may not be properly authorized.

You need an access token sent as an authorization header before you will be able to make that call please check authorization
As this new method isn't documented I would have to guess it would be something like this.
<code>GET https://youtube.googleapis.com/youtube/v3/sponsors?part=snippet?key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
</code>
If you have been granted access to this method then you might have an email contact at google that you can ask what the actual call is if its not working.
Comment: Thanks for your reply. You're getting it mixed up. Members.List is not deprecated, Sponsors.List is deprecated. Members.List is on the Google OAuth 2.0 Playground as it is listed in Step 3 under "List possible operations". My initial question was, is the response in my question the one you get when you're missing the approval from Google?
Comment: I know that and the request is authorized with the correct scope.
You can replicate this behaviour yourself here:
https://developers.google.com/oauthplayground/

1. Select the youtube.channel-memberships.creator scope
2. Exchange authorization code for tokens
3. Request GET https://www.googleapis.com/youtube/v3/members?part=snippet
Comment: sponsors list isnt on oauth playgroud as you need access to it.  members list isnt there either as its deprecated so im not sure what your doing.
Comment: The response you are getting is the one from a lack of authorization either you are not sending your access token or they have not granted you access yet. Have you heard from them when did they grant you access?


Mongo with Spring Data - Use Distinct and Orderby in the same query

Question: I am working on some dataset whose json format for one object is given below.
{
  _id: ............,
   code : G12220,
   type : etf,
   volume : 13,
   modified_time:..................
   .
   .
   .
}

This dataset gets updated very frequently (every 1 minute) and there are few thousands unique codes. I want to write a query to fetch the set of documents for each of the most latest distinct "codes" available. Eg: If there are two documents each having same code the result should be the most latest. I am using Spring Data.
I started writing my query and the given below is a sample.
@Query("{type : ?0}......")
public List<ProductEntities> getLatestProductsSet(String type);

I am not very sure how to write a complex query on this. Would be grateful if you can help me.
Thanks in advance,
Answer: You might want to have a look at the following mongo query to achieve this.
db.collection.aggregate([
    {
        "$group": {
            "_id": {
                "code": "$code",
                "modifiedTime": "$modified_time"
            },
            "docs": {
                "$push": "$$ROOT"
            }
        }
    },
    {
        "$sort": {
            "_id.modifiedTime": -1
        }
    },
    {
        "$limit": 1
    }
]);

Following are the links which will help you understand the above query.
http://docs.mongodb.org/manual/reference/operator/aggregation/group/
http://docs.mongodb.org/manual/reference/operator/aggregation/sort/
http://docs.mongodb.org/manual/reference/operator/aggregation/push/
http://docs.mongodb.org/manual/reference/operator/aggregation/limit/

Spring part follows.
http://www.mkyong.com/mongodb/spring-data-mongodb-aggregation-grouping-example/

Let me know, if this helps.


Changing Activity to Fragment with sqlite db

Question: I have recently tried to change a working sqlite populated listview activity into a fragment. I have made the changes needed but I continue to get errors that i dont understand. If any of you could help it would relieve serious frustration.
Here is my main activity
public class FoursFragment extends Fragment {

private DbHelper mHelper;
private SQLiteDatabase dataBase;

private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();

private ListView userList;
private AlertDialog.Builder build;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.display_activity, container, false);

    userList = (ListView) view.findViewById(R.id.List);

    mHelper = new DbHelper(getActivity());

    //add new record
    getView().findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("update", false);
            startActivity(i);

        }
    });

    //click to update data
    userList.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            Intent i = new Intent(getActivity(),
                    AddActivity.class);
            i.putExtra("Fname", user_fName.get(arg2));
            i.putExtra("Lname", user_lName.get(arg2));
            i.putExtra("ID", userId.get(arg2));
            i.putExtra("update", true);
            startActivity(i);

        }
    });

    //long click to delete data
    userList.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {

            build = new AlertDialog.Builder(getActivity());
            build.setTitle("Delete " + user_fName.get(arg2) + " "
                    + user_lName.get(arg2));
            build.setMessage("Do you want to delete ?");
            build.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {

                            Toast.makeText(
                                    getActivity(),
                                    user_fName.get(arg2) + " "
                                            + user_lName.get(arg2)
                                            + " is deleted.", 3000).show();

                            dataBase.delete(
                                    DbHelper.TABLE_NAME,
                                    DbHelper.KEY_ID + "="
                                            + userId.get(arg2), null);
                            displayData();
                            dialog.cancel();
                        }
                    });

            build.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = build.create();
            alert.show();

            return true;
        }
    });
    return view;
}

@Override
public void onResume() {
    displayData();
    super.onResume();
}

/**
 * displays data from SQLite
 */
private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
            + DbHelper.TABLE_NAME, null);

    userId.clear();
    user_fName.clear();
    user_lName.clear();
    if (mCursor.moveToFirst()) {
        do {
            userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
            user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
            user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName);
    userList.setAdapter(disadpt);
    mCursor.close();
}

}
Here is adapter that is called.
public class DisplayAdapter extends BaseAdapter {

 private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;

public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
    this.mContext = c;

    this.id = id;
    this.firstName = fname;
    this.lastName = lname;
}

public int getCount() {
    // TODO Auto-generated method stub
    return id.size();
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public View getView(int pos, View child, ViewGroup parent) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (child == null) {
        layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        child = layoutInflater.inflate(R.layout.listcell, null);
        mHolder = new Holder();
        mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
        mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
        mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
        child.setTag(mHolder);
    } else {
        mHolder = (Holder) child.getTag();
    }
    mHolder.txt_id.setText(id.get(pos));
    mHolder.txt_fName.setText(firstName.get(pos));
    mHolder.txt_lName.setText(lastName.get(pos));

    return child;
}

public class Holder {
    TextView txt_id;
    TextView txt_fName;
    TextView txt_lName;
}

}
And here is the DBhelper.
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT)";
    db.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

}
The error i receive is as follows
03-20 13:15:50.108: E/AndroidRuntime(795): FATAL EXCEPTION: main
03-20 13:15:50.108: E/AndroidRuntime(795): java.lang.NullPointerException
03-20 13:15:50.108: E/AndroidRuntime(795):  atapp.norman.tennis.FoursFragment.onCreateView(FoursFragment.java:52)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:795)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:998)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.BackStackRecord.run(BackStackRecord.java:622)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1330)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.FragmentManagerImpl$1.run(FragmentManager.java:417)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Handler.handleCallback(Handler.java:605)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.os.Looper.loop(Looper.java:137)
03-20 13:15:50.108: E/AndroidRuntime(795):  at android.app.ActivityThread.main(ActivityThread.java:4340)
03-20 13:15:50.108: E/AndroidRuntime(795):  at java.lang.reflect.Method.invokeNative(Native Method)
03-20 13:15:50.108: E/AndroidRuntime(795):  at java.lang.reflect.Method.invoke(Method.java:511)
03-20 13:15:50.108: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-20 13:15:50.108: E/AndroidRuntime(795):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-20 13:15:50.108: E/AndroidRuntime(795):  at dalvik.system.NativeStart.main(Native Method)

I really don't mind if it is something stupid but really cant figure out what is going on! Thankyou!
Answer: Replace
//add new record
getView().findViewById(...

with
//add new record
view.findViewById(...

getView() in onCreateView() is too early - you haven't yet returned the view to the framework for getView() to return.