Q: Differential eqs gives the error: 'is neither a list of replacement rules nor a valid dispatch table, \ and so cannot be used for replacing' I am trying to solve these differential equations, so I can get a list of y values for different values of R. I only keep getting the message: 'is neither a list of replacement rules nor a valid dispatch table, \ and so cannot be used for replacing.'
I've tried to use ?NumericQ, but I didn't manage to get rid of the errors or I used ?NumericQ wrong . The script worked perfectly when I didn't have the differentialeqY  and the stuff that did go with the differntialeqY (like the boundary conditions of y). I would really appreciate if someone could help me out!
Cconst = 2.99792458*10^(10);(*speed of light in cm/s*)

Gconst = 6.67408*10^(-8);
msun = 1988500*10^(24)*10^3;
msunincm = Gconst/Cconst^2*msun;
densitypercm2 = Gconst/Cconst^2;
Centi = 1/msunincm // N;
second = Cconst/msunincm // N;
gram = 1/msun // N;
gcm3 = gram/Centi^3 // N;
km = 10^5*Centi;
press = gcm3/Cconst^2;
dynecm2 = gcm3/Cconst^2;
rmin = 1*10^(-10);
rmax = 15.;
rhotest = 10^(15) gcm3;
(* This takes the K values from the Read paper, multiplied with c^2 \
to get the right units, and converts
them into units where c=G=msun=1*)

Kgeom[Kcgs_, gamma_] := Kcgs *dynecm2/(gcm3^gamma)
pressure[\[Rho]_, K_, \[CapitalGamma]_] := K*\[Rho]^\[CapitalGamma] ;
density[p_, K_, \[CapitalGamma]_] := (p/K)^(1/\[CapitalGamma]) ;
epsilon[p_, K_, \[CapitalGamma]_,
  a_] := (K/(\[CapitalGamma] - 1)) *
   density[p, K, \[CapitalGamma]]^\[CapitalGamma] + (1 + a )*
   density[p, K, \[CapitalGamma]]
(* mass-energy density *)
(* Polytrope crust definition, first is the \
K-value, second is gamma, third is border-value;in geometric units *)

aFun[a_, g1_, g2_, Kval1_, Kval2_,
   rhoVal_] := (epsilon[pressure[rhoVal, Kval1, g1], Kval1, g1, a]/
     rhoVal) - 1 - (Kval2/(g2 - 1))*rhoVal^(g2 - 1);
ReadCrustgeom := {
   {Kgeom[6.8011*10^-9* Cconst^2, 1.5842], 1.5842,
    2.44034*10^7 gcm3},
   {Kgeom[1.06186*10^-6 * Cconst^2, 1.28733], 1.28733,
    3.78358*10^11 gcm3},
   {Kgeom[5.32697*10^1* Cconst^2, 0.62223], 0.62223,
    2.62780*10^12 gcm3},
   {Kgeom[3.99874*10^-8 * Cconst^2, 1.35692], 1.35692}};
(* rho1 and and rho2 from Read*)
\[Rho]1 = 10^14.7 gcm3;
\[Rho]2 = 10^15.0 gcm3;

EosDefinitions := {{"EoS", "Pressure p1",  "\[CapitalGamma]1",
    "\[CapitalGamma]2", "\[CapitalGamma]3"},
   {"SLy", 10^34.384 dynecm2, 3.005, 2.988, 2.851},
   {"ENG", 10^34.437 dynecm2, 3.514, 3.130, 3.168},
   {"MPA1", 10^34.495 dynecm2, 3.446, 3.572, 2.887},
   {"MS1", 10^34.858 dynecm2, 3.224 , 3.033, 1.325},
    {"MS1b", 10^34.858 dynecm2, 3.456, 3.011, 1.425},
   {"H4", 10^34.6692 dynecm2, 2.909, 2.246, 2.144},
   {"ALF2", 10^34.616 dynecm2, 4.070, 2.411, 1.890}};

mrModule[dens_, gamm1_, gamm2_, gamm3_] :=
 Module[{p1 = dens, \[CapitalGamma]1 = gamm1, \[CapitalGamma]2 =
    gamm2, \[CapitalGamma]3 = gamm3},
  K1 = const /.
    Solve[pressure[\[Rho]1, const, \[CapitalGamma]1] == p1 , const][[
     1]]; (* since p1 is known we can calculate the value of K1*)

  K2 = (K1*\[Rho]1^\[CapitalGamma]1)/(\[Rho]1^\[CapitalGamma]2);
  K3 = (K2*\[Rho]2^\[CapitalGamma]2)/(\[Rho]2^\[CapitalGamma]3);
  \[Rho]0 = (K1/
      ReadCrustgeom[[4,
       1]])^(1/(ReadCrustgeom[[4, 2]] - \[CapitalGamma]1));
  pPW[rho_] := Piecewise[
    {{pressure[rho, ReadCrustgeom[[1, 1]], ReadCrustgeom[[1, 2]]],
      0 < rho <= ReadCrustgeom[[1, 3]]},
     {pressure[rho, ReadCrustgeom[[2, 1]], ReadCrustgeom[[2, 2]]],
      ReadCrustgeom[[1, 3]] < rho <= ReadCrustgeom[[2, 3]]},
     {pressure[rho, ReadCrustgeom[[3, 1]], ReadCrustgeom[[3, 2]]],
      ReadCrustgeom[[2, 3]] < rho <= ReadCrustgeom[[3, 3]]},
     {pressure[rho, ReadCrustgeom[[4, 1]], ReadCrustgeom[[4, 2]]],
      ReadCrustgeom[[3, 3]] < rho <= \[Rho]0 },
     {pressure[rho, K1, \[CapitalGamma]1],  \[Rho]0 <
       rho <= \[Rho]1},
     {pressure[rho, K2, \[CapitalGamma]2],   \[Rho]1 < rho <= \[Rho]2},
     {pressure[rho, K3, \[CapitalGamma]3],  rho >  \[Rho]2}}];
  aMinus3 = 0;
  aMinus2 =
   aFun[aMinus3, ReadCrustgeom[[1, 2]], ReadCrustgeom[[2, 2]],
    ReadCrustgeom[[1, 1]], ReadCrustgeom[[2, 1]],
    ReadCrustgeom[[1, 3]]];
  aMinus1 =
   aFun[aMinus2, ReadCrustgeom[[2, 2]], ReadCrustgeom[[3, 2]],
    ReadCrustgeom[[2, 1]], ReadCrustgeom[[3, 1]],
    ReadCrustgeom[[2, 3]]];
   a0 = aFun[aMinus1, ReadCrustgeom[[3, 2]], ReadCrustgeom[[4, 2]],
    ReadCrustgeom[[3, 1]], ReadCrustgeom[[4, 1]],
    ReadCrustgeom[[3, 3]]];
  a1 = aFun[a0, ReadCrustgeom[[4, 2]], \[CapitalGamma]1,
    ReadCrustgeom[[4, 1]], K1, \[Rho]0];
  a2 = aFun[a1, \[CapitalGamma]1, \[CapitalGamma]2, K1, K2, \[Rho]1];
  a3 = aFun[a2, \[CapitalGamma]2, \[CapitalGamma]3, K2, K3, \[Rho]2];
  epsiPiece[pressure_] := Piecewise[
    {{epsilon[pressure, ReadCrustgeom[[1, 1]], ReadCrustgeom[[1, 2]],
       aMinus3],  0 < pressure <= pPW[ReadCrustgeom[[1, 3]]]},
     {epsilon[pressure, ReadCrustgeom[[2, 1]], ReadCrustgeom[[2, 2]],
       aMinus2],
      pPW[ReadCrustgeom[[1, 3]] ] < pressure <=
       pPW[ReadCrustgeom[[2, 3]]]},
     {epsilon[pressure, ReadCrustgeom[[3, 1]], ReadCrustgeom[[3, 2]],
       aMinus1],
      pPW[ReadCrustgeom[[2, 3]]] < pressure <=
       pPW[ReadCrustgeom[[3, 3]]]},
     {epsilon[pressure, ReadCrustgeom[[4, 1]], ReadCrustgeom[[4, 2]],
       a0],  pPW[ReadCrustgeom[[3, 3]]] < pressure <= pPW[\[Rho]0] },
     {epsilon[pressure, K1, \[CapitalGamma]1, a1],
      pPW[\[Rho]0]  < pressure <= pPW[\[Rho]1]},
     {epsilon[pressure, K2, \[CapitalGamma]2, a2],
      pPW[\[Rho]1] < pressure <= pPW[\[Rho]2]},
     {epsilon[pressure, K3, \[CapitalGamma]3, a3],
      pressure >  pPW[\[Rho]2]}}];
  mmPrimePoly :=
   4 \[Pi] r^2 * epsiPiece[p[r]]  == Derivative[1][mm][r];
  TOVPoly := (mm[r] +
        4 \[Pi] r^3 p[r]) ((p[r] +
          epsiPiece[p[r]] )/(r (r - 2 mm[r])) ) +
     Derivative[1][p][r] == 0;
  Differentialequation :=
   ry'[r] + y[r]^2 +
     y[r] (1 - (2 mm[r])/r)^-1 (1 +
        4 \[Pi] r^2 (p[r] - epsiPiece[r])) +
     r^2 (4 \[Pi] (1 - (2 mm[r])/r)^-1 (5 epsiPiece[r] +
           9 p[r] + (epsiPiece[r] + p[r])/D[p[r], epsilon[r]]) - (
        6 (1 - (2 mm[r])/r)^-1)/
        r^2 - (2/r (mm[r] + 4 \[Pi] r^3 p[r])/(r - 2 mm[r]))^2) == 0;
  solutionsME[\[Rho]0_] := NDSolve[
     {mmPrimePoly,
      TOVPoly,
      Differentialequation ,
      p[rmin] == pPW[\[Rho]0],
      WhenEvent[p[r] - rmin, "StopIntegration"],
      y[rmin] == 2,
      mm[rmin] == epsiPiece[pPW[\[Rho]0]]*4/3*\[Pi]*rmin^3},
     {mm, p, y},
     {r, rmin, rmax}, Method -> {"DiscontinuityProcessing" -> False},
     PrecisionGoal -> 15, AccuracyGoal -> 15,
     WorkingPrecision -> 25] // Quiet;
  Radius[\[Rho]_] := (p /. solutionsME[\[Rho]][[1]])[[2]] ;
  mass[\[Rho]_, r_] := (mm[r] /. solutionsME[\[Rho]][[1]]) ;
  differentialeqY[\[Rho]_, r_,
    mm_] := (y[r] /. solutionsME[\[Rho]][[1]]) ;
  radiusTable = Table[{
     i,
     10^(i) gcm3,
      Radius[10^(i) gcm3]},
    {i, 13.5, 15.9, 0.4}];
  analysis = MapThread[List, {radiusTable[[All, 3]],
     differentialeqY @@@
      MapThread[
       List, {radiusTable[[All, 2]], radiusTable[[All, 3]]}]}];
  MapThread[List, {analysis[[All, 1]], analysis[[All, 2]]}]]

mrResult =
  ParallelMap[mrModule @@ # &, EosDefinitions[[2 ;; All, 2 ;; All]]];

This is the latex expression for the equation:
r y'(r) + y(r)^2 +y(r) \bigg[1-\frac{2m(r)}{r}\bigg]^{-1}(1+4 \pi r^2[p(r) - \epsilon(r)])
+ r^2\big(4\pi \bigg[1-\frac{2m(r)}{r}\bigg]^{-1}\bigg[5\epsilon(r) + 9p(r) + \frac{\epsilon(r) + p(r)}{\frac{dp}{d\epsilon}} \bigg]
- \frac{6\bigg[1-\frac{2m(r)}{r}\bigg]^{-1}}{r^2} - \bigg(\frac{2}{r}\bigg[\frac{m(r) + 4\pi p(r) r^3}{r - 2m(r)}\bigg]\bigg{)^2}\big)=0

and this is just a picture of the equation


Q: How is there a connection between energy and information? http://physicsworld.com/cws/article/news/2010/nov/19/information-converted-to-energy
In the last part of the third paragraph of the above article it says:
"In fact, Szilárd formulated an equivalence between energy and information, calculating that kTln2 (or about 0.69 kT) is both the minimum amount of work needed to store one bit of binary information and the maximum that is liberated when this bit is erased, where k is Boltzmann's constant and T is the temperature of the storage medium. "
Now, I find this connection between energy and information rather odd for the following reason: Consider two computational systems, each made of buckets of water, with the only difference between the two being the size of the buckets. That is, system A consists of 10 liter buckets while system B consists of 1 liter buckets. It seems evident that the amount of work done to perform a computation in system A would be a lot more than the amount of work done to perform the same computation on system B. My main point from this analogy is that energy required to store or manipulate bits of information seems to be technology-dependent. Can someone come up with the weakness in my analogy or provide a better analogy that could explain how the energy-information equivalence is valid? (I have only a rudimentary understanding of the concept of information).

A: The information isn't stored in the bucket, it's stored in a device which is exchanging thermal energy with the bucket, like a ball in one of two minima in a cup. You need to move the ball between the minima to write the information, and to make this store data, you need to reduce the phase space volume of the ball plus water by a factor of 2, which gives the bound you are talking about. The phase space volume is the definition of entropy. The relation is not there at zero temperature, you can store bits with arbitrarily small amounts of energy then.


Q: php for loop skips by twos I have a function in php that builds an html string for a table so at inside I have a for loop
for ($counter = 0; $counter<10; $counter++){
  $htmlString .= code for table row here;
}

The for loop only makes 5 rows and i even printed out the value of $counter and it says: 0, 2, 4, 6, 8
I have never seen this before and I can't think of any way to fix this other than changing the loop from 10 to 20 but I rather know what is causing this so I can fix it for good.
here is my full code for the function i pass in a row from a sql db:
function BuildNetworkString($Query){
        $NetworkHtml = "

";
        $counter = 0;
        if($Query['FacebookID'] != '')
        {
            $NetworkHtml .= "	";
            $counter+=1;
        }
        for ($counter; $counter<10; $counter++)
        {
            $NetworkHtml .= "&nbsp ; $counter	";
        }
        $NetworkHtml .= "

";
        return $NetworkHtml;
    }

A: Try changing:
"&nbsp ; $counter	"

to:
"  $counter	"


Q: How to eliminate the repetition of same rows I have a table in my database which looks like (there can be same tuples in table):
+-------------+---------+--------+
| ProductName | Status  | Branch |
+-------------+---------+--------+
| P1          | dead    |      1 |
| P1          | dead    |      2 |
| P1          | dead    |      2 |
| P2          | expired |      1 |
+-------------+---------+--------+

I want to show the result after as (the Branch attribute is dynamic):
+-------------+---------+--------+
| ProductName | Branch 1|Branch 2|
+-------------+---------+--------+
| P1          | dead    |    dead|
| P2          | expired |     OK |
+-------------+---------+--------+

After some help i came up with following solution:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
  'GROUP_CONCAT(case when branch = ''',
  branch,
  ''' then status ELSE NULL end) AS ',
  CONCAT('Branch',branch)
 )
) INTO @sql
FROM Table1;

SET @sql = CONCAT('SELECT productName, ', @sql, '
               FROM Table1
               GROUP BY productName');

PREPARE stmt FROM @sql;
EXECUTE stmt;

The result shown is like:
+-------------+---------+-----------+
| productName | Branch1 |  Branch2  |
+-------------+---------+-----------+
| p1          | dead    | dead,dead |
| p2          | expired | (null)    |
+-------------+---------+-----------+

SQL Fiddle. What i want now is to show product status as "OK" instead of null when status is null and also need not to concatenate the status if there is a repetition of a product in the table..tried a lot, but couldn't sort out. Thanks in advance.

A: This is a bit tricky because there will be repetion if statuses are the same,so the coalesce has to be on the outside of the GROUP_CONCAT
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'COALESCE(GROUP_CONCAT(DISTINCT case when branch = ''',
      branch,
      ''' then  status  end),''OK'') AS ',
      CONCAT('Branch',branch)
    )
  ) INTO @sql
FROM Table1;

SET @sql = CONCAT('SELECT productName, ', @sql, '
                   FROM Table1
                   GROUP BY productName');

PREPARE stmt FROM @sql;
EXECUTE stmt;

Link


Q: Force code to execute in order? I am seeing a strange problem in my C# code. I have something like this:
public static class ErrorHandler {
  public static int ErrorIgnoreCount = 0;
  public static void IncrementIgnoreCount() {
    ErrorIgnoreCount++;
  }
  public static void DecrementIgnoreCount() {
    ErrorIgnoreCount--;
  }
  public static void DoHandleError() {
    // actual error handling code here
  }
  public static void HandleError() {
    if (ErrorIgnoreCount == 0) {
      DoHandleError();
    }
  }
}

public class SomeClass {

  public void DoSomething() {
    ErrorHandler.IncrementIgnoreCount();
    CodeThatIsSupposedToGenerateErrors(); // some method; not shown
    ErrorHandler.DecrementIgnoreCount();
  }
}

The problem is that the compiler often decides that the order of the three calls in the DoSomething() method is not important. For example, the decrement may happen before the increment. The result is that when the code that is supposed to generate errors is run, the error handling code fires, which I don't want.
How can I prevent that?

A: Add Trace or Logs to your code in IncrementIgnoreCount, DecrementIgnoreCount and HandleError function.
That will help you to view real call order.


Q: Pandas error TypeError: bad operand type for unary ~: 'float' I have inherited this piece of code
dummy_data1 = {
    'id': ['1', '2', '3', '4', '5'],
    'Feature1': ['A', 'C', 'E', 'G', 'I'],
    'Feature2': ['Mouse', 'dog', 'house and parrot', '23', np.NaN],
    'dates': ['12/12/2020','12/12/2020','12/12/2020','12/12/2020','12/12/2020']}

df1 = pd.DataFrame(dummy_data1, columns = ['id', 'Feature1', 'Feature2', 'dates'])

df1 = df1.assign(
                    Feature2=lambda df: df.Feature2.where(
                        ~df.Feature2.str.isnumeric(),
                        pd.to_numeric(df.Feature2, errors="coerce").astype("Int64"),
                    )
    )

print(df1)

I know that this is because of the np.NAN value. What does the code do? My understanding is that it tries to convert the String to Int, if it is of type integer. Also please tell me how to overcome this issue.

A: You can try via pd.to_numeric() and then fill NaN's:
df['Feature2']=pd.to_numeric(df['Feature2'], errors="coerce").fillna(df['Feature2'])

OR
go with the where() condition by filling those NaN's with fillna() in your condition ~df.Feature2.str.isnumeric():
df['Feature2']=df['Feature2'].where(~df.Feature2.str.isnumeric().fillna(True),
                     pd.to_numeric(df.Feature2, errors="coerce").astype("Int64")
                    )


Q: MySQL - Filter one last item I am trying to count the different majors involved in various program courses. I have it mostly done, but noticed that I am counting duplicate usernames if they are registered for more than one course. Can you help me get the DISTINCT tag somewhere in this query?
SELECT a.`major_desc` AS `major`,
(SELECT COUNT(a.`major_desc`) FROM all_students WHERE major_desc=`major` LIMIT 1) AS `count`
FROM all_students AS a
INNER JOIN all_course_reg AS b ON a.username=b.username
INNER JOIN courses AS c ON b.`crn`=c.`crn`
GROUP BY `major`

EDIT: sqlfiddle -> http://sqlfiddle.com/#!2/81bb0/3/0

A: It seems to me that this is what you're after - I don't know what all that other stuff is for...
SELECT major_desc, COUNT(*) cnt
  FROM all_students
 GROUP
    BY major_desc;

A: Here we go. Thanks to my boy 3mHz.
SELECT a.major_desc,
   (select count(a.username)) as test
FROM all_students AS a
WHERE EXISTS (select * from all_course_reg
    inner join courses on courses.crn=all_course_reg.crn
    where all_course_reg.username=a.username)
GROUP BY a.major_desc

So we now get the right count for each major if the course is offered within the set of program courses.


Q: Environments with matched parens in \begin and \end Suppose I have this sort of expression in a document.
\multicolumn{8}{l}{%
\parbox{25em}{%
\begin{itemize}
\addtolength{\itemsep}{-1em}
\item foo
\item bar
\end{itemize}%
}}

I'd like to define a new environment, call it "comment" that would allow me to simple write
\begin{comment}
\item foo
\item bar
\end{comment}

and produce the same output. The problem I've encountered is that the parentheses that are opened at the start are only balanced at the very end. That creates a problem if I try to define the "begin"-section of the new environment in the flatfooted way:
\newenvironment{comment}{%
  \multicolumn{8}{l}{%
  \parbox{25em}{%
  \begin{itemize}
  \addtolength{\itemsep}{-1em}
}

The parentheses are unbalanced right now, and if I were to balance them inside the definition of the "begin" part of the environment, I'd get the wrong result.
Here's an MWE
    \documentclass{article}

\def\Boxes{%
  $\Box$ & $\Box$ & $\Box$ & $\Box$ & $\Box$ & $\Box$ & $\Box$%
}
\usepackage{fullpage}

\begin{document}

\begin{table}[h!]
  \begin{tabular}{l|ccccccc}
    & Tue & Wed & Thur & Fri & Sat & Sun & Mon\\
    \hspace{1em}B$^{\flat}$ Major & \Boxes\\

    \multicolumn{8}{l}{%
      \parbox{25em}{%
      \begin{itemize}
        \addtolength{\itemsep}{-1em}
      \item foo
      \item bar
\end{itemize}%
}}
\\
\end{tabular}
\end{table}
\end{document}

A: As noted in comments you can collect up the environment in lrbox. As noted in Werner's and Heiko's comments you can't use a standard \begin before \multicolumn so this fudges \begin slightly.
    \documentclass{article}
%! LaTeX Error: Command \Box not provided in base LaTeX2e.
% make supplied MWE processable, grumble
\usepackage{amssymb}

\def\Boxes{%
  $\Box$ & $\Box$ & $\Box$ & $\Box$ & $\Box$ & $\Box$ & $\Box$%
}
\usepackage{fullpage}

\makeatletter
% only need this for \begin{spanlist} syntax otherwise skip this and use
% \spanlist....\endspanlist
\let\oldbegin\begin
\let\oldend\end
\def\begin#1{%
  \expandafter\ifx\csname#1\endcsname\spanlist
    \expandafter\@firstoftwo
  \else
  \expandafter\expandafter\expandafter\oldbegin\expandafter\@gobble
  \fi
  \spanlist{#1}}
\def\end#1{%
  \expandafter\ifx\csname#1\endcsname\spanlist
    \expandafter\@firstoftwo
  \else
  \expandafter\expandafter\expandafter\oldend\expandafter\@gobble
  \fi
  \endspanlist{#1}}
% end of scary \begin/\end redefinition.
\makeatother

\newenvironment{spanlist}
 {\omit\begin{lrbox}{0}\begin{minipage}{25em}\begin{itemize}\addtolength{\itemsep}{-1em}}
 {\end{itemize}\end{minipage}\end{lrbox}%
  \span\multicolumn{7}{l}{\usebox{0}}}

\begin{document}

% never use[h] on its own
%\begin{table}[h!]
\begin{table}[htp!]
  \begin{tabular}{l|ccccccc}
    & Tue & Wed & Thur & Fri & Sat & Sun & Mon\\
    \hspace{1em}B$^{\flat}$ Major & \Boxes\\
\begin{spanlist}
      \item foo
      \item bar
\end{spanlist}
\\
\end{tabular}
\end{table}
\end{document}


Q: Update columns for the first user inserted I'm trying to create a trigger and a function to update some columns (roles and is_verified) for the first user created. Here is my function :
CREATE OR REPLACE FUNCTION public.first_user()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
DECLARE
    begin
        if(select count(*) from public.user = 1) then
        update new set new.is_verified = true and new.roles = ["ROLE_USER", "ROLE_ADMIN"]
        end if;
    return new;
    end;
$function$
;

and my trigger :
create trigger first_user
before insert
    on
    public.user for each row execute function first_user()

I'm working on Dbeaver and Dbeaver won't persist my function because of a syntax error near the "=". Any idea ?

A: Quite a few things are wrong in your trigger function. Here it is revised w/o changing your business logic.
However this will affect the second user, not the first. Probably you shall compare the count to 0. Then the condition shall be if not exists (select from public.user) then
CREATE OR REPLACE FUNCTION public.first_user()
RETURNS trigger LANGUAGE plpgsql AS
$function$
begin
   if ((select count(*) from public.user) = 1) then
   -- probably if not exists (select from public.user) then
        new.is_verified := true;
        new.roles := array['ROLE_USER', 'ROLE_ADMIN'];
   end if;
   return new;
end;
$function$;


Q: How to check a particular part of url using php I have a url in a variable.
<?php
$a='www.example.com';
?>

I have another variable, that has like this
<?php
$b='example.com';
?>

In what way I can check that $b and $a are same. I mean even if the url in $b is like
'example.com/test','example.com/test.html','www.example.com/example.html'

I need to check that $b is equal to $a in this case. If it is like example.net/example.org as the domain name changes, it should return false.
I checked with strpos and strcmp. But I didn't find it is the correct way to check in case of urls.What function can I use to check that $b in this case is similar to $a?

A: You can use parse_url to do the heavy lifting and then split the hostname by the dot, checking if the last two elements are the same:
$url1 = parse_url($url1);
$url2 = parse_url($url2);

$host_parts1 = explode(".", $url1["host"]);
$host_parts2 = explode(".", $url2["host"]);

if ($host_parts1[count($host_parts1)-1] == $host_parts2[count($host_parts2)-1] &&
   ($host_parts1[count($host_parts1)-2] == $host_parts2[count($host_parts2)-2]) {
   echo "match";
} else {
   echo "no match";
}

A: You could use parse_url for parsing the URL and get the root domain, like so:

*

*Add http:// to the URL if not already exists

*Get the hostname part of the URL using PHP_URL_HOST constant

*explode the URL by a dot (.)

*Get the last two chunks of the array using array_slice

*Implode the result array to get the root domain

A little function I made (which is a modified version of my own answer here):
function getRootDomain($url)
{
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
        $url = "http://" . $url;
    }

    $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
    return $domain;
}

Test cases:
$a = 'http://example.com';
$urls = array(
    'example.com/test',
    'example.com/test.html',
    'www.example.com/example.html',
    'example.net/foobar',
    'example.org/bar'
    );

foreach ($urls as $url) {
    if(getRootDomain($url) == getRootDomain($a)) {
        echo "Root domain is the same\n";
    }
    else {
        echo "Not same\n";
    }
}

Output:
Root domain is the same
Root domain is the same
Root domain is the same
Not same
Not same

Note: This solution isn't foolproof and could fail for URLs like example.co.uk and you might want to additional checks to make sure that doesn't happen.
Demo!

A: I think that this answer can help: Searching partial strings PHP
Since these URLs are just strings anyway


Q: Describe file content in swagger I'm working on documenting our existing API's in swagger using open api 3.0.0 specification. I would like to understand the procedure on documenting the contents of a file that is to be uploaded. For e.g.
Say the file that is to be uploaded is response.json, and it has the following content:
{
 name: xyz,
 age: 50
}
I would like to know the procedure for documenting the above JSON so that clients using our API should provide the file in the aforesaid JSON format.


Q: Save File on Filesystem using werkzeug I am trying to save uploaded file on my system. at specific path but i am getting this error in windows. can someone tell me where i am doing mistake?
system: windows 8.1
python version: 2.7
Here is my code:
# -*- coding: utf-8 -*-

from werkzeug.serving import run_simple
from werkzeug.wrappers import BaseRequest, BaseResponse
import os

def view_file(req):
    if not 'file' in req.files:
        return BaseResponse('no file uploaded')
    f = req.files['file']

    s = "C:\Users\admin\Desktop\test"
    f.save(s, f.filename)
    return BaseResponse('File Saved!')

def upload_file(req):
    return BaseResponse('''

Upload File

    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
    ''', mimetype='text/html')

def application(environ, start_response):
    req = BaseRequest(environ)
    if req.method == 'POST':
        resp = view_file(req)
    else:
        resp = upload_file(req)
    return resp(environ, start_response)

if __name__ == '__main__':
    run_simple('localhost', 5000, application, use_debugger=True)

here is traceback:
Traceback (most recent call last):
  File "C:\Users\admin\Desktop\test.py", line 30, in application
    resp = view_file(req)
  File "C:\Users\admin\Desktop\test.py", line 13, in view_file
    f.save(s, f.filename)
  File "C:\Python27\lib\site-packages\werkzeug\datastructures.py", line 2703, in
 save
    dst = open(dst, 'wb')
IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\\Users\x07dmin\\Desktop
\test'

A: I don't know why are you all mixing up all things, just keep it easy and clean.
Make two files called 'app.py' and 'index.html' and make a folder in your app root dirrectory called "upload"
index.html

Upload File

<form action="/uploader" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

app.py
from flask import Flask, request,render_template
from werkzeug import secure_filename
import os

app = Flask(__name__)

uploads_dir = "upload"

@app.route("/")
def index():
        return render_template('index.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def uploader():
    if request.method == 'POST':
        input = request.files['file']
        input.save(os.path.join(uploads_dir, secure_filename(input.filename)))
        #print(input)
        return "
Successfully uploaded
"

if __name__ == '__main__':
   app.run()

You can also redirect to other page after saving the file:
return render_template(otherpage.html)

A: It looks like the \a is being interpreted as a control character.
You should write the path like this:
s = "C:\\Users\\admin\\Desktop\\test"

If you're calling .save() you must also close the file: http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage.save
Also you need to provide a buffer size to .save().
So try:
f.save(s, buffer_size=16384)
f.close()


Q: Using Api keys with AWS API Gateway I want to use api-keys for authorization and grouping users for accesing the api's in API Gateway. The requests will be sent from web-page using javascript calls.

*

*Is there any way to encrypt the api-keys?

*Lets say I am able to encrypt it, will it be beneficial at all? Because someone can still see the encrypted api-keys and use it, and it will still work, because anyhow i will be decrypting it somewhere.

*Is there any better way?

A: You cannot protect your API keys for authorization when your API calls are initiated from the client (i.e., JavaScript). As you said, there will be no point of encrypting them as well. You'll need to have an authorization provider that can return the API key as part of the response.
API Gateway allows you to have custom authorizer for your API. See Output from an Amazon API Gateway Custom Authorizer.


Q: 404 depending on query string Parameters or strictly if route exists Say I had a route such as /Item/Create/ which creates a new Item but requires a mandatory parameter called GroupId. It would have to be called via /Item/Create?GroupId=xxx.
If the given GroupId doesn't exist can I return a 404 or is it wrong to return a 404 based on query string paramters?
I know it would be alright to return a 404 if my route itself was /Item/Create/{GroupId} and the GroupId was not found.

A: It's not "wrong" per se, status 404 means "Resource not found" and you can't find a resource that hasn't been specified.  Status 400 (Bad Request) however might be more appropriate.  It really comes down to the intended meaning of the error code and your interpretation of the error.
A full list of status codes can be found in section 10 of RFC 2616.  The 4xx (error) codes start in section 10.4.


Q: Using 'multiprocessing' libary in Python 3 for PostgreSQL queries I'm trying to write a Python script to read query data from my database into pandas dataframes.
I have simplified the code significantly to test the effectiveness of using the multiprocessing library in order to parallelize running the queries since running a query including all of the information I want to collect takes several minutes.
However, using Pool from multiprocessing is not the most effective. (In fact, no difference in performance occurred when running the script). Is there a more effective approach to run queries concurrently in PostgreSQL?
Any advice would be awesome!
import psycopg2
import pandas as pd
import sqlalchemy as sa
from multiprocessing import Pool

engine = sa.create_engine("<database info>")

def run_query(query):
    print(query)
    data_frame = pd.read_sql_query(query, engine)

if __name__ == '__main__':
    pool = Pool(processes=len(queries))
    pool.map(run_query, queries)

A: I dont know if it is efficient but you can use worker and producers scheme. Basically you define a multiprocessing Q and the producer process adds something into the Q. The Worker listens to the Q and starts working as soon some information is put into the Q.
Here is a good example.
http://danielhnyk.cz/python-producers-queue-consumed-by-workers/
The problem you have with Multiprocessing is that you have to take care about shared data and also the time to schedule the processes must be taken into account which makes the Multiprocessing in Python not very usable for small tasks. However, If you do that tasks very often or you create the process once and just run the tasks when there is one you get a benefit.


Q: I'm making an ASCII rpg in c++ where my character moves using arrow keys. How do i make my character the unicode smiley? I am using the '@' symbol to act as my character right now. I want to switch it to the unicode ☺ smiley.      Below is an example of an ASCII map where my character (currently '@') starts at the top left. The code works by when i hit the arrow keys, the map clears my '@' character symbol and creates it in the adjacent spot in the chosen direction. Basically, instead of my character being a '@' i want it to be a '☺'
char map[10][23] = {
"##########   #########",
"#@       #   #       #",
"#        #   #####   #",
"#        #       #   #",
"#        #########   #",
"#                    #",
"######################" };


Q: How To Populate PDF With Values From Model My django project generates a view in the form of a PDF file which uses an HTML file to outline the format.  I have a separate view which simply displays a drop down list of all the "Reference IDs" in my "Orders" model.  My goal is to choose a "Reference ID" from the dropdown, click submit, and have the PDF generate populating certain values with values from the data that corresponds to that reference ID in the Orders model.
For example, I'd like to
What I have is listed below - any help with this problem would be greatly appreciated!
Below shows code for the view generating the dropdown:
VIEWS.PY
def reference_view(request):
    query_results = Orders.objects.all()
    reference_list = DropDownMenuReferences()

    context = {
        'query_results': query_results,
        'reference_list': reference_list
    }
    return render(request, 'proforma_select.html', context)

FORMS.PY
class DropDownMenuReferences(forms.Form):
    Reference_IDs = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(),
    empty_label=None)

Proforma_select.html
{% extends 'base.html' %}

{% block body %}

  <form method=POST action="">
    {{ reference_list }}

    <button type="submit" class="btn btn-primary" name="button">Add Order</button>
  </form>

{% endblock %}

Below shows code for the PDF which is generated:
VIEWS.PY
def generate_view(request, *args, **kwargs):
    template = get_template('invoice.html')
    context = {
        "invoice_id": 123,
        "ultimate_consignee": "john cooper",

    }
    html = template.render(context)
    pdf = render_to_pdf('invoice.html', context)
    return HttpResponse(pdf, content_type='application/pdf')

INVOICE.HTML (only way I could find online to do this was with HTML 4)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <title>Proforma Invoice</title>

Proforma Invoice # {{ invoice_id }}

Customer: {{ ultimate_consignee }}

Below is the MODELS.PY for Orders Model which the dropdown menu reference IDs is created from and where I would like to pull other fields into the PDF:
MODELS.PY
class Orders(models.Model):

    reference = models.CharField(max_length=50, blank=False)
    ultimate_consignee = models.CharField(max_length=500)
    ship_to = models.CharField(max_length=500)
    vessel = models.CharField(max_length=100)
    booking_no = models.CharField(max_length=50, blank=True)
    POL = models.CharField(max_length=50)
    DOL = models.DateField()
    COO = models.CharField(max_length=50)
    POE = models.CharField(max_length=50)
    ETA = models.DateField()
    pickup_no = models.CharField(max_length=50)
    terms = models.CharField(max_length=1000)
    sales_contact = models.CharField(max_length=100)
    trucking_co = models.CharField(max_length=100)
    loading_loc = models.CharField(max_length=100)
    inspector = models.CharField(max_length=50)
    total_cases = models.IntegerField()
    total_fob = models.DecimalField(max_digits=10, decimal_places=2)
    freight_forwarder = models.CharField(max_length=100)
    commodity = models.CharField(max_length=200)
    is_airshipment = models.BooleanField(default=False)
    credit = models.DecimalField(max_digits=10, decimal_places=2)

def _str_(self):
    return self.reference

As you can see - I am current hardcoding in values to the View which then appear on the PDF - but I'd like these to pull from the Orders Model.
i.e. something like WHERE Reference ID = 100, Ultimate Consignee = John Smith

A: You have to improve your code with a couple of changes
First
Your form is not pointing to any action (Maybe you are using Js for activating the view that generates the PDF) and the easiest way to delivering the form data to the view is making the form action attribute points to the target view.
Let's say your view has an URL named generate_pdf (see Naming URL patterns) then you could in your template:
 <form method=POST action="{% url generate_pdf %}">
    {{ reference_list }}
    <button type="submit" class="btn btn-primary" name="button">Add Order</button>
 </form>

Second
... having the form pointing to your view, you can read the Reference_IDs from the post data in order to obtain the Order instance and use it:
def generate_view(request, *args, **kwargs):

    context = {}

    if request.method == 'POST':
        order_reference = self.request.POST.get('Reference_IDs')
        if order_reference is not None:
            order = Orders.objects.get(reference=order_reference)
            template = get_template('invoice.html')
            context.update({
                "ultimate_consignee": order.ultimate_consignee,
                # ...
            })
            html = template.render(context)
    pdf = render_to_pdf('invoice.html', context)
    return HttpResponse(pdf, content_type='application/pdf')

Good luck!
Note: I've not tested this, it is just an effort to show you one of the approaches you can follow to achieve what you want.


Q: Number theory to estimate lower bound of spectrum in quantum mechanics? I recently worked on the following idea:
Eigenvalue of an Euler product type operator?
Summary of the idea
We represent numbers by infinite dimensional matrices such as $3$ will have all $0$s except the $1$st row will have a $1$ in the third column, the $2$nd row will have a $1$ in the $6$th row and the $r$th row and $3r$th column also have $1$s:
$$ \hat 3  = | 1 \rangle \langle 3 | + | 2 \rangle \langle 6 | + | 3 \rangle \langle 9 | + \dots = \begin{bmatrix}
    0       &0 & 1        &0 & 0& \dots & 0 \\
    0       &0 & 0 &0       &0 & 1 & \dots & \\
    \vdots \\
    0      & 0 & 0 & \dots
\end{bmatrix}
$$
Similarly we can define $\hat 2$:
$$ \hat 2 = | 1 \rangle \langle 2 | + | 2 \rangle \langle 4 | + | 3 \rangle \langle 6 | + \dots =\begin{bmatrix}
    0       &1 & 0        &0 & 0& \dots & 0 \\
    0       &0 & 0 &1       &0 & 0 & \dots & \\
    0       &0 & 0 &0       &0 & 1 & \dots & \\
    \vdots
\end{bmatrix}
$$
One notices that these numbers obey multiplication
$$ \hat 6 = \hat 3 . \hat 2 = \hat 2 . \hat 3$$
where the $r$th row of the $6r$th column has a $1$
One can also use this to define an Euler like product formula:
$$ \hat \zeta (s) = \hat 1  + \hat 2^s + \hat 3^s + \dots = (1- \hat 2^s)^{-1}(1- \hat 3^s)^{-1}(1- \hat 5^s)^{-1} \dots$$
Note: $\zeta(1) |\lambda \rangle  = |\text{factors of } \lambda \rangle$
My Observation
Let us define the following ladder operators $a$ and $a^\dagger$ from quantum mechanics:
$$ A^\dagger|n \rangle = | n+1 \rangle$$
Now we make the following observation:
$$ \frac{A^\dagger}{\hat I- A^\dagger} \geq \hat \zeta(1) - \hat I$$
Where I is the identity or $\hat 1$. To see what $\frac{A^\dagger}{1- A^\dagger} $ looks like apply it $\hat 1$ as: $ \frac{A^\dagger}{1- A^\dagger} \hat 1$. In the sense:
$$ \langle m  |\frac{A^\dagger}{\hat I- A^\dagger} |n \rangle \geq  \langle m  |(\hat \zeta(1) - \hat I) |n \rangle $$
In fact for $n>1$:
$$ \langle m  |\frac{A^{\dagger 2}}{\hat I- A^\dagger} |n \rangle \geq  \langle m  |(\hat \zeta(1) - \hat I) |n -1 \rangle $$
Subtracting the above equations:
$$ \langle m|A^\dagger| n \rangle \geq  \langle m  |(\hat \zeta(1) - \hat I) ( |n \rangle - |n -1 \rangle) \geq  \langle m  |(\hat \zeta(1) - \hat I)  |n \rangle  $$
Question
Given a Hamiltonian can be expressed as annihilation and creation operators can the above expression be used to get some lower bounds on the difficult to compute spectrums?
$$H(a^\dagger, a) \geq H'(\hat \zeta,\hat \zeta^\dagger) $$


Q: How to you solve the problem of implicit locking and parallel execution? Where the code is:
function A()
{
    lock()
    doSomething()
    unlock()
}

We can call A safely from multiple threads, but it never be executed in parallel . For parallel execution, we have to evade all of this code.
But the problem is we never know the A is getting lock or not. If we have source code (maybe lucky case), we have to decode all code to know locking is happening or not. This sucks. But even worse is we normally have no source code. And about the case of the lock is exist on base library?
It's obvious this kind of hidden locks will become bottleneck of parallel execution even all the other parts are designed for parallel.
And also, (1) With locks, execution cannot be parallel. (2) And I can't know whether the locks are used or not in any code. (3) Defensively saying, I can't make parallel anything!
This facts drives me crazy. How do you solve this problem?

A: First, A is not locked but rather threads become locked at the call of "lock()".  There's no hidden locking mechanism here.  A simple check is done which verifies that no other thread is currently holding the lock.  If it is locked, it waits until it is unlocked, otherwise it continues executing the code.
You're right that generally speaking, locking code should be avoided unless absolutely necessary and when you do lock, it must hold a lock for as little time as possible to avoid potential bottlenecks.  A good rule of thumb for knowing when code should be locked is to ask yourself the following questions:

*

*At any step in this process, would I care if it got interrupted?  (imagine the power to the computer failing and not all your code gets executed.. would it be a problem?)

*If my program kept re-executing code due to some processor error, local variables aside, would there be some sort of risk of tampering with the end result in the previous execution?

If you answer yes to either, congratulations!  You've found code you need to lock.
Typically there are two types of locks:  read and write locks.  If you just see "lock()" and "unlock()", what you're seeing is a write lock.  A write lock is the most severe form of lock and it blocks threads regardless of what you're executing.  Sometimes you may not even need to perform an operation, just simply check to see if you need to, yet you don't want to read data that may have since been modified by another thread, so you have to keep it in a lock.  For this, you need a read lock.  Read locks are always used in combination with a write lock.  Typically you see a read lock immediately and some sort of check.  If the check passes, you place a write lock to ensure that no thread can enter the read lock section until you're sure that it is in a consistent state.
If you write it correctly, you need not know whether or not a thread is locked just like you don't know when writing to a file will cause a program to block while it's being used by another program.
If that didn't answer your question, then perhaps I didn't quite follow what you were asking.

A: If you call A concurrently from multiple threads, one of three things will happen:
1) The threads will not actually block each other because they won't try to acquire the lock at the same time. In this case, they will still run concurrently and there will be no problem.
2) The threads will conflict on the lock and one of the threads will no longer be ready to run. In this case, the operating system will schedule some other thread that doesn't require that lock, in which case those threads will still run concurrently and there will be no problem.
3) Once all the threads that don't need the lock are scheduled, there are still idle cores. Only a thread that requires the lock can be scheduled on that core. But this only happens when everything you need to do required calling that function.
In other words, you only need to worry about this in the 5%-10% of your code that's performance critical. And you have to know that code inside out anyway, for obvious reasons.

A:
It's obvious this kind of hidden locks will become bottleneck of parallel execution even all the other parts are designed for parallel.

False.  All false.

(1) With locks, execution cannot be parallel.

In a one-core machine nothing is actually parallel, instruction streams from two or more threads are interleaved.
On a two-core machine, then you have exactly two parallel, interleaved instruction streams for all the running threads.
Cores are the only actual parallel execution.  Threads are interleaved.
The threads appear to be executing in parallel.

(2) And I can't know whether the locks are used or not in any code.

What?

(3) Defensively, I can't make parallel anything!

False.


Q: Keras - Compile model when using theano backend (K.function) to calculate loss I am building an NN in Keras and I am using Theano backend.
Code:
    cost = ((pred - target)**2).mean()
    opt = RMSprop(lr = self.lr, rho = self.rho, epsilon = self.rms_epsilon)
    #model -> keras nn
    params = self.model.trainable_weights
    updates = opt.get_updates(params, [], cost)

    self.model.compile(optimizer = opt,loss='mse')

    self._train = K.function([S, NS, A, R, T], cost, updates=updates)

If I compile this model using the above-mentioned parameters and save it, will the loaded model preserve the training configuration (loss,optim.)?
Since I use the K.function(...) method to calculate cost(loss), will this affect the model's configuration in any way?
So far I have not been able to figure out a way to check whether the resumed model's config is same as the saved one.
So, is there a way to print out the network configuration to check if it has been properly restored i.e. with the exact same config and param it was saved with?


Q: Passwords and Keys in Linux In a fit of desperation when I had my wireless connection die on me, I thought it was a problem with the key I had created at the start when I initially configured the wireless connection and hence deleted it. The option to create the key had presented itself when I created the wireless connection. It no longer asks me to.
Now I am back online, do I have re-create the password and key I had before? If so, what do I choose and why? The options I have are as follows;

*

*PGP

*Stored password

*Password keyring

*Secure shell key

The first and last option seem to be obvious and I have no idea about the differences between the second and third options.
Why do I need a stored password or password keyring in all scenarios and not just the wireless issue I ran into?
EDIT 0
Further to Belisama's comment, I have amended my question.
EDIT 1
As requested, I have attached a screenshot

A: The "password keyring" one is if you have an app that requires security, so you can give it a password, the password will be added to the "keyring" and you unlock all of the passwords on the "Keyring" by typing a password into the dialog box after you've logged into the system. That's how I understand it, anyway.
In brief: "for convenience"


Q: Entity saving to database wrong date format codeigniter 4 My entity looks like this:
class Request extends Entity
{
    protected $casts = [
        'id'                => 'integer',
        'added_at'          => 'datetime',
        'deadline'          => 'datetime',
        'completed'         => 'integer'
    ];
}

When saving, the model generates the date fields in 'Y/m/d' format for the sql query, hovewer my database can not parse this. How can I force it to generate dates in 'Y-m-d' format when calling $myModel->insert($myEntity) ?

A: Entities has the option of setters. It performs the validation or conversion in your case whenever you perform save an entity. Lets say you want to change the form of deadline in that case you have to set the Setter for your deadline as follow :
public function setDeadline(string $dateString)
{
    $this->attributes['deadline'] = $dateString;

    return $this;
}

In the following line : $this->attributes['deadline'] = $dateString; You will use some library like Carbon to format the $dateString and then reassign your variable deadline. Reference link :
https://codeigniter4.github.io/userguide/models/entities.html


Q: Determining whether each row has the highest value within the group specified in another column We want to find the row with highest priority.
We have about 30,000 rows of data in a Table like this:
Item  Group  Priority  Highest(formula wanted)
A                              TRUE
B     P           2.2          TRUE
C     P             1          FALSE
D                              TRUE
E     Q             2          FALSE
F     Q             4          TRUE
G     Q             1          FALSE

(Note: a priority is present if and only if there is a group. No tie exists in our data.)
The column Highest is TRUE if the row has no Group, or within the same group it has the highest priority. In the example above, Item C belongs to Group P but is not of the highest priority. Items E and G are of Group Q but don't have highest priority.
I have tried the following array formula (also seen here):
=IF([@Group]="",TRUE,MAX(([Group]=[@Group])*[Priority]))
However, for some reason we do not accept array formula. Sorting is also not accepted as the original ordering is important in other calculations. Then, how can we set the formula?

A: =OR([@Group]="",LOOKUP(1,0/FREQUENCY(0,1/(1+([Group]=[@Group])*[Priority])),[Priority])=[@Priority])
On a side, I am very interested in knowing your reason for not allowing array formulas. Would you mind sharing it?
Regards


Q: Python - How to start Y axis at 0 import pandas as pd
import matplotlib.pyplot as plt

pd.options.display.max_rows = 100
pd.set_option('display.max_columns', None)

western_counties = pd.read_csv('2018_governor_results_western_ny_dem.csv')

df = pd.DataFrame(western_counties)
X = list(df.iloc[:, 0])
Y = list(df.iloc[:, 1])

plt.bar(X, Y, color='g')
plt.title('Region 1 - Western New York')
plt.xlabel('x')
plt.ylabel('y')
plt.ylim(ymin=0)

plt.show()

I am getting the following chart. As you can see the first "bar" starts at its value (3254). I want this to actually show the green bar, which means Y axis needs to be set to zero. Any help is appreciated.

A: Matplotlib doc says to use ylim(bottom=0) instead of ylim(ymin=0)
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ylim.html#
you could also just say plt.ylim([0,162772])


Q: DJANGO importing fields to model from another model I have the following Models and I'm try to get the vector in Especie.zonas to be a field in the model Zona.
i.e. Especie.zonas is a vector of Zonas (model Zona) and I want it to have a OneToOne relationship with the model EspecieZona
Models.py
class Zona(models.Model):
    codigo          = models.CharField(max_length=120)
    area            = models.CharField(max_length=120)
    especies        = models.ManyToManyField("Especie", blank=True)

        def __str__(self):
            return self.codigo
        def get_especies(self):
            return self.especies.all().values_list('nome', flat=True)

    class Especie(models.Model):
        nome            = models.CharField(max_length=120)
        nome_latino     = models.CharField(max_length=120)
        data_insercao   = models.DateTimeField(auto_now_add=True)
        actualizacao    = models.DateTimeField(auto_now=True)
        zonas           = models.ManyToManyField("Zona",blank=True )

        def get_zonas(self):
            return self.zonas.all().values_list('codigo', flat=True)
        def __str__(self):
            return self.nome

    class EspecieZona(models.Model):
        idEspecie          = models.OneToOneField("Especie")
        here_is_my_problem = models.Especie.zonas()
        idZona             = models.OneToOneField("Especie.zonas")
        fechado            = models.BooleanField()
        def __str__(self):
            return str(self.idEspecie)+' em '+str(self.idZona)

Thanks in advance!

A: I'm not entirely sure of your intent. Relationships are to be established between models (so you can't OneToOne to a class' field). As I understand EspecieZona relates one Especie instance to one Zona instance, but you also would like to easily get all the Zona instances related to some Especie instance that you are accessing through EspecieZona.
It seems to me like you should drop that here_is_my_problem field entirely and use foreign keys to Especie and Zona in EspecieZona, instead of OneToOne. With the foreign keys you can use a ManyToMany field from Zona to Especie (or vice versa. you have to declare the MtM field in only one side of the relationship, whichever makes more sense to you) and use EspecieZona as a 'through' field for that relationship (probably with a unique_together constraint for Especie and Zona). That way you can establish a relationship like this:
"Each species can be on multiple zones, and each zone can have multiple species (described by the MtM relationship). Additionally, for each zone and species found in them, each species might or not have been recorded(?) in that zone (described in the 'through' model, EspecieZona, thou not sure I understand the meaning of fechado here. In any case, a 'through' model lets you describe whatever details about the relationship between two models)".
Then, in order to retrieve Especies.zonas from an instance of EspecieZona you can do someSpecificEspecieZona.especie.zonas.all() (assuming zonas
 is declared as a MtM field in Especie), which would get you all the zones that are related to that species (as I understand your models)
I suggest reading through the documentation of relationship fields https://docs.djangoproject.com/en/1.11/ref/models/fields/#module-django.db.models.fields.related so you get the details about how it all works, like how to use a  ManyToManyField.through, and perhaps about reverse relationships if you need them.
(also, maybe that was just a mistake when copypasting your code here, but the indentation looks wrong. Different models should be at the same level of indentation there)


Q: How to run bash file for (different directory) as input automatically I have a bash file which takes 5 inputs.
Input1 = file1
Input2 = file2
Input3 = directory1
Input4 = func
Input5 = 50

input 4 and 5 are always the same, never change.
file1 and file 2 are located inside directory1
directory1 is located inside a code directory
/code/directory1/file1
/code/directory1/file2

and there are many directories with the same structure directory(1-70) inside the code folder
/code/directory1/*
/code/directory2/*
/code/directory3/*
...
/code/directory70/*

In order to run the bash file, I have to run the command from terminal 70 times :<
Is there a way to automatically run all these folders at once?
UPDATE: the directory(1-7) each one has a different name e.g bug1, test, 4-A and so on. Even the files are different e.g. bug1.c hash.c
/code/bug1/bug1.c
code/bug1/hash.c

A: Try this:
for dirs in $(ls -F /code | grep '/')
do
    eval files=( "$(ls -1 ${dirs})" )
    <ShellScript>.sh "${dirs}${files[0]}" "${dirs}${files[1]}" "${dirs%/}" func 50
done


Q: Generic template template parameters Fed up with "uniform initialisation" not being very uniform, I decided to write a generic construct() wrapper which uses aggregate initialisation if a type is an aggregate, and direct initialisation otherwise:
template <class T, class... Args,
          std::enable_if_t<std::is_aggregate_v<T>, int> = 0>
constexpr auto construct(Args&&... args)
    -> decltype(T{std::forward<Args>(args)...})
{
    return T{std::forward<Args>(args)...};
}

template <class T, class... Args>
constexpr auto construct(Args&&... args)
   -> decltype(T(std::forward<Args>(args)...))
{
    return T(std::forward<Args>(args)...);
}

This works well enough:
template <class T, class U>
struct my_pair { T first; U second; };

auto p = construct<my_pair<int, float>>(1, 3.14f);
auto v = construct<std::vector<int>>(5, 0);

I'd like to extend this to use template argument deduction for constructors. So I added another pair of overloads:
template <template <class...> class T, // <-- (1)
          class... Args,
          class A = decltype(T{std::declval<Args>()...}),
          std::enable_if_t<std::is_aggregate_v<A>, int> = 0>
constexpr auto construct(Args&&... args)
    -> decltype(T{std::forward<Args>(args)...})
{
     return T{std::forward<Args>(args)...};
}

template <template <class...> class T, // <-- (1)
          class... Args>
constexpr auto construct(Args&&... args)
    -> decltype(T(std::forward<Args>(args)...))
{
    return T(std::forward<Args>(args)...);
}

Perhaps surprisingly (at least to me), this works for simple cases:
// deduction guide for my_pair
template <class T, class U> my_pair(T&&, U&&) -> my_pair<T, U>;

auto p = construct<my_pair>(1, 3.14f); // my_pair<int, float>
auto v = construct<std::vector>(5, 0); // vector of 5 ints

Unfortunately however this fails when trying to call
auto a = construct<std::array>(1, 2, 3); // No matching call to construct()

because std::array has a non-type template parameter, so it doesn't match the template <class...> class T template template parameter at (1).
So my question is, is there a way to formulate the parameter at (1) such that it can accept any class template name, regardless of the kind (type or non-type) of its template parameters?

A: Unfortunately, there is no proper way of doing this without code repetition. The newly added "auto as template parameter" in C++17 only supports non-type template parameters.
The only way I can think this could work is by using a code generator to generate a fixed amount of permutations of auto and class. E.g.
template <
    template <class, auto...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <class, auto, class...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <auto, class, auto...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <auto, class, auto, class...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

template <
    template <auto, class, auto, class, auto...> class T,
    class... Args>
constexpr auto construct(Args&&... args) // ...

// and so on...

live example on wandbox
Sounds like you have a good idea for a proposal...


Q: Implement messaging into website I have a website where I have registered users in the system. When user logs into his profile I have section "Messages".
What is the best way to implement messaging into the website? I don't want to use plug-ins with live chat because of the pop-up boxes. I just want when one user will send a message to another, to have notification for new message, and to be able to start conversation between two sides in the real time.
I have an idea how to implement this with ajax, but I don't think it's a good idea to check for a new messages every a few seconds. Is there some better way to listening for a new messages and for implementing messaging feature in the site?

A: A websocket is what you are looking for; however it is subject to some browser limitations and libraries may fall back to polling with Ajax if the browser doesn't support it.
Here is some reading for you so you can ask a more specific question in the future:

*

*http://en.wikipedia.org/wiki/WebSocket (general info)

*http://socket.io/ (NodeJS and browser client library)


Q: How does shell expands *.c? I encounter a question while I am reading a textbook - Unix System Programming

How big is the argument array passed as the second argument to execvp
  when you execute execcmd of Program 3.5 with the following command
  line?
execcmd ls -l *.c

Answer: The answer depends on the number of .c files in the current
  directory because the shell expands *.c before passing the command
  line to execcmd.

Program 3.5:
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "restart.h"
int main(int argc, char *argv[]) {
   pid_t childpid;
   if (argc < 2){     /* check for valid number of command-line arguments */
      fprintf (stderr, "Usage: %s command arg1 arg2 ...\n", argv[0]);
      return 1;
   }
   childpid = fork();
   if (childpid == -1) {
      perror("Failed to fork");
      return 1;
   }
   if (childpid == 0) {
      execvp(argv[1], &argv[1]);
      perror("Child failed to execvp the command");
      return 1;
   }
   if (childpid != r_wait(NULL)) {
      perror("Parent failed to wait");
      return 1;
   }
   return 0;
}

Why is the size of argument array passed depending on the number of .c files in the current directory? Isn't it the argument array just something like
argv[0] = "execcmd";
argv[1] = "ls";
argv[2] = "-l";
argv[3] = "*.c";
argv[4] = NULL;

Update: Find a link explains pretty well about the shell expansion. May useful for someone who see this post later also do not understand shell expansion.
Description about shell expansion

A: No, because the shell does the wild card expansion.
It finds files in the directory that match the expression, so for instance you can use "echo *.c" to discover what the shell would match.  Then it lists out, every filename matching *.c on the exec call or if none *.c which is likely to result in an error message about file not found.
It is more powerful that the shell does the expansion, the same file wildcarding is immediately available for all programs, like cat, echo, ls, cc.


Q: Nested Params in Spring Controllers is asking for Neting in JSP file Path. How to deal with that? So this is my controller code :
`
package org.inventorymanagement.controller;

import org.inventorymanagement.databaseservice.BorrowBookDatabaseService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BorrowPageController {

    @RequestMapping(value = "/borrow/{bookName}/{issuerName}", method = RequestMethod.GET)
    public ModelAndView searchForBookName(@PathVariable("bookName") String bookName, @PathVariable("issuerName") String issuerName) {
        ModelAndView mav = new ModelAndView("borrow.jsp");
        String rs = (String) new BorrowBookDatabaseService().borrowBookFromBookTable(bookName, issuerName);

        return mav;
    }

}

Here is the error which i am seeing on my webpage:
JSP file [/borrow/ABC/borrow.jsp] not found
ABC is my bookName.
Any suggestions how can i overcome it ?
I tried to change the path of jsp inside ABC folder and it works fine. But since ABC is generic how many folders i will made ?


Q: Advantages of Maven Tycho over Eclipse PDE Tools for exporting RCP In the light of some recent issues regarding JavaFX and exporting an Eclipse RCP application, I'm considering abandoning the Eclipse PDE exporter, and switching to a Tycho build.

*

*Which approach is simpler, and which is over-complicated? Do I need to constantly tweak the Tycho build configuration?

*Current project is already using ant scripts to build a core EAR. Should that be built with Maven to be consistent?

*I'm aware of some issues between Maven and Eclipse Plug-ins. Is there anything critical I should be worried about?
I'm in heavy R&D mode.
Also, I don't consider this to be opinion-based, rather a topic asking for strong arguments in favour of each one of these two.

A: I wouldn't say one of them is much simpler then the other. Most often Tycho is preferred since Maven is de facto an industry standard for builds. As such Maven skills are more common. This also allows you to build an RCP product like any other application using Maven.
In Maven/Tycho both the pom.xml and the OSGi manifest include dependency information so there's a bit of redundancy. The idea is to have one of these files be the master version. If you choose OSGi files to be master then resulting approach is called manifest-first. Choose otherwise and you end up with POM-first.
I'm using manifest-first and my POM files for plugins look like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>aerie-sdk</groupId>
      <artifactId>aerie-sdk</artifactId>
      <version>3.0.5-SNAPSHOT</version>
      <relativePath>../pom.xml</relativePath>
   </parent>
   <groupId>aerie-sdk</groupId>
   <artifactId>com.example.aerie.ui</artifactId>
   <version>2.5.5-SNAPSHOT</version>
   <packaging>eclipse-plugin</packaging>
</project>

I only need to bump versions in POM files to match the ones in manifest files.
Answers:

*

*I'd say the one you're more familiar with is simpler. If you're new to Maven but have some experience with PDE build then Maven is harder. For Maven POM-first there's a need to tweak POM files quite often. If you choose manifest-first then POMs are not modified that frequently (and changes are simpler - mostly version changes).

*You can run Ant from Maven, no need to convert.

*Not really. If you hit any bumps there's a lot of information on Eclipse community forums, stackoverflow or similar sites.

A: I'm not sure your comparison makes sense at all. The Eclipse PDE exporter is an interactive tool, and as such cannot be used for an automated build. So if you need an automated build, you will have move to something else, e.g. Tycho.
Tycho is a Maven build extension which aims to make it easy to set up an automated build for projects developed with the Eclipse PDE. It re-uses the configuration files that you already have (MANIFEST.MF, feature.xml, *.product), so the additional configuration files needed for Tycho (pom.xml) are pretty minimal and rarely need to be updated.
The only piece of information which is redundant in the pom.xml file is the artifact version. To support you when updating artifact versions, there is a command-line tool: the tycho-versions-plugin.


Q: correct word for "proving a prediction false"? Which word should I use to say that " A is trying to prove B's prediction wrong"?
For example, in the recent United Nations water scarcity report, UN predicted that in 10 years from now, two-thirds of the world population will be facing severe fresh water scarcity problem. We people have to prove that UN's prediction is wrong (of course, one has to wait for 10 years to see whether the prediction became true or not).
Before that, what word should I use in the below context?

To disprove the UN's prediction, we have to build desalination
  plants.

or

To prevent the UN's prediction, we have to ....

or

To invalidate the UN's prediction, we have to ...

or please suggest a better word(s).
click here for word reference.

A: You could try refute:-

*

*To prove to be false or erroneous; overthrow by argument or proof [American Heritage Dictionary via the Free Dictionary]

although the force of this word is somewhat diluted due its to the common use to mean deny. You would say, "we refuted the prediction by experiment xyz".

A: This question is confusing and appears to be asking for two different things. The text appears to be asking for wording that shows people are attempting to show that the original prediction was wrong but the examples appear to be saying that if the prediction is accepted then what term describes the actions taken as a result. I have chosen to answer the latter.
'Mitigate' can be used in this context:

verb (used with object), mitigated, mitigating.
1 - to lessen in force or intensity, as wrath, grief, harshness, or pain; moderate.
2 - to make less severe: to mitigate a punishment.

For example:
To mitigate the UN's prediction, we have to build desalination plants.
To mitigate the UN's prediction, we have to....

A: Falsify - to demonstrate a theory to be false.

A: preempt:

to prevent (something) from happening

A: Although not an exact fit, I think forestall is best here. Strictly speaking, it is the predicted water shortage that you are forestalling, and not the prediction itself; but I think the meaning is clear.


Q: What is going on in this log file? I'm a server n00b, running a website off a Windows 2012 r2 server.  My website has slowed to a crawl, so I started looking through some log files in C:\inetpub\logs\LogFiles and I started seeing a bunch of this:
2018-03-05 05:21:34 MyIPAddress GET /Dates.aspx U=878 80 - 162.158.79.99 Mozilla/5.0+(compatible;+bingbot/2.0;++http://www.bing.com/bingbot.htm) - 200 0 1236 86200
2018-03-05 05:25:50 MyIPAddress GET /Dates.aspx U=895 80 - 172.69.70.69 Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html) - 200 0 1236 85069
2018-03-05 05:27:17 MyIPAddress GET /robots.txt - 80 - 141.101.97.124 Mozilla/5.0+(compatible;+SeznamBot/3.2;++http://napoveda.seznam.cz/en/seznambot-intro/) - 404 0 2 657
2018-03-05 05:27:36 MyIPAddress GET /ImageCSharpThumb.aspx FileName=855_20180206121628_2012-09-02+KS+Knuckleheads.jpg 80 - 172.68.215.128 Mozilla/5.0+(compatible;+SeznamBot/3.2;++http://napoveda.seznam.cz/en/seznambot-intro/) - 200 0 0 666
2018-03-05 05:28:35 MyIPAddress GET /Dates.aspx U=269 80 - 141.101.97.121 Mozilla/5.0+(compatible;+SeznamBot/3.2;++http://napoveda.seznam.cz/en/seznambot-intro/) - 200 0 64 45704
2018-03-05 05:37:47 MyIPAddress GET /robots.txt - 80 - 172.69.70.213 Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html) - 404 0 2 2460
2018-03-05 05:37:51 MyIPAddress GET /ads.txt - 80 - 172.69.69.80 Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html) - 404 0 2 503
2018-03-05 05:38:03 MyIPAddress GET /favicon.ico - 80 - 108.162.215.128 Mozilla/5.0+(Macintosh;+Intel+Mac+OS+X+10_7_0)+AppleWebKit/535.11+(KHTML,+like+Gecko)+Chrome/17.0.963.56+Safari/535.11 - 304 0 0 6620
2018-03-05 05:38:20 MyIPAddress GET /ogPipe.aspx name=http://www.dongtaiwang.com/ 80 - 172.68.211.224 Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/55.0.2883.87+Safari/537.36 - 404 0 1236 10958
Can someone tell me what the hackers are trying to do, and if there's any way to defend it?  My server is completely unusable, my IP told me whatever is going on is using 100% of my allotted upload bandwidth.


Q: UserForm ComboBox with searchable list to not select first item with keyDown Background
I have a UserForm with a ComboBox (ComboBox1) that includes a searchable list (thanks to the code). However, when I use the down button, it just selects the first item and gets rid of the rest of the list that was there first (like as if basically puts the first item as the searched name).
I have found a very similar question on stack overflow but the solution did not fully work for me.
Here is the link: How use the combobox keydown event without selecting the listed item
The code that I have for my UserForm is below:
Dim a()

Private Sub CommandButton2_Click()

End Sub

Private Sub UserForm_Initialize()
  a = [Liste].Value
  Me.ComboBox1.List = a
End Sub
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Abort As Boolean
    Select Case KeyCode
        Case 38  'Up
            If ComboBox1.ListIndex <= 0 Then KeyCode = 0 'ignore "Up" press if already on the first selection, or if not on a selection
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection past the first entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox.ListIndex - 1
            End If
            Me.ComboBox1.DropDown
        Case 40 'Down
            If ComboBox1.ListIndex = ComboBox1.ListCount - 1 Then KeyCode = 0
        ' This method was from the discussion I linked, prevents "falling off the bottom of the list"
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection before the last entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox1.ListIndex + 1
            End If
            Me.ComboBox1.DropDown
    End Select
    Abort = False
End Sub

Private Sub ComboBox1_Change()
If Abort Then Exit Sub ' Stop Event code if flag set
    Abort = True
    ' sets the flag until finished with commands to prevent changes made by code triggering the event multiple times
Set d1 = CreateObject("Scripting.Dictionary")
    tmp = UCase(Me.ComboBox1) & "*"
    For Each c In a
        If UCase(c) Like tmp Then d1(c) = ""
    Next c
    Me.ComboBox1.List = d1.keys
    Me.ComboBox1.DropDown
Abort = False
End Sub

Private Sub CommandButton1_Click()
  ActiveCell = Me.ComboBox1
  Unload Me
End Sub

Private Sub cmdClose_Click()
  Unload Me
End Sub

The particular section that is apparently trying to stop the comboBox from selecting the first item is this:
Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Abort As Boolean
    Select Case KeyCode
        Case 38  'Up
            If ComboBox1.ListIndex <= 0 Then KeyCode = 0 'ignore "Up" press if already on the first selection, or if not on a selection
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection past the first entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox.ListIndex - 1
            End If
            Me.ComboBox1.DropDown
        Case 40 'Down
            If ComboBox1.ListIndex = ComboBox1.ListCount - 1 Then KeyCode = 0
        ' This method was from the discussion I linked, prevents "falling off the bottom of the list"
            Abort = True
            If Not KeyCode = 0 Then ' If on a selection before the last entry
                KeyCode = 0
            'Manually choose next entry, cancel key press
                ComboBox1.ListIndex = ComboBox1.ListIndex + 1
            End If
            Me.ComboBox1.DropDown
    End Select
    Abort = False
End Sub

However, when I enter something (Let's say I enter "App" to find "Applesauce" and the dropdown list shows both "Apple" and "Applesauce") and click the down button, it just goes to the first item and does not move anymore. The list does not disappear but it just gets stuck on the first item.
Does anyone have any idea what I need to change in my code to make it work? (Or any other ideas on how to make it work in general)?
GIF for clarification:
KeyDown not moving beyong first item


Q: Two different approaches to estimating a homography matrix I've been using the following reference to compute a homography given set of N>=4 points.
https://cseweb.ucsd.edu/classes/wi07/cse252a/homography_estimation/homography_estimation.pdf
The approach is to construct a homogenous system of equations of the form $Ah = 0$ and solve it using SVD. $h$ is a 9 element vector containing the entries of the homography matrix.
Here's how this article constructs the $A$ matrix. Note the terms $a_x$ and $a_y$
Link to image 1
Now there's another article that attempts to solve for the homography matrix in the same way.
http://www.robots.ox.ac.uk/%7Evgg/presentations/bmvc97/criminispaper/node3.html
However, their $A$ matrix is the negative of the $A$ matrix from the first article.
Link to image 2
Question: Why are there two different formulations of the $A$ matrix? They yield two different homographies.
(Sorry for not embedding images, don't have enough rep)
Thanks!

A: The resulting systems of equations are equivalent, since
$$
Ah = 0 \iff (-A)h=0.
$$
Let $A=U_1\Sigma_1 V_1^{\top}$ and $-A=U_2\Sigma_2 V_2^{\top}$ be SVDs of $A$ and $-A$, respectively. The homogeneous least-squares solution $h$ is obtained as the rightmost column in either $V_1$ or $V_2$. Depending on the particular SVD implementation, the results may either be equal or differ by a minus sign. Since the homography matrix is only determined up to a scalar multiple anyway, this possible minus sign does not matter.


Q: How to compute this double integral in r? I'm wanting to compute an integral of the following density function :

Using the packages "rmutil" and "psych" in R , i tried :
X=c(8,1,2,3)

Y=c(5,2,4,6)

correlation=cov(X,Y)/(SD(X)*SD(Y))

bvtnorm <- function(x, y, mu_x = mean(X), mu_y = mean(Y), sigma_x = SD(X), sigma_y = SD(Y), rho = correlation) {
  force(x)
  force(y)
  function(x, y)
    1 / (2 * pi * sigma_x * sigma_y * sqrt(1 - rho ^ 2)) *
    exp(- 1 / (2 * (1 - rho ^ 2)) * ((x - mu_x) / sigma_x) ^ 2 +
          ((y - mu_y) / sigma_y) ^ 2 - 2 * rho * (x - mu_x) * (y - mu_y) /
          (sigma_x * sigma_y))
}

f2 <- bvtnorm(x, y)

print("sum_double_integral :")

integral_1=int2(f2, a=c(-Inf,-Inf), b=c(Inf,Inf)) # should normaly give 1

print(integral_1)  # gives Nan

The problem :
This integral should give 1 , but it gives Nan ??
I don't know how can i fix the problem , i tried to force() x and y variables without success.

A: You were missing a pair of parentheses. The corrected code looks like:
library(rmutil)
X=c(8,1,2,3)

Y=c(5,2,4,6)

correlation=cor(X,Y)

bvtnorm <- function(x, y, mu_x = mean(X), mu_y = mean(Y), sigma_x = sd(X), sigma_y = sd(Y), rho = correlation) {

  function(x, y)
    1 / (2 * pi * sigma_x * sigma_y * sqrt(1 - rho ^ 2)) *
    exp(- 1 / (2 * (1 - rho ^ 2)) * (((x - mu_x) / sigma_x) ^ 2 +
          ((y - mu_y) / sigma_y) ^ 2 - 2 * rho * (x - mu_x) * (y - mu_y) /
          (sigma_x * sigma_y)))
}

f2 <- bvtnorm(x, y)

print("sum_double_integral :")

integral_1=int2(f2, a=c(-Inf,-Inf), b=c(Inf,Inf)) # should normaly give 1

print(integral_1)  # prints 1.000047

This was hard to spot. From a debugging point of view, I found it helpful to first integrate over a finite domain. Trying it with things like first [-1,1] and then [-2,2] (on both axes) showed that the integrals were blowing up rather than converging. After that, I looked at the grouping even more carefully.
I also cleaned up the code a bit. I dropped SD in favor of sd since I don't see the motivation in importing the package psych just to make the code less readable (less flippantly, dropping psych from the question makes it easier for others to reproduce. There is no good reason to include a package which isn't be used in any essential way). I also dropped the force() which was doing nothing and used the built-in function cor for calculating the correlation.


Q: Return a custom response body directly from Apache Is it possible to configure Apache to return content directly at a particular location? Without actually creating a file anywhere with that contents. Something like:
<location /custom-location.txt>
    <responsebody>hello world!</responsebody>
</location>

A: As far as I know you only have that option for error messages i.e.:
ErrorDocument 404 "Sorry but the requested resource can't be found."


Q: Centering MenuItems in second ActionBar? So I am trying to center my icons like this image from Google Developer:

My second row is actually just below the top row (which is also actionbar tabs without a title or icon enabled in the activity). So, right now, as I've added in my three buttons (just text, no icons) they stack on the right side of the bar, and I can't seem to find anything in the docs about centering. Any ideas?
Relevant code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_demos"
          android:title="Chart +/-"
          android:showAsAction="always|withText" />
    <item android:id="@+id/menu_data"
          android:title="Datas"
          android:showAsAction="always|withText" />
    <item android:id="@+id/menu_reset"
          android:title="Reset"
          android:showAsAction="always|withText" />
</menu>

manifest line:
<activity android:name="polling.Chart" android:label="Chart"
        android:icon="@drawable/chart512"     android:windowSoftInputMode="stateHidden"/>

Main Activity:
    bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    bar.setDisplayShowTitleEnabled(false);
    bar.setDisplayShowHomeEnabled(false);

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.chartsmenu, menu);
    return true;
}

A: Use the split action bar option. All items which does not fix in the top action bar will be shown in the second action bar at the bottom of your screen. The remaining items will be centered within the second action bar.
protected void onCreate(final Bundle savedInstanceState) {
    getSherlock().setUiOptions(ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW);
    super.onCreate(savedInstanceState);
}


Q: Running an interactive shellscript using java I am writing a javacode to call a interactive shellscript and using process builder for calling shellscript. I know that to pass parameters to this shell script i have to take its inputstream to check it's output and need to use output stream to pass command to it. My question is that how would I know using Input Stream that it's  prompting for entering values ?
My code :
  ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh","--ip="+formobj.getUpFile().getFileName(),"--seqs="+seqs);

        script_exec = pb2.start();

                OutputStream in = script_exec.getOutputStream();

                InputStreamReader rd=new InputStreamReader(script_exec.getInputStream());

                pb2.redirectError();

                BufferedReader reader1 =new BufferedReader(new InputStreamReader(script_exec.getInputStream()));

                StringBuffer out=new StringBuffer();

                String output_line = "";

                  while ((output_line = reader1.readLine())!= null)
                  {
                           out=out.append(output_line+"/n");
                           System.out.println("val of output_line"+output_line);

                           //---> i need code here to check that whether script is prompting for taking input ,so i can pass it values using output stream

                  }

Is there any  way to know directly that script is waiting for an input from user?

A: Read the process output stream and check for the input prompt, if you know the input prompt, then put the values to process inupt stream.
Otherwise you have no way to check.
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
BufferedReader b1 = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter w1 = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String line = "";
String outp = "";
while ((line = b1.readLine()) != null) {
  if (line.equals("PLEASE INPUT THE VALUE:")) {
     // output to stream
     w1.write("42");
  }
  outp += line + "\n";
}

...

UPD: for your code it should be something like that
    ProcessBuilder pb2=new ProcessBuilder("/home/ahijeet/sample1.sh","--ip="+formobj.getUpFile().getFileName(),"--seqs="+seqs);

    script_exec = pb2.start();

            OutputStream in = script_exec.getOutputStream();

            InputStreamReader rd=new InputStreamReader(script_exec.getInputStream());

            pb2.redirectError();

            BufferedReader reader1 =new BufferedReader(new InputStreamReader(script_exec.getInputStream()));

            StringBuffer out=new StringBuffer();

            String output_line = "";

              while ((output_line = reader1.readLine())!= null)
              {
                       out=out.append(output_line+"/n");
                       System.out.println("val of output_line"+output_line);

                       //---> i need code here to check that whether script is prompting for taking input ,so i can pass it values using output stream
                       if (output_line.equals("PLEASE INPUT THE VALUE:")) {
                           // output to stream
                           in.write("42");
                       }

              }


Q: Voltage dividers value signification Which is the difference between doing a voltage dividers from 5V to 3.3V with 10k and 20k resistors vs 4.7k and 2.4k?
It s easier to use the first option.

A: It's usually easier to do it using resistors you have. If you do it with resistors you don't have, it will take an extra day or so for them to arrive.
As you have correctly noticed, any two resistors should have the correct ratio for the voltage division. However ...
The smallest resistor \$R_{min}\$you can use is governed by
a) the driving current available at the source
The largest resistors \$R_{max}\$you can use are governed by
a) the resistive load you have to drive
b) and how fast you have to drive changes through any stray capacity it has
If you are lucky, then \$R_{min}\$>\$R_{min}\$, and there are some solutions available. This is usually the case with op-amps and CMOS gates in all combinations. This sometimes isn't the case with very weak sources, or heavy loads, and then you have to use something other than a voltage divider.

A: Most of the time, a voltage divider is made with a load. The value of that load will greatly impact the choice of the resistor value. The second thing to think about is the current you want to use for that voltage devider.
Most of the time, IC's input are consider as infinite load. That mean you can use the value of resistor you want. An infinite resistor in parallel is consider as a dead branch (due to the very low amount of current passing through)


Q: How can I save a variable from a database and use it in C#? I am changing a program and I need some help because I don't know C#. I change things with:
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=385";
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();

There is a case where I need to find an ID, store it and then use it again. So I use select
 OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
 OleDbDataReader reader = cmd.ExecuteReader();
 if (reader.HasRows)
 {
   reader.Read();
   var result = reader.GetInt32(0);
 }

 strSQL = "UPDATE materials SET ";
 strSQL = strSQL + "Dscr = 'concrete', ";
 strSQL = strSQL + "width=50 ";
 strSQL = strSQL + " WHERE ID=result";
 objCmd = new OleDbCommand(strSQL, db_def.conn);
 objCmd.ExecuteNonQuery();

But I get an error:

No value given for one or more required parameters.

A: Although your code that you're working on is less than desirable, I'll just provide the fix you require at this point:
Change your code to :
 OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
 OleDbDataReader reader = cmd.ExecuteReader();

int result=0;

 if (reader.HasRows)
 {
   reader.Read();
   result = reader.GetInt32(0);
 }

 strSQL = "UPDATE materials SET ";
 strSQL = strSQL + "Dscr = 'concrete', ";
 strSQL = strSQL + "width=50 ";
 strSQL = strSQL + " WHERE ID=" + result;
 objCmd = new OleDbCommand(strSQL, db_def.conn);
 objCmd.ExecuteNonQuery();

You need to provide the value of the result variable outside the SQL string - the database will not know the value of 'result' in its own context.
EDIT: the result variable was declared within the if statement, therefore not available further down for assigning.

A: you can try this and tell  me if it works
     OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE    Type=1", db_def.conn);
     OleDbDataReader reader = cmd.ExecuteReader();
    int result=-1 ;
     if (reader.HasRows)
     {
       reader.Read();
       result = reader.GetInt32(0);
     }
if (result != -1)
{
     strSQL = "UPDATE materials SET ";
     strSQL = strSQL + "Dscr = 'concrete', ";
     strSQL = strSQL + "width=50 ";
     strSQL = strSQL + " WHERE ID="+result;
     objCmd = new OleDbCommand(strSQL, db_def.conn);
     objCmd.ExecuteNonQuery();
}


Q: Unable to Import after Pip Install Ive just installed a package via pip,
  Cloning https://github.com/felix001/commontools.git to /tmp/pip-LMwfnO-build
Installing collected packages: commontools
  Running setup.py install for commontools
Successfully installed commontools-1.0

When I try to import commontools it doesnt import.
The path looks ok though,
>>> import pprint
>>> import sys
>>> pprint.pprint(sys.path)
['',
 '/Library/Python/2.7/site-packages/pip-7.1.2-py2.7.egg',
 '/Users/felix001',
 '/usr/local/lib/python2.7/site-packages',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages',
 '/Library/Python/2.7/site-packages']
>>>
MacBook-Pro:~ felix001$ ls -l /Library/Python/2.7/site-packages
total 392
-rw-r--r--   1 root  wheel    119  9 Sep  2014 README
drwxr-xr-x   7 root  wheel    238 18 Dec 21:39 commontools-1.0-py2.7.egg-info
-rw-r--r--   1 root  wheel    207  3 Nov 20:20 easy-install.pth
drwxr-xr-x   4 root  wheel    136  3 Nov 20:20 pip-7.1.2-py2.7.egg
drwxr-xr-x  60 root  wheel   2040 23 Oct  2014 scapy
-rw-r--r--   1 root  wheel    261 18 Oct  2014 scapy-2.1.0-py2.7.egg-info
drwxr-xr-x   7 root  wheel    238 11 Dec 22:18 threader-1.0-py2.7.egg-info
drwxr-xr-x   6 root  wheel    204 20 Jul 21:49 vboxapi
-rw-r--r--   1 root  wheel    241 20 Jul 21:49 vboxapi-1.0-py2.7.egg-info
drwxr-xr-x  10 root  wheel    340  3 Nov 20:21 virtualenv-13.1.2.dist-info
-rw-r--r--   1 root  wheel  99421  3 Nov 20:21 virtualenv.py
-rw-r--r--   1 root  wheel  83209  3 Nov 20:21 virtualenv.pyc
drwxr-xr-x   8 root  wheel    272  3 Nov 20:21 virtualenv_support

Here is the package details.
MacBook-Pro:~ felix001$ pip show commontools
---
Metadata-Version: 1.0
Name: commontools
Version: 1.0
Summary: commontools
Home-page: UNKNOWN
Author: ====
Author-email: ====
License: UNKNOWN
Location: /Library/Python/2.7/site-packages
Requires:

EDIT :
The error is shown below when I try to import,
MacBook-Pro:~$ which python
/usr/local/bin/python

MacBook-Pro:~$ python
Python 2.7.10 (default, Sep 23 2015, 04:34:14)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from commontools import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named commontools

EDIT2 :
So i removed all instances of python. I installed a new version using brew. Same Issue.
New Python path ,
MacBook-Pro:~ felix001$ which python
/usr/local/bin/python

Now if I install anything by pip. It works fine. But if I install my own git repos it fails (??). Heres an example of one - https://github.com/felix001/commontools
Heres an example,
MacBook-Pro:~ felix001$ pip -v install netaddr
Collecting netaddr
  Getting page https://pypi.python.org/simple/netaddr/
  1 location(s) to search for versions of netaddr:
  * https://pypi.python.org/simple/netaddr/
  Getting page https://pypi.python.org/simple/netaddr/
  Analyzing links from page https://pypi.python.org/simple/netaddr/
    Skipping link https://pypi.python.org/packages/2.4/n/netaddr/netaddr-0.3.1.win32.exe#md5=ba0615105ab8193f4115e2a5767a121c (from https://pypi.python.org/simple/netaddr/); unsupported archive format: .exe
    Skipping link https://pypi.python.org/packages/2.4/n/netaddr/netaddr-0.4.win32.exe#md5=77c28e03c14e081b3339118fad7f1bce (from https://pypi.python.org/simple/netaddr/); unsupported archive format: .exe
    Skipping link https://pypi.python.org/packages/2.4/n/netaddr/netaddr-
0.7.x/CHANGELOG (from https://pypi.python.org/simple/netaddr/); not a file
    Skipping link http://packages.python.org/netaddr/ (from https://pypi.python.org/simple/netaddr/); not a file
    Skipping link https://github.com/drkjam/netaddr/blob/rel-0.7.x/CHANGELOG (from https://pypi.python.org/simple/netaddr/); not a file
    Skipping link https://pythonhosted.org/netaddr/ (from https://pypi.python.org/simple/netaddr/); not a file
  Using version 0.7.18 (newest of versions: 0.7.18, 0.7.18, 0.7.18, 0.7.17, 0.7.17, 0.7.17, 0.7.16, 0.7.16, 0.7.16, 0.7.15, 0.7.15, 0.7.15, 0.7.14, 0.7.14, 0.7.14, 0.7.13, 0.7.13, 0.7.13, 0.7.12, 0.7.12, 0.7.11, 0.7.11, 0.7.10, 0.7.10, 0.7.3, 0.7.3, 0.7.2, 0.7.2, 0.7.1, 0.7.1, 0.7, 0.7, 0.6.4, 0.6.4, 0.6.3, 0.6.3, 0.6.2, 0.6.2, 0.6.1, 0.6.1, 0.6, 0.6, 0.5.2, 0.5.2, 0.5.1, 0.5.1, 0.5, 0.5, 0.4, 0.4, 0.3.1, 0.3.1)
  Using cached netaddr-0.7.18-py2.py3-none-any.whl
  Downloading from URL https://pypi.python.org/packages/any/n/netaddr/netaddr-0.7.18-py2.py3-none-any.whl#md5=f18d38b78469bb440560544f5559e649 (from https://pypi.python.org/simple/netaddr/)
Installing collected packages: netaddr

Successfully installed netaddr-0.7.18
Cleaning up...
MacBook-Pro:~ felix001$ python
Python 2.7.10 (default, Sep 23 2015, 04:34:14)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import netaddr
>>>
>>>
>>>
MacBook-Pro:~ felix001$ pip -vvv  install git+https://github.com/felix001/commontools
Collecting git+https://github.com/felix001/commontools
  Cloning https://github.com/felix001/commontools to /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build
  Running command git clone -q https://github.com/felix001/commontools /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build
  Running setup.py (path:/var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build/setup.py) egg_info for package from git+https://github.com/felix001/commontools
    Running command python setup.py egg_info
    running egg_info
    creating pip-egg-info/commontools.egg-info
    writing pip-egg-info/commontools.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/commontools.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/commontools.egg-info/dependency_links.txt
    writing manifest file 'pip-egg-info/commontools.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'pip-egg-info/commontools.egg-info/SOURCES.txt'
    writing manifest file 'pip-egg-info/commontools.egg-info/SOURCES.txt'
  Source in /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build has version 1.0, which satisfies requirement commontools==1.0 from git+https://github.com/felix001/commontools
Installing collected packages: commontools
  Running setup.py install for commontools
    Running command /usr/local/opt/python/bin/python2.7 -c "import setuptools, tokenize;__file__='/var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-hU9LyU-record/install-record.txt --single-version-externally-managed --compile
    running install
    running build
    running install_egg_info
    running egg_info
    creating commontools.egg-info
    writing commontools.egg-info/PKG-INFO
    writing top-level names to commontools.egg-info/top_level.txt
    writing dependency_links to commontools.egg-info/dependency_links.txt
    writing manifest file 'commontools.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'commontools.egg-info/SOURCES.txt'
    writing manifest file 'commontools.egg-info/SOURCES.txt'
    Copying commontools.egg-info to /usr/local/lib/python2.7/site-packages/commontools-1.0-py2.7.egg-info
    running install_scripts
    writing list of installed files to '/var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-hU9LyU-record/install-record.txt'
  Removing source in /var/folders/13/780bwzl13p5118ldv4qdqgvw0000gn/T/pip-76GaiR-build
Successfully installed commontools-1.0
Cleaning up...
MacBook-Pro:~ felix001$ python
Python 2.7.10 (default, Sep 23 2015, 04:34:14)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import commontools
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named commontools
>>>

Any ideas ?

A: This is not a problem with pip; this is a problem with the commontools package.
Here is its setup.py:
from setuptools import setup

setup(
    name="commontools",
    version="1.0",
    author="xxxxxxxxxxxx",
    author_email="xxxxxxxxxxxx",
    description="commontools",
)

It does not even follow the minimal viable example for packaging or the basic use for setuptools.
TL;DR:
It is not including the source files; which is what the packages keyword for setup() does.


Q: Getting a "Unexpected field at makeError" when uploading a form My form has an input for a file (in my case an image) and for some text. When I hit the submit button, the stated error occurs. I have had the issue for two days now and I tried to understand where the problem was, but my efforts were in vain and I have decided to yield and seek assistance.
Here is my controller for the image:
// using this to generate a random name for an image
var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
    imgUrl = '';

// this is just a loop to create a 10 character random name
for(var i = 0; i < 10; i++) {
    imgUrl += possible.charAt(Math.floor(Math.random() *
              possible.length));
}

/* I saw an answer to a similar question where the correct answer author
said path will always refer to folder where the input folder resides */

var tempPath = req.file.path,
    ext = path.extname(req.file.path).toLower(),
    targetPath = './app/controller/store/' + imgUrl + ext;

// Check if image is of the correct format
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif')
{
    fs.rename(tempPath, targetPath, function(err) {
        if (err) throw err;
        res.redirect('/posts/'+ imgUrl);
    });
} else {
    fs.unlink(tempPath, function () {
        if (err) throw err;
        res.json(500, {error: 'Only image files are allowed.'});
    });

var post = new Post({
    content: req.body.content,
    author: req.user,
    filename: imgUrl + ext
});

post.save(function(err) {
    if(err) {
        return res.status(400).send({
            message: getErrorMessage(err)
        });
    } else res.json(post);
});
}

And here is the form:
<form method="post" action="/posts" enctype="multipart/form-data">
    <textarea name="content"></textarea>
    <input type="file" name="file" id="file">
    <input type="submit" value="Post">
</form>

I did the usual stuff in my configuration file:
app.use(multer({dest: './app/controller/store'}).single('photo'));

I would truly appreciate it if you steer me towards the right path, thanks in advance.

A: .single('parameter') means the input field's name is 'parameter'
In your case:
app.use(multer({dest: './app/controller/store'}).single('photo'));

You passed a 'photo' argument into single func.
Then your form should look like this, change it:
..
    ..
    <input type="file" name="photo">
    ..
..


Q: Any way to make Eclipse 4 Java editor use Courier New? I updated to eclipse 4 and found the default editor font is Consolas, i tried to change the font back to Courier new but in Colors and Fonts editor i just can't find it, any ideas?

A: Window->preference->General->Editor->Text Editor->Colors and Fonts(in the upside of the window)

A: Suppose you are using Windows 7:

*

*Go to Control Panel / Fonts.

*Find Courier New.

*Right click, and choose show.
The reason you cannot find Courier New is that Windows 7 hides it by default.