Linear Algebra, multiplication of Tensor by vector by vector.

Question: I am deriving some equations and need to know the correct mathematical notation for opening up the brackets of an equation with the following variables:
tensor $A \in$ ${\mathbb R}^{l \times l \times l}$, a vector $\mathbf{x} \in {\mathbb R}^{l \times 1}$ and a vector $\mathbf{y} \in {\mathbb R}^{l \times 1}$.
I need to open up the following brackets, specifically interested in multiplying out the $A\mathbf{x}$ term:
$(something + A\mathbf{x})(\mathbf{y} + \mathbf{x})$.
What is correct?
For first term
$\mathbf{y}^TA\mathbf{x}$ or
$\mathbf{x}^TA^T\mathbf{y}$ or
$(A\mathbf{x})\mathbf{y}$ or
$A\mathbf{x}\mathbf{y}$?
Equally for the second term:
$\mathbf{x}^TA\mathbf{x}$ or
$\mathbf{x}^TA^T\mathbf{x}$ or
$(A\mathbf{x})\mathbf{x}$ or
$A\mathbf{x}\mathbf{x}$?
My actual derivations are below:
A commonly studied nonlinear system describing the evolution of the state takes the form
\begin{equation}
\dot{\mathbf{x}}(t) = \mathbf{f}(\mathbf{x}(t),\mathbf{u}(t)) = \widetilde{A}(\mathbf{x}(t))\mathbf{x}(t) + \widetilde{B}(\mathbf{x}(t))\mathbf{u}(t)
\end{equation}
where $\widetilde{A}(\mathbf{x}(t)) \in \mathbb{R}^{{l}\times{l}}$ and $\widetilde{B}(\mathbf{x}(t)) \in \mathbb{R}^{{l}\times{m}}$ are the state and control weight matrices respectively, which are nonlinear in state.
We know that matrices $A(\mathbf{x}(t))$ and $B(\mathbf{x}(t))$ are partial derivatives of $\dot{\mathbf{x}}(t)$ with respect to the state $\mathbf{x}(t) \in\mathbb{R}^{l}$ and control $\mathbf{u}(t) \in \mathbb{R}^{m}$ variables respectively, therefore
\begin{align}
% 1 ------------------------------------------------------------------------------------------------
\frac{\partial \mathbf{f}(\mathbf{x}(t),\mathbf{u}(t)) } {\partial \mathbf{x}(t) }
&=
\frac{\partial \bigg(\widetilde{A}(\mathbf{x}(t))\mathbf{x}(t) + \widetilde{B}(\mathbf{x}(t))\mathbf{u}(t)\bigg) } {\partial \mathbf{x}(t) } \\
&= \widetilde{A}(\mathbf{x}(t)) + \frac{\partial \widetilde{A}(\mathbf{x}(t)) } { \partial\mathbf{x}(t) }\mathbf{x}(t) + \frac{\partial \widetilde{B}(\mathbf{x}(t)) } { \partial \mathbf{x}(t) }\mathbf{u}(t)\\
% 2 ------------------------------------------------------------------------------------------------
\frac{\partial \mathbf{f}(\mathbf{x}(t),\mathbf{u}(t)) } {\partial \mathbf{u}(t) }
&=
\frac{\partial \bigg(\widetilde{A}(\mathbf{x}(t))\mathbf{x}(t) + \widetilde{B}(\mathbf{x}(t))\mathbf{u}(t)\bigg) } {\partial \mathbf{u}(t) } = \widetilde{B}(\mathbf{x}(t))
\end{align}
where $\frac{\partial \widetilde{A}(\mathbf{x}(t)) } {\partial \mathbf{x}(t) } \in \mathbb{R}^{{l}\times{l}\times{l}}$ and $\frac{\partial \widetilde{B}(\mathbf{x}(t)) } { \partial \mathbf{x}(t) } \in \mathbb{R}^{{l}\times{m}\times{l}}$ are $3$-dimensional tensors, while $\frac{\partial \widetilde{A}(\mathbf{x}(t)) } {\partial \mathbf{x}(t) }\mathbf{x}(t) \in \mathbb{R}^{{l}\times{l }}$ and $\frac{\partial \widetilde{B}(\mathbf{x}(t)) } { \partial \mathbf{x}(t) }\mathbf{u}(t) \in \mathbb{R}^{{l}\times{m}}$ are $2$-dimensional matrices.
The nonlinear dynamics (see Eq of $\dot{\mathbf{x}}(t)$) can be linearised around a point ($\mathbf{a}_{x}^{(i)},\mathbf{a}_{u}^{(i)}$), $i=1,...,I$ using first order Taylor approximation
\begin{align}
% 1 ------------------------------------------------------------------------------------------------
\dot{\mathbf{x}}(t)
&=
\mathbf{f}(\mathbf{a}_{x}^{(i)},\mathbf{a}_{u}^{(i)})
+
\Bigg(
 \left.\frac{\partial \mathbf{f}(\mathbf{x}(t),\mathbf{u}(t))}{\partial \mathbf{u}(t)}
 \right|_{\substack{\mathbf{x}(t)=\mathbf{a}_{x}^{(i)}\\\mathbf{u}(t)=\mathbf{a}_{u}^{(i)}}}
 \Big(
  \mathbf{u}(t) - \mathbf{a}_{u}^{(i)}
 \Big)
\Bigg)
+
\Bigg(
 \left.\frac{\partial \mathbf{f}(\mathbf{x}(t),\mathbf{u}(t))}{\partial \mathbf{x}(t)}
 \right|_{\substack{\mathbf{x}(t)=\mathbf{a}_{x}^{(i)}\\\mathbf{u}(t)=\mathbf{a}_{u}^{(i)}}}
 \Big(
  \mathbf{x}(t) - \mathbf{a}_{x}^{(i)}
 \Big)
\Bigg)
\nonumber \\
% 2 ------------------------------------------------------------------------------------------------
&=
\Bigg(
 \widetilde{A}(\mathbf{a}_{x}^{(i)})\mathbf{a}_{x}^{(i)}
+
\widetilde{B}(\mathbf{a}_{x}^{(i)})\mathbf{a}_{u}^{(i)}
\Bigg)
+
\Bigg(
 \widetilde{B}(\mathbf{a}_{x}^{(i)})
 \Big(
  \mathbf{u}(t) - \mathbf{a}_{u}^{(i)}
 \Big)
\Bigg)
\nonumber \\
% 3 ------------------------------------------------------------------------------------------------
& +
\Bigg(
  \widetilde{A}(\mathbf{a}_{x}^{(i)})
  +
  \frac{\partial\widetilde{A}(\mathbf{x}(t))}{\partial \mathbf{x}(t)}\bigg|_{x(t)=\mathbf{a}_{x}^{(i)}} \mathbf{a}_{x}^{(i)}
  +
  \frac{\partial\widetilde{B}(\mathbf{x}(t))}{\partial \mathbf{x}(t)}\bigg|_{x(t)=\mathbf{a}_{x}^{(i)}} \mathbf{a}_{u}^{(i)}
\Bigg)
\bigg(
 \mathbf{x}(t) - \mathbf{a}_{x}^{(i)}
\bigg)
\end{align}
Now come my actual questions:

I am highly concerned that this is incorrect: $\frac{\partial \widetilde{B}(\mathbf{x}(t)) } { \partial \mathbf{x}(t) }\mathbf{u}(t)$, because $\frac{\partial \widetilde{B}(\mathbf{x}(t)) } { \partial \mathbf{x}(t) }$ is $\in \mathbb{R^{l \times m \times l}}$ and $\mathbf{u}$ is $\in \mathbb{R^{m \times 1}}$. Therefore I don't think I can multiply the derivative by the $\mathbf{u}$ but how do I write this differentiation using the product rule then?
When I open up the brackets what is the answer? $\Bigg(
  \widetilde{A}(\mathbf{a}_{x}^{(i)})
  +
  \frac{\partial\widetilde{A}(\mathbf{x}(t))}{\partial \mathbf{x}(t)}\bigg|_{x(t)=\mathbf{a}_{x}^{(i)}} \mathbf{a}_{x}^{(i)}
  +
  \frac{\partial\widetilde{B}(\mathbf{x}(t))}{\partial \mathbf{x}(t)}\bigg|_{x(t)=\mathbf{a}_{x}^{(i)}} \mathbf{a}_{u}^{(i)}
\Bigg)
\bigg(
 \mathbf{x}(t) - \mathbf{a}_{x}^{(i)}
\bigg) $
Comment: It is rather close to impossible to understand what you mean. Please read http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-qu%E2%80%8C%E2%80%8Bick-reference
Comment: Thank you very much for the reply, I edited the question to include everything as Latex. I just have not dealt with multiplying these things out before and not sure of how to write it correctly. Which options are correct please, if any :-)?
Comment: You want \partial, not \partderiv.
Answer: If $A$ takes one vector to give a linear application on $\mathbb{R}^\ell$, then you can write in coordinates $x=x^{j}$, $y=y^{k}$ and $A=A^{i}_{jk}$ where $i,j,k\in\{1,\ldots,\ell\}$ and then write $A^{i}_{jk}x^jy^k$. This is the abstract index notation : $A^{i}_{jk}x^jy^k$ is the $i$-th coordinates of the vector obtained by applying $A$ to both vectors $x$ and $y$.
If you want to keep your vectorial notation, then for the first term you can write $A\textbf{x}\textbf{y}$ or $\left(A\textbf{x}\right)\textbf{y}$ or also $\left(A\textbf{x}\right)\left(\textbf{y}\right)$ because $A\textbf{x}$ is a linear map on $\mathbb{R}^\ell$. Take care of the notation $\textbf{y}^T\textbf{z}$ which is the inner product of $\mathbb{R}^\ell$ of $\textbf{y}$ with $\textbf{z}$ (both vectors!).
Comment: I am not sure I understand. When we have a quadratic form $\mathbf{x}^TC\mathbf{x}$ where $\mathbf{x}^T$ is $\in \mathbb{1 \times l}$ and $C \in \mathbb R ^{l \times l}$, we are allowed to say $\mathbf{x}^TC$ because the dimensions agree. This is where my thinking is coming from for this form, since the dimensions of $\mathbf{x}^TA$ agree, because $\mathbf{x}^T$ is $\in \mathbb{1 \times l}$ and $A$ is $\in \mathbb{ R} ^{l\times l \times l}$.
Comment: Thank you very much for your reply. Could you please clarify, you mean to be careful of notation $\mathbf{x}\mathbf{x}$ I think. I indeed agree that this was not a good option. What did you think of the 'quadratic' form $\mathbf{y}^TA\mathbf{x}$?
Comment: I meant that $\textbf{y}^T A\textbf{x}$ has no sense because $\textbf{v}^T \textbf{w}$ is the dot product in $\mathbb{R}^\ell$ between two vectors $\textbf{v}$ and $\textbf{w}$, and here $A\textbf{x}$ is not a vector but a linear map (or a tensor of type $(1,1)$).
Comment: Please see my original Qn, for which I actually now added my actual derivations, where one particular part, i.e. opening the brackets, is confusing me.
Comment: Good point here Katya : $\textbf{y}^TA\textbf{x}$ has indeed a sense when you consider it as a matix composition. But $\textbf{y}^TA\textbf{x}$ is a linear form on $\mathbb{R}^3$ whereas $A$ applied to both vectors $\textbf{x}$, $\textbf{y}$ is a new vector! Actually, you see here that the identification $\mathbb{R}^3$ with the matrices in column is not really good (it can be confusing), and that's why I proposed the abstract index notation.
Comment: As for you new question, could you write it better (I can not read it correctly) ? Note \partial for $\partial$ symbol and take care of the spaces between symbols in a formula when you have some \. I will try to answer it after your correction.
Comment: Dear Nicolas, thank you for your help. I hope that everything now is more clear and I really look forward to discussing the 2 questions with you. I am also not clear what it means to say ' a linear form on $\mathbb {R^{3}}$ '? The issue with the abstract index notation is that I don't think it is practical for my equations, which I am deriving.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/23162/discussion-between-nicolas-and-katya).


How is the precise value of pi calculated?

Question: We often see the value of pi(irrational) with large no of digits behind the decimal place. How is such precise value of pi calculated?
Comment: I'm pretty sure this question has been asked several times. [Here is one such example](http://math.stackexchange.com/questions/588141/how-is-the-value-of-pi-pi-actually-calculated/596555) where you may find some of the answers helpful.
Comment: You  have [rapidly converging series](http://math.stackexchange.com/questions/14113/series-that-converge-to-pi-quickly), which can be used.
Comment: $\pi=\frac41-\frac43+\frac45-\frac47+\frac49\dots$
Comment: @barak manos; How is this series developed?
Comment: @Lamichhane88: Taylor series of $\arctan$?
Comment: @barakmanos: That series is definitely *not* how large numbers of digits of $\pi$ are calculated.  It converges much too slowly.
Comment: @NateEldredge: That series is definitely how large numbers of digits of $\pi$ **can** be calculated. The question doesn't mention anything about efficiency.
Comment: @barakmanos: I interpreted the word "is" in the title to ask about practical methods, i.e. those that actually have been used to calculate large numbers of digits.
Comment: @NateEldredge: I interpreted it as if OP could not figure out how the decimal digits of $\pi$ possibly be calculated. I would tend to guess that OP would just as well refer to any other irrational number for that matter, and just so happen had $\pi$ in mind. But that's more of an interpolation on OP ratings, plus the fact that the answer to this question could easily be found here and elsewhere... So I suppose that only OP could provide the actual meaning behind this question...
Answer: If you want an easy way to calculate $\pi$ you can divide the circumference of a circle by its diameter, but such a method involves taking precise and accurate measurements and there is always some error to be accounted for. Wolfram Mathworld has listed methods and formulas to calculate $\pi$, but if you want 5 user friendly ways, here they are.
Note:
The precision to which pi can be calculated and the time taken to do so approximately depends upon the computers and algorithms used and how they have been optimised.
Comment: If its only about easy (which it isn't): A Monte-Carlo method (extremely slow conv.) is to choose points with random $x,y$ coordinates between -1 and 1. And then counting those for which $\sqrt{x^2 + y^2} \le 1$ and relating the count to the total number of points (that gives you $\pi/4$).
Comment: in the limit for $\infty$ points


Connecting to external oracle database using db_set_active in settings.php not working

Question: In DRUPAL7 i am trying to connect to oracle external db using db_set_active('ora_db'). here is my code snippet in settings.php. i am not sure where i am going wrong.
when i try oci_connect('uname','pass','db_name/service_name') it works fine in my drupal page. but when i try using drupal way to connect oracle db it's not working.
Note: just for database connect i don't want to use other modules
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'db_name1',
      'username' => 'xxxx',
      'password' => 'xxxx',
      'host' => 'host1',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'mportal' =>
  array(
    'default' =>
    array (
      'database' => 'db_name2',
      'username' => 'zzzzz',
      'password' => 'zzzzz',
      'host' => 'host2',
      'port' => '3306',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
'ora_db' =>
    array(
    'default' =>
        array (
        'database' => 'ora_dbname',
                'username' => 'yyyyyy',
                'password' => 'yyyyyy',
                'host' => 'ora_db_host_name/service_name',
                'port' => '1521',
                'driver' => 'oracle',
                'prefix' => '',
            ),
    ),
);

Thanks in Advance.
Answer: Drupal core doesn't have an Oracle driver, so you can't use the API with an Oracle database unless you install a module (or find another way to introduce the code, but it would be counter-intuitive not to use a module).
The Oracle Driver module provides what you need, if you don't want to install it you're stuck using oci_connect etc.
Comment: call me crazy but PDO supports ODBC as well -- isn't there an Oracle ODBC driver one could install on the server?
Comment: there is no specific documentation on how to use Oracle Driver module.
i installed the module and no configuration appears, am i missing something here?
Comment: @vnimbala The configuration page is at admin/config/development/oracle. For the rest, it's a database driver; you just tell Drupal the kind of database engine to use, in the settings.php file.


Apache Camel split with new line token and use aggregation stategy

Question: I have the following route:
from("file:/home/tmp/test?move=.done")
    .routeId("file")
    .split(body().tokenize("\n"),new GroupedBodyAggregationStrategy())
    .process(new Processor() {
      @Override
      public void process(Exchange exchange) throws Exception {
        exchange.getMessage().setHeader("Test", "test");
        System.out.println(exchange.getIn().getBody());
      }
  })

and the file that is being consumed is:
1234,56676,2345
234,213,412
124,423,5236

I would expect only one exchange to reach the processor after split and that its body contains all the above lines, however it behaves like I do not use an aggregation strategy at all. 3 exchanges reach the processor each with the body that corresponds to a single line. Also, it does not matter if I use GroupedBodyAggregationStrategy or a custom one, it is always the same. What am I doing wrong?
Answer: Give a look here enter link description here
What you look is :
from("file:/home/tmp/test?move=.done")
.routeId("file")
.split(body().tokenize("\n"),new GroupedBodyAggregationStrategy())
  // instructions on each message from the split (.ie each row here)
.end()
  // instructions on aggregated result
.process(new Processor() {
  @Override
  public void process(Exchange exchange) throws Exception {
    exchange.getMessage().setHeader("Test", "test");
    System.out.println(exchange.getIn().getBody());
  }
})

Comment: Yes, that was it, thank you for your prompt reply. It needs the instructions to work, if end() comes just after the split then the route fails to load.


Intgrating acceleo with jboss errai and gwt

Question: I have to create a project in jboss errai with GWT but I want to generate must of my model code using acceleo using eclipse modeling framework .ecore model. I have done this things.

created maven project using command

mvn archetype:generate -DarchetypeGroupId=org.jboss.errai.archetypes -DarchetypeArtifactId=cdi-quickstart -DarchetypeVersion=2.2.0.Final

Imported project to eclipse as existing maven project.
Goes to Acceleo->Convert Project to  Acceleo Generator Project but getting  nothing.
Then I goes to Acceleo->Convert to Acceleo MTL Projects and created a new acceleo project and generated model to my previous project using .ecore model but getting error in model class as I am getting EString at String
and other also as E-datatype ,plz suggest solution how can I use acceleo feature into my jboss errai maven project.

my template file is as :
<code>[comment encoding = UTF-8 /]
[module main('http://www.eclipse.org/emf/2002/Ecore')  ]

[template public generateElement(anEClass : EClass)]
[comment @main /]
[file (anEClass.name.concat('.java'), false, 'UTF-8')]
    public class [anEClass.name.toUpperFirst()/]{
[ for (p:EAttribute|anEClass.eAttributes) separator('\n')]
private [p.eAttributeType.name/] [p.name/];
[/for]

[ for (p:EAttribute|anEClass.eAttributes)  separator('\n')]
public  [p.eAttributeType.name/]  get[p.name.toUpperFirst()/]()
{

    return this.[p.name/];

}
[/for]

[ for (p:EAttribute|anEClass.eAttributes) separator('\n')]
public  void set[p.name.toUpperFirst()/]([p.eAttributeType.name/] [p.name/])
{
 this.[p.name/]=[p.name/];
}
[/for]

[protected ('protected')]

[/protected]

}

[/file]
[/template]
</code>
The one of model generated from .ecore model is as
<code>public class UserRegistration {
    private EString strFirstName;
    private EString strSurName;
    private EString strOccupation;
    private EString strQualificaion;
    private EString strFotherName;
    private EString strMotherName;
    private EEList chMaritalStatus;
    private EDouble dblAnnualIncome;
    private EDate dtDOB;
    private EString strAbout;
    private EJavaClass objAcceleo;

    public EString getStrFirstName() {
        return this.strFirstName;
    }

    public EString getStrSurName() {
        return this.strSurName;
    }

    public EString getStrOccupation() {
        return this.strOccupation;
    }

    public EString getStrQualificaion() {
        return this.strQualificaion;
    }

    public EString getStrFotherName() {
        return this.strFotherName;
    }

    public EString getStrMotherName() {
        return this.strMotherName;
    }

    public EEList getChMaritalStatus() {
        return this.chMaritalStatus;
    }

    public EDouble getDblAnnualIncome() {
        return this.dblAnnualIncome;
    }

    public EDate getDtDOB() {
        return this.dtDOB;
    }

    public EString getStrAbout() {
        return this.strAbout;
    }

    public EJavaClass getObjAcceleo() {
        return this.objAcceleo;
    }

    public void setStrFirstName(EString strFirstName) {
        this.strFirstName = strFirstName;
    }

    public void setStrSurName(EString strSurName) {
        this.strSurName = strSurName;
    }

    public void setStrOccupation(EString strOccupation) {
        this.strOccupation = strOccupation;
    }

    public void setStrQualificaion(EString strQualificaion) {
        this.strQualificaion = strQualificaion;
    }

    public void setStrFotherName(EString strFotherName) {
        this.strFotherName = strFotherName;
    }

    public void setStrMotherName(EString strMotherName) {
        this.strMotherName = strMotherName;
    }

    public void setChMaritalStatus(EEList chMaritalStatus) {
        this.chMaritalStatus = chMaritalStatus;
    }

    public void setDblAnnualIncome(EDouble dblAnnualIncome) {
        this.dblAnnualIncome = dblAnnualIncome;
    }

    public void setDtDOB(EDate dtDOB) {
        this.dtDOB = dtDOB;
    }

    public void setStrAbout(EString strAbout) {
        this.strAbout = strAbout;
    }

    public void setObjAcceleo(EJavaClass objAcceleo) {
        this.objAcceleo = objAcceleo;
    }

    //Start of user code protected
    //End of user code
}
</code>
Here I am getting EString at place of String and other  primitive data type as E-Data type.
Plz suggest a solution How can I get java Data and other processor for the same
Answer: Actually I got the core answer for my question I just modified in my mtl file
<code>[comment encoding = UTF-8 /]
[module main('http://www.eclipse.org/emf/2002/Ecore')/]
[template public generateElement(anEClass : EClass)]
[comment @main /]
[file (anEClass.name.concat('.java'), false, 'UTF-8')]
package com.garvityWeb.main.migrated.models;
@Portable
public class [anEClass.name.toUpperFirst()/]
{
[ for (p:EAttribute|anEClass.eAttributes) separator('\n')]
@Inject
@DataField
private [p.eAttributeType.instanceClassName/] [p.name/];
[/for]

[ for (p:EAttribute|anEClass.eAttributes)  separator('\n')]
public  [p.eAttributeType.instanceClassName/]  get[p.name.toUpperFirst()/]()
{
    return this.[p.name/];
}
[/for]
[ for (p:EAttribute|anEClass.eAttributes) separator('\n')]
public  void set[p.name.toUpperFirst()/]([p.eAttributeType.instanceClassName/] [p.name/])
{
 this.[p.name/]=[p.name/];
}
[/for]
}
[/file]
[/template]
</code>


c# pass value from current Form1 to Form2 shows error non static

Question: private void btn_justest_Click(object sender, EventArgs e)
{
    using (var myForm = new FormShowResult())
    {
        myForm.Show();
        textBoxNameTest.Text = FormShowResult.TheValue;
    }
}

in Form 2:
public string TheValue
{
    get { return richtb_Show.Text; }
}

the problem is there is error "An object reference is required for the non-static field, method, or property"
how to solve
My purpose to is call set an value to the parameter of Form2's Function, and load the function when start Form2.
Answer: You need to use the myForm variable to access the instance, not the type name.
Answer:   textBoxNameTest.Text = myForm.TheValue;


Constructing an invertible integer matrix given one column.

Question: Given a vector $\vec{v}\in\mathbb{Z}^n$ whose entries are relatively prime, is it possible to build an invertible $n\times n$ integer matrix which has $\vec{v}$ as a column?
For $n=2$ this is true, and it seems like it should be true for $n>2$, but the proof becomes much more complicated as the expression for the determinant becomes more complicated. I am more or less trying to set the determinant equal to $\pm 1$ and then determine if the corresponding equations have integer solutions. This is messy. I am wondering if there is a nicer way to prove this. The proof doesn't need to be elementary.
Answer: Yes; the Smith Normal Form algorithm is a sledgehammer that will do
this.
More generally, one can transform a column $\pmatrix{a_1\\\vdots\\a_n}$
with integer entries and $\gcd(a_1,\ldots,a_n)=1$ to the unit vector
$\pmatrix{1\\0\\\vdots\\0}$ via row operations of the form $R_i\mapsto R_i+mR_j$ ($i\ne j$, $n\in\Bbb Z$), $R_i\leftrightarrow R_j$ and $R_i\mapsto R_j$, each of which corresponds to premultiplying by an elementary matrix with integer entries and determinant $\pm1$. Thus there is a matrix $M$ integer entries and determinant $\pm1$ with
$M\pmatrix{a_1\\\vdots\\a_n}=\pmatrix{1\\0\\\vdots\\0}$. Then $M^{-1}$
also has integer entries, and determinant $\pm1$ and its first column is
$\pmatrix{a_1\\\vdots\\a_n}$.
Answer: This can be done by induction.
You can just try to put the last column of the matrix to be
\begin{pmatrix}  a \\ 0 \\ 0 \\ \cdots \\ 0 \\ b \end{pmatrix}
And use the induction hypothesis


AZURE FUNCTIONS: PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH? for pdf2image

Question: I am getting this error "Result: Failure Exception: PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH? for azure functions."
I am using pdf2image library's convert_from_path() to process my pdf to image. This works fine while I test from local. While publishing the function to azure, poppler-utils package also gets installed there but still the error comes. I saw a lot of threads related to this error and tried it but wanted to know , if anyone experienced this specifically for azure functions.
Answer: Suggestion for this issue has been provided in the thread
"you should try to troubleshoot it by simply having a function that opens a process and prints the help of pdftoppm (poppler). You will be able to get a different message that might be more relevant.
Something like this:
<code>  import subprocess

  def main():
   p = subprocess.Popen(["pdftoppm", "-h"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   out, err = p.communicate()
   print(out, err)
</code>
As a general recommendation, I would bundle the poppler utilities with your package to avoid installing it in the function environment. You can call the function with poppler_path."
Comment: Thanks Jaya. Yes I tried this. Still, I had the same issue. So I decided to deploy the functions via docker into azure container registry. This worked for me without any issues.


Which direction to play chords cello

Question: I'm practicing a simple cello exercise to fill in gaps in my knowledge and, well, I found one.

It is a simple passage with pizz.
Which direction should the chords be played? From lowest to highest note? Highest to lowest? Alternate? Or, though I doubt it, all at once with three fingers?
When I meet the same symbol on guitar I use all fingers and roll from lowest to highest (unless there's an arrow). Is that how this should be done?
Answer: You have correctly interpreted the notation. Default is bottom to top.
On the cello, arpeggiated pizzicato chords are usually played with the side of the right thumb (while you keep the bow with the other fingers), quickly touching each string from lowest (here G) to A in a kind of spiral move of the hand and the arm.
If you want maximum effect:

press very firmly the left hand over the stopped strings : if your left fingers are too soft, they will dampen the sound.
try to use your right thumb over the lower half of the fingerboard, going closer to the bridge for the higher notes so that they sound as loud as the lowest ones.

This is especially important in the passage you show : only the highest note is stopped and change from one chord to the other. It should be heard "above" the others.
Also : make sure your nail on the right thumb cannot touch or catch the strings while making the pizzicato, this is different from some guitar styles. You may need to clip it a little on the side.
Answer: Lowest to highest. This is the usual symbol for a rolled chord on most instruments. A high to low rolled chord is the same symbol with a downward pointing arrow at the bottom.
https://fthmb.tqn.com/fU1WRViMgiE_4R6rrAhgawP547s=/735x0/GL_arpeggio-57c7d9093df78c71b6a9fca9.png
(edited to display linked image)

The first two show upward rolled chords and the third a downward rolled chord.
Comment: Ya beat me to it :-) .
Answer: That wiggly line is a standard notation for arpeggio. You can meet it on other instruments too (like piano). It means to play the notes not all at once, but in a quick succession, from lowest to highest, without muting them, so that the whole chord is eventually sounding.
A chord without the wiggly line should (strictly technically) be played all at once.
I don't play the cello, but this is the meaning on the piano and on the guitar. When, on the guitar, you're rolling all the fingers down one by one, you actually make a sort of rasgueado, which is somewhat different sound, used mainly in flamenco guitar (most often denoted either by a word "rasgueado" or explicitly with written-out quintuplets with lots of arrows and right-hand finger designations all over the place :--)). Chances are that it works this way on the cello as well.

Which direction to play chords cello


The MPN ID you provided (XXXXXX) does not exist, or you do not have access to it. Please provide a valid MPN ID and try again]

Question: I am getting this error when I am trying to add MPNID to an Azure Application Registration. No documentation regarding this issue
The MPN ID you provided (XXXXXX) does not exist, or you do not have access to it. Please provide a valid MPN ID and try again. [VFSMWUDu8KWgEx8CQ8Djg7]
Answer: There are 2 types of MPNID - Local and Global. I was trying Local MPNID
Try Global MPNID


.htaccess test query parameters instead of FilesMatch

Question: I have the following htaccess file:
<filesMatch "\.png$">
<ifModule mod_headers.c>
Header set Cache-Control "public"
Header set Content-Description "File Transfer"
Header set Content-Disposition "attachment"
Header set Content-Type "image/png"
Header set Content-Transfer-Encoding "binary"
</ifModule>
</filesMatch>

I'd like to test the %{QUERY_STRING} instead of performing a filesmatch. Is that possible?
Answer: You're not going to be able to do this using only your htaccess file. You're going to need to write a script or something to set the headers, then map requests to the script using something like this:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^dl=true$
RewriteRule ^(.*)\.png$ /image_dl.php?file=$1.png [L]

Then in your image_dl.php script:
<?php
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment');
header('Content-Type: image/png');
header('Content-Transfer-Encoding: binary');

$file = $_GET['file'];
header("Content-length: ".filesize($file));

ob_clean();
flush();
readfile($file);
?>


Node reference field display

Question: I have a content type with several fields, some of them are node reference fields displaying multiple values. I've configured the display of one node reference field like teaser showing two fields "code, description".
The problem is when the node reference has more than one value, keeps adding lines to the bottom. I want to display this node reference field like "code1/code2 description1/description2" in one line.
How can I achieve this? What template should I override, field.tpl.php or node.tpl.php?
Comment: Presumably you've tried both and have found one/both do not work? Please elaborate on what happened when you tried both template files yourself, we're not here to do your testing for you :)
Comment: Hi! Of course not! :) yes, i have tried field.tpl.php but i didn't find out how to control each field of the node reference field. i just can print the whole output of a line next to each other.. Also i think this is not the best way of doing it, i would like to know if there is a better way. In node.tpl.php i can't access the fields..
Answer: After a lot of research i finally solved my problem. I don't know if this is the best way of doing it but it works for me.
I added a THEME_field() function to my template.php of the desired field.
Inside my template function i removed the even/odd css classes because i want all in a single line.
Probably exists a better way to access field values, this was the solution i found. Digging the $item array i was able to get my code and color description values.
If someone knows a better way of doing this please help me improve it.
There goes the code i hope it helps someone else.
Don't forget to replace THEME by your theme name and the FIELDNAME.
function THEME_field__FIELDNAME($variables) {
$output = '';

// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
  $output .= '
' . $variables['label'] . ':
';
}

// Render the items.
$output .= '
';
$codes = "";
$colors ="";
foreach ($variables['items'] as $delta => $item) {

    $code = $item['field_color_description']['#object']->title_field['und'][0]['value'];
    $color = $item['field_color_description']['#object']->field_color_description['und'][0]['node']->title;

    $codes .= $code."/";
        //avoid repeated color descriptions
        if (strpos($colors,$color) === false)
        {
        $colors .= $color."/";
        }
     }
     $classes = 'field-item even';

     $codeAndColors = rtrim($codes,"/") . " ". rtrim($colors,"/");
     $output .= '
' . $codeAndColors . '
';
     $output .= '
';

     // Render the top-level DIV.
     $output = '
' . $output . '
';

     return $output;

}

Node reference field display


How can I deserialize my string into JSON?

Question: The idea is that I want to take my string, convert it to a JSON object, then loop through the results array to extract all of the id fields and put them in a separate array.
I've tried multiple 'C# string to JSON examples' but have gotten the farthest with this particular bit of code.
main:
String myString = "{
  "total": 111,
  "token": "abcdefghijklmn",
  "results": [
    {
      "id": "001",
      "some_stuff": {
        "aValue": 0,
        "bValue": 1
      }
    },
    {
      "id": "001",
      "some_stuff": {
        "aValue": 0,
        "bValue": 1
      }
    },
    {
      "id": "001",
      "some_stuff": {
        "aValue": 0,
        "bValue": 1
      }
    },
  ],
  "whatdidido": {
    "iretrieved": "yes"
  }
}";

var list = JsonConvert.DeserializeObject<List<IdReturn>>(myString);

classes:
public class IdReturn
 {
  public int total { get; set; }
  public string token { get; set; }
  public List<Attribute> results { get; set; }
 }

public class results
 {
  public string id { get; set; }
  public string some_stuff { get; set; }
 }

The expected result is a JSON object that I can use as: list.results[i].id to get to each id. The error message that I get from the code above is:

Unhandled Exception: Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[myExample.IdReturn]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
  To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Comment: You can't deserialize to `List` because your JSON doesn't represent a collection, it represents just one object. So you should be deserializing to `IdReturn`. Then your class for the property `result` is `Attribute` not the `results` class you've shown in your code.
Comment: First clear up some terms. JSON _is a string_. There is no such thing as a JSON object (although the error message you get is confusing on this point). You want to convert your string (which is JSON) to a .Net object
Comment: change public class results to public class Attribute. Also create a new class for some_stuff which has 2 integer properties. And change public string some_stuff { get; set; } to public SomeStuff some_stuff { get; set; }
Answer: First your string is not written as valid C#, it should be:
        String myString = @"{
  ""total"": 111,
  ""token"": ""abcdefghijklmn"",
  ""results"": [
    {
      ""id"": ""001"",
      ""some_stuff"": {
        ""aValue"": 0,
        ""bValue"": 1
      }
},
    {
      ""id"": ""001"",
      ""some_stuff"": {
        ""aValue"": 0,
        ""bValue"": 1
      }
    },
    {
      ""id"": ""001"",
      ""some_stuff"": {
        ""aValue"": 0,
        ""bValue"": 1
      }
    },
  ],
  ""whatdidido"": {
    ""iretrieved"": ""yes""
  }
}";

Next you need a set of classes to represent the JSON structure:
public class Rootobject
{
    public int total { get; set; }
    public string token { get; set; }
    public Result[] results { get; set; }
    public Whatdidido whatdidido { get; set; }
}

public class Whatdidido
{
    public string iretrieved { get; set; }
}

public class Result
{
    public string id { get; set; }
    public Some_Stuff some_stuff { get; set; }
}

public class Some_Stuff
{
    public int aValue { get; set; }
    public int bValue { get; set; }
}

And finally to deserialize it and print each id you can do this:
var root = JsonConvert.DeserializeObject<Rootobject>(myString);
Console.WriteLine(string.Join(",", root.results.Select(item => item.id)));

Which, for your sample will result in:
001,001,001


qwt save plot configuration?

Question: The user has spent a lot of time setting up a nice qwt plot (picking curves from the database, configuring line colour and style, scaling them, scrolling and panning to the interesting places, and so on). Now he wants to save this layout, not as a picture, but as a configuration which he can load again later, and refine even more.
What's the most elegant way to make a QwtPlot save itself to a file, so that I can load it again? I'd love to simply write
<code>outf << myQwtPlot;
</code>
which obviously isn't possible out of the box. Maybe there is something simpler than making my own QwtPlod-derived class which implements operator<< and operator>> to read and write all "important" attributes.. ?
Answer: You could try Qt's new property system, but I think you still end up doing approximately what you have in mind.
http://qt-project.org/doc/qt-4.7/properties.html
Comment: Although negative, this reply is the appropriate one :(

qwt save plot configuration?


Join/Sort Running Slowly

Question: I spent several hours crafting an SQL query that executes a JOIN and sorts two columns together, in a way that I haven't dealt with before.  Here is the query:
SELECT `m`.`id`, `m`.`primary_category_id`, `m`.`primary_category_priority`, `m`.`description`
FROM (`merchant` AS m)
LEFT JOIN `merchant_category`
    ON `merchant_category`.`merchant_id` = `m`.`id`
WHERE
    `merchant_category`.`category_id` = '2'
    OR `m`.`primary_category_id` = '2'
GROUP BY `m`.`id`
ORDER BY
    LEAST(merchant_category.priority = 0, `primary_category_priority` = 0) ASC,
    LEAST(merchant_category.priority, `primary_category_priority` ) ASC
LIMIT 10

It has to sort two columns together, one from the merchant_category table, and one from the merchant table, so that they're sorted together.  Each row of the merchant has a a "primary" category, referred to directly in the table, and zero or more "secondary" categories, stored in the merchant_category table.  Now it works fine, but it's very slow: usually over a minute on my production database.  I imagine the JOIN plus the complex sorting is causing the problem, but what can I do?
EDIT Here are the two table's schemas:
CREATE TABLE IF NOT EXISTS `merchant` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) CHARACTER SET utf8 NOT NULL,
  `primary_category_id` int(11) NOT NULL,
  `primary_category_priority` int(10) unsigned NOT NULL DEFAULT '0',
  `description` mediumtext CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE IF NOT EXISTS `merchant_category` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `merchant_id` int(10) NOT NULL,
  `category_id` int(10) NOT NULL,
  `priority` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
)

Comment: can you post the schema of tables specifically `merchant` and `merchant_category`? maybe you have missed some indexes..
Comment: Do you have indexes set-up properly? How many rows in the two tables ?
Comment: @Erik `merchant` has over 20,000 I believe, and `merchant_category` has several times more.
Comment: @JohnWoo I added the table schemas.
Answer: Try to add foreign key constraint on the second table,
CREATE TABLE IF NOT EXISTS `merchant_category` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `merchant_id` int(10) NOT NULL,
  `category_id` int(10) NOT NULL,
  `priority` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  CONSTRAINT mc_fk FOREIGN KEY (`merchant_id`) REFERENCES `merchant`(`id`)
)

Comment: @Jonah what are you trying to sort?
Comment: By a priority number that is in two different tables.  In the `merchant` table for the primary category, and in the `merchant_category` table for the secondary categories.
Comment: Okay, I added the foreign key constraint, should I expect my query to run more quickly now?
Comment: as expected, maybe. did you try to run the query again?
Comment: wow, that sped it up so much, it's basically instant now.  Thanks!
Answer: You're forcing it to run LEAST (twice!) for each row in order to sort it.  It can't use an index for this.
Comment: What would you recommend as an alternative?
Comment: I had to use `LEAST` to integrate the two numbers, in order to sort them together.
Comment: Two other small comments.  Shouldn't the '`merchant_category`.`category_id` = '2'' be part of the `JOIN`?  And You should have a composite index that includes the things you're selecting by and the primary key, so (primary_category_id, id).  An `EXPLAIN` would have shown a table scan on that table...
Comment: I don't know if it would be any faster, but it feels like you should use a `CASE` statement as part of the `SELECT` to determine the _priority_, and then `SORT BY` that named column.
Comment: that `WHERE` statement is just the particular category being selected in this case, it could be anything.

Join/Sort Running Slowly


How to show that if $\int_a^bf(x)p(x)dx=0$ for continuous $f$ and polynomial $p$, $f$ is identically is zero?

Question: Suppose $f$ is continuous on $[a,b]$ and $\int_a^bf(x)p(x)dx=0$ for every polynomial $p$ with $p(a)=0=p(b)$.
Show that $f$ is identically is zero?
This question is different than If $f$ is continuous on $[a , b]$ and $\int_a^b f(x) p(x)dx = 0$ then $f = 0$
Because we have assumption on the end points of $p$.
Comment: @norfair It's not exactly a duplicate because the OP is imposing that $p(a)=p(b)=0$.
Comment: What have you tried? If you're stuck, try something easier. Like what if you knew that $f$ was a polynomial?
Comment: Moreover, you might want to take a look at the following (almost duplicate) questions linked [here](https://math.stackexchange.com/q/165825/36150)
Answer: A more simple-minded approach might be to say: Consider
$$ \frac{1}{B(p,q)} \int_0^1 x^{p-1} (1-x)^{q-1} f(x) \,  dx $$
with $B$ denoting the Beta function. Let $p,q  \to \infty$ with $\frac{p}{p+q}=\mu$ fixed, and the integral is $f(\mu)$ in the limit, which will need to be zero. As this works for any $\mu$, we have $f=0$.
Comment: I like the probability-inspired solution!  I wouldn't really say that's simple-minded though...
Comment: Well it's like saying that I can make a polynomial look like a delta function, which I dare say would be frowned upon in an Analysis class!
Comment: Yep, which interpreted probabilistically, is some sort of law of large numbers statement.  "Simple-minded" to me is a somewhat self-deprecating statement.  Maybe you meant it's simple and elegant, which I definitely agree with.  The type of argument p4sch gives is certainly the more standard "analysis" one.
Answer: The set of all polynomials $p \colon \mathbb{R} \rightarrow \mathbb{R}$ with $p(a) = p(b)=0$ form a sub-algebra $\mathcal{P}_0$ of the space $C_0((a,b))$, the space of real-valued continuous functions on $(a,b)$ which vanish at $a$ and $b$.

The polynomial $p(t) := (t-a)(t-b)$ has the property that $p(x) \ne 0$ for all $x \in (0,1)$, i.e. $\mathcal{P}_0$ vanishes nowhere.
$\mathcal{P}_0$ seperates points, because for $x \neq y$ in $(0,1)$ we can define $p(t) := (t-a)(t-b)(t-y)$. Then $p(x) \ne 0 = p(y)$.

By the Stone-Weierstraß theorem in the locally compact version the space $\mathcal{P}_0$ is dense in $C_0((a,b))$. Since $f$ is bounded, we can conclude that $\int_a^b f(x)p(x) \, d x =0$ for all $p \in \mathcal{P}_0$ already implies that
$$\int_a^b f(x) g(x) \, dx =0 \quad \text{ for all } g \in C_0((a,b)).$$
Now any indicator function of an interval $[c,d]$ with $a<c<d<b$ can be approximated by a sequence of functions from $C_0((a,b))$. Hence we get
$$\tag{1}\int_c^d f(x) \, dx =0.$$
Now the set $\mathcal{A}:=\{A \in \mathcal{B}((a,b)) \colon \int_B f(x), dx =0 \}$ is a Dynkin-system, which contains a generator of the Borel-$\sigma$-Algebra. Therefore we have already $\mathcal{A} = \mathcal{B}((a,b))$. As known $\int_B f(x) \, dx =0$ for all $B \in \mathcal{B}((a,b))$ implies that $f(x) =0$ almost everywhere. Since $f$ is also continuous and nullsets don't contain any interval, we get already $f(x) =0$ for all $x \in [a,b]$.
Comment: Isn't there a way not to use sub-algebra? I am taking real analysis and want to solve it with that knowledge.
Answer: Lemma: Assume $f$ is continuous on $[a,b]$ and $f(a)=0=f(b).$ Then there exists a sequence of polynomials $p_n$ with $p_n(a)=0=p_n(b)$ such that $p_n\to f$ uniformly on $[a,b].$
Proof: By Weierstrass there are polynomials $q_n$ converging uniformly to $f$ on $[a,b].$ Let $l_n$ be the linear function joining $(a,q_n(a)),(b,q_n(b).$ Then $p_n=q_n-l_n$ does the job.
Proof for the given problem: Given $a<a'<b'<b,$ define $g$ this way: on $[a,a']$ $g$ is the line joining $(a,0)$ and $(a',f(a'));$ on $[a',b'],$ $g=f;$ on $[b',b]$ $g$ is the line joining $(b',f(b'))$ and $(b,0).$ Find polynomials $p_n$ converging to $g$ uniformly as in the lemma. Then
$$0= \int_a^bfp_n = \int_a^{a'}fp_n +\int_{a'}^{b'}fp_n + \int_{b'}^b fp_n $$ $$\to \int_a^{a'}fg+\int_{a'}^{b'}f^2+ \int_{b'}^b fg$$
Now let $a'\to a^+, b'\to b^-$ to see $0=\int_{a}^{b}f^2.$ This proves $f\equiv 0.$
Comment: We have no assumption on $f$ in the problem statement, except its continuity.  How can you assume $f(a)=0=f(b)$?
Comment: Also, could you tell me what you mean by the line joining $(a,q_n(a))$ and $(b,q_n(b))$? Is it $l_n=t(a,q_n(a))-(1-t)(b,q_n(b))$ for all $t \geq 0$?
Comment: I did not assume $f(a)= f(b)=0.$ However, g(a)= g(b)=0,$ so the lemma applies to $g.$ Your second question: What is the equation of the line joining two given points? You know the answer to that.


Scoring an American Football Game?

Question: Is there an analog to baseball's scorecard for football?
http://en.wikipedia.org/wiki/Baseball_scorekeeping
Answer: While it's not really possible to keep score in football like you do in baseball (in baseball you capture a lot of data that would be impossible to capture in football), they do make scorebooks for football games so that you can track various statistics (like you'd track hits, homeruns, strikeouts etc in baseball).
Here is an example a quick search on Amazon turns up. This obviously doesn't have a very good look at what the pages look like, but it appears it has space to track plays through the game (possibly even indicating formation, yardage and how the runner/receiver ran his route).
It should be noted that similar score tracking devices are employed in football (soccer), and basketball. They don't have the same nostalgia factor you see in baseball scorekeeping (I've never seen a picture of a fan in a stadium for any of football, american football or basketball keeping score, whereas its common practice in baseball to distribute score sheets in programs).

Scoring an American Football Game?


HBase create region

Question: I want dynamically add splits to existing table before saving data with keys for new regions.
Is any way available for create HBase region for existing HBase table or Phoenix table with defined start-end region keys or part of keys?
Answer: There is a "split" command in HBase shell.

HBase create region


Transactional Replication from SQL Server 2008 to 2000

Question: I has transactional replication from my server1 (MS SQL 2000) to server2 (MS SQL 2000) in another company (and on different network) and it worked OK. Instead of using real name of server2, I used alias referring to IP address of server2.
Now, I try to set up transactional replication from my server3 (MS SQL 2008) to the same server2 (MS SQL 2000). I can connect to the server2 via SSMS using the same alias name. However, when I try to use it for replication, I got a message that for replication I have to use only real instance name (and the message provides that real name!). But when I try to use it, the message says that the host not found.
So, on the one hand, the server2 is perfectly "visible" and I can query the database from SSMS, but on the other hand it is not "visible" to set up replication.
Any thoughts?
Thank you,
YG
Answer: You need to add a reference to server2 in the DNS that server3 is using.  If you don't want to edit DNS like that then edit the hosts file on server3 and add a reference in to pointing to server2's name and IP address.


If $A$ Is invertible $n\times n$ matrix which is made of only 1's and -1's, then $|\det(A)| \geq 2^{n-1}$.

Question: How do I prove what's written in the title (By saying "made of 1's and -1's" I mean that A contains only the numbers 1 and -1)? I tried using gauss elimination but I don't see how it helps me, and I have no other idea. If any of you could help me or at least give me a hint, It will help me a lot. Thanks!
Comment: I think you want $\;|\det A|\;$ , with absolute value, otherwise the claim is false.
Comment: @SantanaAfton Each row has norm $\sqrt{n}$.  If rows are orthogonal, which gives maximum absolute value of the determinant, then $\lvert\det(A)\rvert=n^{n/2}$, which can be much greater than $n2^{n-2}$.
Comment: @DonAntonio Yep. You are right, my bad. Editing.
Comment: Fun fact: it's also true that $|\det(A)|\le n2^{n-2}$ when $n\ge 2$.
Answer: Hint: Gaussian elimination is definitely (one of) the right way(s) to go. Think about what happens when you've gotten your matrix into upper-triangular form. Can you get $n-1$ factors of $2$ to pop out anywhere and still get the determinant of an integer matrix? Here's a (simple) example:
$$\begin{vmatrix} 1 & 1 & 1 \\ 1 & -1 & 1 \\ -1 & 1 & 1 \end{vmatrix}=\begin{vmatrix} 1 & 1 & 1 \\ 0 & -2 & 0 \\ 0 & 2 & 2 \end{vmatrix}=\begin{vmatrix} 1 & 1 & 1 \\ 0 & -2 & 0 \\ 0 & 0 & 2 \end{vmatrix}=2^2\begin{vmatrix} 1 & 1 & 1 \\ 0 & -1 & 0 \\ 0 & 0 & 1 \end{vmatrix}.$$
Comment: I think you gave me an idea. detA is not 0, since otherwise, A would not be invertible. Let's name the rows of A: R_1,R_2,...,R_n. We'll do the following:                             R_2-->R_2-R_1,R_3-->R_3-R_1,...,R_n-->R_n-R_1. The determinant hasn't changed. Look at the new rows R_1,...,R_n. None of them is all 0's, otherwise detA=0. but each element in them is one of the following sums: 1+(-1), 1+1, (-1)+(-1). So It's 0,2 or -2. So we can factor out 2 out of each of those rows (n-1 factors of 2) and still get an integer matrix, whose determinant is not 0. so we are done. ?
Comment: @Omer yes, you even further simplified the answer, since we don't need to go into the upper-triangular form.
Comment: can you or someone else verify it's right (sorry for not editing and double-commenting, I can't edit, not sure why (maybe I edited too many times?)
Comment: @PetiteEtincelle Okay. Thanks!
Answer: Let $A$ be a matrix with entries $\pm 1$ of size $n>1$. The case $n=1$ is immediate.
We are going to transform $A$ in two steps, without altering
$\,|\!\det A|\,$:
(1) Take the first column and the first row of $A$ to define diagonal matrices
$C=a_{11}\cdot\operatorname{diag}(a_{11},-a_{21},\dots,-a_{n1})\:$ and
$\:R=\operatorname{diag}(a_{11},a_{12},\dots,a_{1n})\,$.
Then $|\!\det C|=|\!\det R|=1$, and multiplying $A$ from the left and the right yields
$$CAR\;=\;\begin{pmatrix}
1&1&\cdots &1\\ -1\\ \vdots &&B\\ -1
\end{pmatrix}$$
where $B\,$ is a submatrix of size $n-1$ with entries from {$\pm 1\}$.
(2) Now let's add the first row in the $CAR\,$ to all the other rows to obtain
$$\begin{vmatrix}
1&1&\cdots &1\\ -1\\ \vdots &&B\\ -1
\end{vmatrix}
\quad=\quad
\begin{vmatrix}
1&1&\cdots &1\\ 0\\ \vdots &&2\cdot B'\\ 0
\end{vmatrix}$$
and $B'$ has entries in $\{1,0\}$. Furthermore, $B'$ is singular iff $A$ is singular (also true if $n=2$).
Reaping the fruit of the preceding steps one has
$$\begin{align}|\!\det A|&\;=\;|\!\det(CAR)|\;=\;2^{n-1}\,|\!\det B'|\\[2ex]
&\;\geqslant\;2^{n-1},\end{align}$$
as claimed for non-singular $A$.


Using Big-O notation?

Question: Is there a difference between $O(n) + O(b)$ and $O(n+b)$ for two variables $n$ and $b$?
Comment: You cannot directly add $O()$ notations. The big O notation describes two functions that asymptotically is the same. It's not a particular value
Answer: When people write things involving arithmetic and big-O notation they are usually speaking loosely. $O(a)$ is a set of functions, so the addition isn't immediately meaningful. It seems probable the authors intend for $O(n+b)$ and $O(n)+O(b)$ to mean the same thing.
Answer: In general the big Landau "O" is used to describe that two functions asymptotically behave identically, i.e.
$$ f(x) = O(g(x)) \; :\Leftrightarrow \; \lim\limits_{x\to x_0} \frac{f(x)}{g(x)}=1 $$
Is this how you have defined it?
Answer: $$f(x)=x=O(x)$$
$$g(x)=-x=O(x)$$
$$h(x)=f(x)+g(x)=0=O(0)\neq O(x)$$
These hold from the definition of $O$

Using Big-O notation?


How can I copy a new version of libc?

Question: I have a computer which is not to be connected to the internet for security reasons. It is running Linux. On a separate computer, I have code and a cross compiler for linux. When I move the program over to the offline Linux computer, I cannot execute it, due to an error " version `GLIBC_2.17' not found "
After checking /lib, I see that I do indeed only have version 2.13 of libc. On my development computer, I have all the relevant files for the 2.22 version which is being used to compile the program. I would like to somehow copy this version of libc on my development computer over to my offline computer so that I can run my program.
The problem is, I cannot seem to copy the files. Attempting to do so gives an error:
mv: error writing './libc.so.6': No space left on device

or something similar. I know this is not actually due to there not being space left on the device, because I don't have much of anything ON the device, and I can copy the files to other places in the filesystem, just not to the /lib directory. How can I migrate my newer version of libc over to the offline computer?
Comment: Does your offline computer has some linux distribution installed, and which one? Can you just update your distribution to newer version with recent enough glibc? (Or compile your program statically and it will run **if** kernel of target PC has all features needed by your glibc.)
Answer:
I would like to somehow copy this version of libc on my development computer over to my offline computer so that I can run my program.

Incorrectly updating libc on your "offline" computer is a very easy way to render it unbootable. You should not attempt this unless you understand what you are doing (which you clearly do not), and unless you know how to restore "offline" computer in case of failure.
The best approach is to use the package manager on the "offline" computer to install libc package correctly (details vary on what package manager is being used).
If the package manager approach doesn't work, you can copy individual files. Hoever note that system ld-linux.so and libc.so.6 must match at all times, or every dynamically linked program (your shell, cp, mv etc.) will break.
Since you need to update two files simultaneously, how could this be done? You need a statically-linked copy of cp. It is best to have a statically-linked copy of $SHELL and ln as well (in case you make a mistake).
Comment: ld-linux and libc.so.6 *must* match *exactly* (come from the same build) because they have private unversioned binary interface between them. Here is an example of errors when they do not match: http://stackoverflow.com/q/847179/50617
Comment: Why `ld-linux.so` and `libc.so` must match? ld-linux should be capable of loading most ELFs, and only misbehave in case of some advanced features like ifunc. Both ld-linux and libc.so can be saved in other place and used (when computer is online) by manual starting of ld-linux and with env variables with path to libc.so...

How can I copy a new version of libc?


Counting Number of Items in a tuple List in Erlang

Question: I have the following List structure:
[{A, [{B <--, [A, C]}, {C <--, [B, A]}]}, {B, [{C <--, [A, C]}]}]

For example, B = 1, C = 2.
What would be the correct way to do so?
UPDATE
I'd like to count the number of <-- (a symbol I added just to show what I'm referring to) pointed item in it.
Comment: Would you mind to elaborate? What's the meaning for this `<--` symbol in your question? Do you want to know how many values/items a list (that may contain tuples) can have?
Comment: @ɐuıɥɔɐɯ hi, <-- is just a symbol I added to show items I wanted to count
Answer: It can be implemented in many ways. Here is one more.
 count(List) ->
    count(List, dict:new()).

count([{_, InList} | Rest], Dict) ->
    count(Rest, count2(InList, Dict));
count([], Dict) ->
    dict:to_list(Dict).

count2([{Symbol, _} | Rest], Dict) ->
    count2(Rest, dict:update_counter(Symbol, 1, Dict));
count2([], Dict) ->
    Dict.

Example Output:
1> test:count([{one, [{b, [123]}, {c,[123]}, {b,[123]}]}, {two, [{b, [123]}, {c,[123]}, {b,[123]}]}]).
[{b,4},{c,2}]

Answer: You can write a simple code using an accumulator and some list functions. Supposing all list elements are of the same format:
count(L) ->
    count (L, []).

count ([], Cases) ->
    Cases;
count ([{_E1, [{X, [_E2, _E3]}]} | Rest], Cases) ->
    NewCases =
        case lists:keysearch(X, 1, Cases) of
            false ->
                [ {X, 1} | Cases ];
            {value, {X, Val}} ->
                lists:keyreplace(X, 1, Cases, {X, 1+Val})
        end,
    count(Rest, NewCases).


Bipartite graph: Average number of cuts for a given partition

Question: Say I have a graph with an even number of nodes. We then randomly connect those nodes. The possible number of combinations boils down to $P=\frac{(2n)!}{2^n n!}$. We now make a partition of length $L$ on the graph, such that $L\in(1,n)$. This partition splits the graph into two subsets, and my question is: Given the randomly connected nodes, how many nodes will a partition cut? I attach a picture that I hope will helps understand the problem.
We define the average number of cuts as $Q(n,L)$. For n=2, we have a 4 nodes graph and there are $P=3$ ways to create edges. However, for the partition L=2, it will only cut the graph in two of the three possible cases. For n=3, there are 15 possible combinations, which I do not draw all of them.
I was able to almost find a general expression for it, $Q(n,L)=(P-x)L+xL$, where $P$ is defined before as the total number of combinations and $L$ is the partition. The problem is that I do not know how to express the factor $x$, nor do I know if this really generalizes.
It seems like a problem known for graph theory and may be related to cuts (https://en.wikipedia.org/wiki/Cut_(graph_theory)), but I am not sure.
Any help would be appreciated.
Edited: As asked in the comments, I attach a picture of all the n=3 possible combinations for L=3 and L=2 (L=1 is the trivial case). Notice how the geometry is a bit different, as they are no longer on a circle, but rather on two sets.
Comment: Maybe worth highlighting that your partition implicitly arises from embedding and choosing a half-space; that is, can't (for example) choose only the left and right nodes in the bottom-right "$u=2$" diagram.
Comment: @JacobManaker I think you are refereing where I put my partition? It is actually arbitrary and does not really matter because we are considering all permutations of edges.
Comment: Do you have all the $n=3$ configurations ? https://en.wikipedia.org/wiki/Chord_diagram_(mathematics) ... Can you make a table of the values you wany to generate ?
Comment: @DonaldSplutterwit I edited the post to add all possible n=3 configurations for L=3 and L=2 (L=1 is the trivial case). And thanks for the reference, it may help me find the answer.
Comment: I would write $P=(2n-1)!!$ (but it's same thing) ... anyway, have a look at OEIS https://oeis.org/A001147
Answer: There are $L\times (2n-L)$ pairs of vertices such that the two vertices are on opposite sides of the cut. For each of these pairs of the vertices, $x$ and $y$, the probability that they are joined by an edge in the matching is $1/(2n-1)$; this is because $x$ is equally likely to be joined to each of the other $2n-1$ vertices.
Therefore, by linearity of expectation, the expected number of edges crossing the cut is
$$
L\times (2n-L)\times \frac1{2n-1}.
$$
This is the expected number of cut edges. The quantity $Q(n,L)$ you are computing is something more like the total number of cut edges over all possible matchings. To go from expected to total, you multiply by the size of the probability space, which is the number of mathcings, equal to $$P = (2n)!/(2^nn!) = (2n-1)(2n-3)(2n-5)\cdots 1:=(2n-1)!!.$$ It follows that
$$
Q(n,L) = L\times (2n-L)\times \frac1{2n-1}\times (2n-1)!! = L\times (2n-L)\times (2n-3)!!
$$
This agrees with what you already found. For example,
$$
Q(3,3) = 3\times 3\times 3!! = 3\times 3\times 3=27\\
Q(3,2) = 2\times 4\times 3!! = 24\\
Q(3,1) = 1\times 5\times 3!! = 15
$$
For a further example,
$$
Q(4,3) = 3\times (8-3)\times 5!! = 3\times 5\times (5\times 3\times 1)=225
$$
Comment: That is the complete answer! Thank you! Still, I am a bit confused, as I was expecting a different answer. The answer I expected was somewhat that, for large n, $Q\simeq \log(L)$ (I checked with Mathematica in this limit they are not the same). I say that because the origin of the problem comes from a known physics result: (https://arxiv.org/pdf/1402.6008.pdf and https://arxiv.org/pdf/cond-mat/0406737.pdf) If you make cuts of length L at a 1D chain made of random pairs, the number of cut bonds goes as log(L).
Comment: Hmm, I am not sure what the reason for the discrepancy is. I glanced at the papers, and noticed that in all of the diagrams, there where never any connections which crossed each other. If the random matching is restricted to noncrossing matchings like this, that would change the analysis, and might produce the $\log L$ result.
Comment: Indeed, one of the papers says "The qualitative picture of the ground state generated in this process shown in Fig. 1 looks like a random arrangements of non crossing singlet pairs occuring at all scales." It might be interesting to see what happens in a uniformly random non-crossing matching (explicitly: choosing each non-crossing matching of $2n$ points with probability $\frac1{C_n}$, where $C_n$ is the $n^{\text{th}}$ [Catalan number](https://en.wikipedia.org/wiki/Catalan_number)).
Comment: @MishaLavrov Could you also guide me on how to do it with the Catalan numbers? I tried and failed at getting it (https://math.stackexchange.com/questions/4615509/how-to-count-pairs-with-catalan-distribution)


Delta option of term field missing in views

Question: So I have a view that's been working for the last year. now suddenly there is a missing broken handler.
Turns out that the missing field is a delta (field) of a term reference field, the term field is still available. Now even when creating a new view i can't add term reference delta
What could possibly be causing this. if someone could just give me a place to start that would be great.
this is the missing field from views export on the staging site.. which still works.. :/
<code>$handler->display->display_options['filters']['delta']['id'] = 'delta';
$handler->display->display_options['filters']['delta']['table'] = 'field_data_field_people_reference';
$handler->display->display_options['filters']['delta']['field'] = 'delta';
$handler->display->display_options['filters']['delta']['relationship'] = 'reverse_field_people_reference_field_collection_item';
$handler->display->display_options['filters']['delta']['value']['value'] = '0';
</code>
Answer: If you accidentally change the amount of values this field takes to one then obviously there will be no delta... side note I am an Idiot


Simple A star algorithm Tower Defense Path Trapped

Question: So first of all I'm in a 100 level CS college class that uses Java. Our assignment is to make a tower defense game and I am having trouble with the pathing. I found from searching that A* seems to be the best for this. Though my pathing get's stuck when I put a U around the path. I'll show some beginner psuedo code since I haven't taken a data structures class yet and my code looks pretty messy(working on that).
Assume that I will not be using diagonals.
while(Castle not reached){
    new OpenList
    if(up, down, left, right == passable && isn't previous node){
         //Adds in alternating order to create a more diagonal like path
         Openlist.add(passable nodes)
    }
    BestPath.add(FindLeasDistancetoEnd(OpenList));
    CheckCastleReached(BestPath[Last Index]);
{

private node FindLeastDistancetoEnd(node n){
    return first node with Calculated smallest (X + Y to EndPoint)
}

I've stripped A* down(too much, my problem most likely). So I'm adding parents to my nodes and calculating the correct parent though I don't believe this will solve my problem. Here's a visual of my issue.
X = impassable(Towers)
O = OpenList
b = ClosedList(BestPath)
C = Castle(EndPoint)
S = Start
OOOOXX
SbbbBX   C
OOOOXX

Now the capitol B is where my issue is. When the towers are placed in that configuration and my Nav Path is recalculated it gets stuck. Nothing is put into the OpenList since the previous node is ignored and the rest are impassable.
Writing it out now I suppose I could make B impassable and backtrack... Lol. Though I'm starting to do a lot of what my professor calls "hacking the code" where I keep adding patches to fix issues, because I don't want to erase my "baby" and start over. Although I am open to redoing it, looking at how messy and unorganized some of my code is bothers me, can't wait to take data structures.
Any advice would be appreciated.
Answer: Yes, data structures would help you a lot on this sort of problem. I'll try to explain how A* works and give some better Pseudocode afterwards.
A* is a Best-First search algorithm. This means that it's supposed to guess which options are best, and try to explore those first. This requires you to keep track of a list of options, typically called the "Front" (as in front-line). It doesn't keep track of a path found so far, like in your current algorithm. The algorithm works in two phases...
Phase 1
Basically, you start from the starting position S, and all the neighbouring positions (north, west, south and east) will be in the Front. The algorithm then finds the most promising of the options in the Front (let's call it P), and expands on that. The position P is removed from the Front, but all of its neighbours are added in stead. Well, not all of its neighbours; only the neighbours that are actual options to go. We can't go walking into a tower, and we wouldn't want to go back to a place we've seen before. From the new Front, the most promising option is chosen, and so on. When the most promising option is the goal C, the algorithm stops and enters phase 2.
Normally, the most promising option would be the one that is closest to the goal, as the crow flies (ignoring obstacles). So normally, it would always explore the one that is closest to the goal first. This causes the algorithm to walk towards the goal in a sort-of straight line. However, if that line is blocked by some obstacle, the positions of the obstacle should not be added to the Front. They are not viable options. So in the next round then, some other position in the Front would be selected as the best option, and the search continues from there. That is how it gets out of dead ends like the one in your example. Take a look at this illustration to get what I mean: https://upload.wikimedia.org/wikipedia/commons/5/5d/Astar_progress_animation.gif The Front is the hollow blue dots, and they mark dots where they've already been in a shade from red to green, and impassable places with thick blue dots.
In phase 2, we will need some extra information to help us find the shortest path back when we found the goal. For this, we store in every position the position we came from. If the algorithm works, the position we came from necessarily is closer to S than any other neighbour. Take a look at the pseudocode below if you don't get what I mean.
Phase 2
When the castle C is found, the next step is to find your way back to the start, gathering what was the best path. In phase 1, we stored the position we came from in every position that we explored. We know that this position must always be closer to S (not ignoring obstacles). The task in phase 2 is thus very simple: Follow the way back to the position we came from, every time, and keep track of these positions in a list. At the end, you'll have a list that forms the shortest path from C to S. Then you simply need to reverse this list and you have your answer.
I'll give some pseudocode to explain it. There are plenty of real code examples (in Java too) on the internet. This pseudocode assumes you use a 2D array to represent the grid. An alternative would be to have Node objects, which is simpler to understand in Pseudocode but harder to program and I suspect you'd use a 2D array anyway.
//Phase 1
origins = new array[gridLength][gridWidth]; //Keeps track of 'where we came from'.
front = new Set(); //Empty set. You could use an array for this.
front.add(all neighbours of S);
while(true) { //This keeps on looping forever, unless it hits the "break" statement below.
    best = findBestOption(front);
    front.remove(best);
    for(neighbour in (best's neighbours)) {
        if(neighbour is not a tower and origins[neighbour x][neighbour y] == null) { //Not a tower, and not a position that we explored before.
            front.add(neighbour);
            origins[neighbour x][neighbour y] = best;
        }
    }
    if(best == S) {
        break; //Stops the loop. Ends phase 1.
    }
}

//Phase 2
bestPath = new List(); //You should probably use Java's ArrayList class for this if you're allowed to do that. Otherwise select an array size that you know is large enough.
currentPosition = C; //Start at the endpoint.
bestPath.add(C);
while(currentPosition != S) { //Until we're back at the start.
    currentPosition = origins[currentPosition.x][currentPosition.y];
    bestPath.add(currentPosition);
}
bestPath.reverse();

And for the findBestOption method in that pseudocode:
findBestOption(front) {
    bestPosition = null;
    distanceOfBestPosition = Float.MAX_VALUE; //Some very high number to start with.
    for(position in front) {
        distance = Math.sqrt(position.x * position.x - C.x * C.x + position.y * position.y - C.y * C.y); //Euclidean distance (Pythagoras Theorem). This does the diagonal thing for you.
        if(distance < distanceOfBestPosition) {
            distanceOfBestPosition = distance;
            bestPosition = position;
        }
    }
}

I hope this helps. Feel free to ask on!
Comment: Thanks for all the info. I started over and implemented with the help of your psuedo code and explanation. Couple of Notes. First your Euclidean Distance just has X values in the psuedo code. I used: 'Math.sqrt(Math.pow(X - EndPoint.x(), 2) + Math.pow(Y - EndPoint.y(),2));' Second I don't believe your method includes assigning new parents or elimination origins in your example I suppose. Unless I missed a step. In my implementation I get a lot of extra paths into closed of U's then it goes back out and finds the correct path. I'm working on assigning new parents.
Comment: Good answer, but it is preferable to be able to assign new parents, as "shorter" paths to closed nodes can be found after the initial discovery -- for example, a shorter backtrack around an obstacle. Closed nodes and their back paths remain relevant since they may be used as parents (back paths) of open nodes still under exploration.
Comment: The Euclidean distance function was indeed wrong. Don't know what I was thinking. Updated it. `Math.pow()` works, but multiplying is faster. It seems that parents (`origins`) can indeed change, according to Wikipedia. My mistake. I hope you figured it out by now.
Answer: Implement the A* algorithm properly. See: http://en.wikipedia.org/wiki/A%2A_search_algorithm
On every iteration, you need to:

sort the open nodes into heuristic order,
pick the best;
-- check if you have reached the goal, and potentially terminate if so;
mark it as 'closed' now, since it will be fully explored from.
explore all neighbors from it (by adding to the open nodes map/ or list, if not already closed).

Based on the ASCII diagram you posted, it's not absolutely clear that the height of the board is more than 3 & that there actually is a path around -- but let's assume there is.
The proper A* algorithm doesn't "get stuck" -- when the open list is empty, no path exists & it terminates returning a no path null.
I suspect you may not be closing the open nodes (this should be done as you start processing them), or may not be processing all open nodes on every iteration.
Use a Map<GridPosition, AStarNode> will help performance in checking for all those neighboring positions, whether they are in the open or closed sets/lists.
Comment: Appreciate the response. "Implement the A* algorithm properly." Yeah I found I can't take shortcuts with algorithms.
Comment: Edited my post to reflect the correct A* algorithm, thinking on my code & realized I had mislead you as to which nodes (just the best one) to explore each iteration. Yes, you do need to implement algorithms correctly -- otherwise they do something else. Hope this helps.  @Spero


Trabalhando com o datepicker no ng-bootstrap

Question: Estou trabalhando com esse exemplo de componente: https://stackblitz.com/edit/angular-ytr3qa
Eu preciso adicionar três recursos.
O primeiro acredito ter a ver com a classe, como nesse exemplo, se o dia estiver fora da data mínima ou máxima permitida, o dia ficaria "desativado", com uma coloração diferente. Minhas tentativas de reproduzir o exemplo acima foram todas falhas.
Deveria ficar mais ou menos assim:

O segundo recurso seria chamar o datapicker apenas quando um botão fosse clicado.
E o terceiro recurso tem a ver com regra de negócio, quando for selecionado o
"dateFrom", eu gostaria de alterar a configuração, para que permitisse selecionar o "dateTo" para no máximo, daqui um mês, a partir da data selecionada no "dateFrom".
Eu tentei fazer o seguinte:
onDateSelection(date: NgbDateStruct, config: NgbDatepickerConfig) {
  if (!this.fromDate && !this.toDate) {
    this.fromDate = date;
    config.maxDate = {year: date.year, month: date.month + 1, day: date.day};
  } else if (this.fromDate && !this.toDate && after(date, this.fromDate)) {
    this.toDate = date;
  } else {
    this.toDate = null;
    this.fromDate = date;
    config.maxDate = {year: date.year, month: date.month + 1, day: date.day};
  }
}

Porém me retorna o seguinte erro:

ERROR Error: Cannot set property 'maxDate' of undefined

Isso também pode ser visto em https://stackblitz.com/edit/angular-ytr3qa
Answer: Para definir uma data máxima, crie uma nova propriedade em sua classe NgbdDatepickerRange:
maxDate: NgbDateStruct;

para evitar repetição de código, crie uma função para adicionar um mês na data inicial:
addMonth() {
  let maxDate = new Date(this.fromDate.year, this.fromDate.month, this.fromDate.day);
  // Define o valor da propriedade `this.maxDate`
  this.maxDate = {
    year: maxDate.getFullYear(),
    month: (maxDate.getMonth()+1),
    day: maxDate.getDate()
  };
}

adicione a propriedade [maxDate]="maxDate" no template:
<ngb-datepicker #dp (select)="onDateSelection($event)" [dayTemplate]="t" [maxDate]="maxDate">

na condição dentro da função onDateSelection chame a função addMonth():
if (!this.fromDate && !this.toDate) {
  this.fromDate = date;
  this.addMonth();
} else if (this.fromDate && !this.toDate && after(date, this.fromDate)) {
  this.toDate = date;
} else {
  this.fromDate = date;
  this.toDate = null;
  this.addMonth();
}

Veja funcionando em stackblitz.com

Para definir o css dos dias desabilitados, adicione a propriedade let-disabled="disabled" no elemento ng-template e [class.disabled]="disabled" no elemento span
<ng-template #t let-date="date" let-focused="focused" let-disabled="disabled">

      {{ date.day }}

</ng-template>

depois adicione no estilo do componente:
.custom-day.disabled {
  background-color: #fff;
  color: #c1c1c1;
}
.custom-day.disabled:hover {
  background-color: #fff;
  color: #c1c1c1;
}

Para exibir quando clicar em um botão, veja um exemplo simples na documentação.


Navbar dentro de uma imagem

Question: Olá, estou fazendo um navbar e queria que todos os botões ficassem dentro de uma imagem dessa forma:
Rodei em um monte de site mas nenhum falava especificamente sobre esse tópico, então se alguém puder me ajudar eu agradeço.
Meu código:

@keyframes pular{
    0%, 20%, 60%, 100%{
        -webkit-transfomr: translateY(0);
        transform: translateY(0)
    }
    40%{
        -webkit-transfomr: translateY(-20px);
        transform: translateY(-20px)
    }
    80%{
        -webkit-transfomr: translateY(-10px);
        transform: translateY(-10px)
    }
}

.pulo:hover{
    animation: pular 1s;
}
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Pokemon Generations</title>
        <link rel="icon" href="Logo/Dream_Poké_Ball_Sprite.png">
        <meta charset="utf-8">
        <meta name="viewport" content="width-device-width, initial scale=1.0">
        <meta name="author" content="Daniel Lucas">
        <meta name="description" content="Tela Inicial do site">
        <meta name="keywords" content="pokémon,bingo,história">
        <link rel="stylesheet" href="estilo.css">
        <link rel="stylesheet" href="node_modules/bootstrap/compiler/bootstrap.css">
        <link rel="stylesheet" href="node_modules/bootstrap/compiler/style.css">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSite">

                </button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Personagens</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Como jogar</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Jogar</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Atualizações</button>

<button type="button" class="btn btn-outline-warning" class="ml-1">Quem Sou</button>

O CÓDIGO ACIMA ESTÁ SEM AS IMAGENS
A imagem que será o navbar:
Comment: Vc que fazer essa barra customizando uma NavBar nativa do Bootstrap? Ou um exemplos simples sem usar o Bootstrap te ajuda? To te perguntando isso pq a NavBar do Bootstrap já vem por default com UM MONTE de CSS original do próprio Bootstrap e esses CSS mais vão atrapalhar do que ajudar a fazer uma Nav tão customizada quanto o que vc quer...  O ideal é vc fazer o seu menu e não usar a Nav original do Bootstrap...
Comment: Eu tô usando o bootstrap mais pelo redimensionamento do que qualquer outra coisa, aí teria como fazer esse menu com algumas classes do bootstrap tipo a navbar-expand-lg?
Comment: Só desenhar a Navbar não é tão complicado, mas fazer ela ficar responsiva que seria mais chato... Vc tem que pensar como vai tratar esse menu em telas pequenas. Mas a minha dica é vc fazer uma barra nova e não usar a NavBar original do Bootstrap pq ela já vem com um monte de CSS que o Bootstrap coloca nela que mais vai atrapalhar do que ajudar! Se vc quiser um exemplo sem usar a Nav do bootstrap posso te dar uma ajuda, mas pra customizar e transforma a Nav do BS nessa Nav, acho que nem vale a pena...
Comment: Pode ser sem a nav do bootstrap então, depois eu me viro pra fazer o redimensionamento
Answer: Estamos aqui para ensinar a pescar e não para entregar o peixe. Então só fiz o lado esquerdo do menu, o lado direito vc faz ;)
Repare que ficou bem flexível, usei flex, e dependendo do tamanho do texto do link vai funcionar bem na maioria das telas...

Primeiro, obviamente eu usei a forma que eu achei mais prática, mas talvez tenha outras melhores
Para o link da ponta esquerda eu usei transform skewX para inclinar nos dos lados do link, e no segundo item da esquerda eu usem um linear-gradiente em 45deg, assim a inclinação fica só em um lado e o outro fica reto. Já para Navbar vermelha no fundo para fazer o angula nos cantos eu usei dois pseudo-elementos, um em cada canto, e cada um deles com um linear-gradiente tb em 45deg com a mesma cor do fundo, branco... Se quiser pode usar sua imagem como background-imagem que não vai mudar muito, depois é só remover os pseudo-elementos do CSS se optar por isso.
O seu dever de casa é fazer agora o lado da direita. Repare que eu não usei nada do Bootstrap, mesmo assim, deixei ele indexado na página, para vc ver que não tem conflito entro o que eu fiz e as classes do BS.

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Page Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />

      link

      link

      link

      link

Comment: ahhh, obrigado cara, me salvou
Comment: @Akali que bom que ajudou, ai no exemplo tem varias técnicas aplicadas, então tem coisas ai que podem te ajudar no futuro em outros layouts. Abs

Navbar dentro de uma imagem


How to use fontawesome icons in angular 13

Question: Itried using font awesome icons But I can't use it. I imported it in  angular.json also but i cn't use it why?
Answer: In order to use fontawesome icons, you need to install the following 3 packages.
"@fortawesome/angular-fontawesome": "^0.7.0",
"@fortawesome/fontawesome-svg-core": "^1.2.28",
"@fortawesome/free-solid-svg-icons": "^5.13.0",

And in the module file, you need to import FontAwesomeModule
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    FontAwesomeModule,
    ...
  ],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

And in the component file, you need to import specific font icon component.
import { faHeart, faComment } from '@fortawesome/free-solid-svg-icons';

export class YourComponent implements OnInit {
    faHeart = faHeart;
    faComment = faComment;
}

Lastly, in the html file you can use this icons.
<fa-icon [icon]="faHeart"></fa-icon>

Hope it could help you.
Comment: but can i use these icons without importing in the  `component.ts` file
Comment: I don't think so. You need to import first.
Answer: I just import font awesome in angular.json file like this:
"options": {
            "styles": [
              "node_modules/@fortawesome/fontawesome-free/css/all.min.css"
            ],
            "scripts": [
              "node_modules/@fortawesome/fontawesome-free/js/all.min.js"
            ]
        }

Then I can use regular font awesome syntax in html, i.ex.

There is 1 problem with that solution - whole font-awesome's code is paste to main style.css which increase file size.


Thread safety of final field

Question: Let's say I have a JavaBean User that's updated from another thread like this:
public class A {

    private final User user;

    public A(User user) {
        this.user = user;
    }

    public void aMethod() {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                ...a long running task..
                user.setSomething(something);
            }

        });
        t.start();
        t.join();
    }

    public void anotherMethod() {
        GUIHandler.showOnGuiSomehow(user);
    }
}

Is this code thread safe? I mean, when the thread that created A instance and called A.aMethod reads user fields, does it see user in the fresh state? How to do it in appropriate thread safe manner?
Note that I can't modify the user class and I don't know if it's thread safe itself.
Answer:
Is this code thread safe? ... does it see user in the fresh state?

Not especially - the fact that user is final in your code makes almost no difference to thread safety other than the fact that it cannot be replaced.
The bit that should change is the instance variable that is set by setSomething. It should be marked as volatile.
class User {
  // Marked `volatile` to ensure all writes are visible to other threads.
  volatile String something;

  public void setSomething(String something) {
    this.something = something;
  }

}

If however (as you suggest) you do not have access to the User class, you must then perform a synchronization that creates a memory barrier. In its simplest form you could surround your access to the user with a synchronized access.
synchronized (user) {
  user.setSomething(something);
}

Added :- It turns out (see here) that this can actually be done like this:
volatile int barrier = 0;
...
user.setSomething(something);
// Forces **all** cached variable to be flushed.
barrier += 1;

Comment: Let's say I can't modify the User class in any way.
Comment: @Behnil - Answer extended.
Answer: marking field as final just means that reference cannot be changed. It means nothing about thread safity of class User. If methods of this class that access fields are synchronized (or use other synchronization technique) it is thread safe. Otherwise it is not.
Answer: final only makes the reference not re-assignable, but if the reference points to a mutable class, you can still alter the state inside that object, which causes thead-unsafe.
Your code is only thread safe if the User class is immutable, I.e. all properties of User cannot be altered outside the object, all references in the class point to other immutable class.
If it is not case, then you have to properly synchronize its methods to make it thread safe.
Answer:
Note that I can't modify the user class and I don't know if it's thread safe itself.

You have to synchronize your access when accessing the User object.
You can for example use the User object to synchronize, so just wrap every access on the user object with something like:
synchronized(user) {
  // access some method of the user object
}

That assumes that the user object is only accessed in your threads asynchronously. Also keep the synchronized blocks short.
You could also build a threadsafe wrapper around the user object. I would suggest that if you have a lot of different calls, the code gets cleaner and better to read that way.
good luck!
Answer: Concerning threading, finalfields are just guaranteed to be consistent in case of constructor escape, since the JSR-133 about Memory Barrier mechanism:

The values for an object's final fields are set in its constructor.
  Assuming the object is constructed "correctly", once an object is
  constructed, the values assigned to the final fields in the
  constructor will be visible to all other threads without
  synchronization.                                                                                In addition, the visible values for any other object
  or array referenced by those final fields will be at least as
  up-to-date as the final fields. What does it mean for an object to be
  properly constructed? It simply means that no reference to the object
  being constructed is allowed to "escape" during construction. (See
  Safe Construction Techniques for examples.)  In other words, do not
  place a reference to the object being constructed anywhere where
  another thread might be able to see it; do not assign it to a static
  field, do not register it as a listener with any other object, and so
  on. These tasks should be done after the constructor completes, not in
  the constructor.

However, nothing ensures automatic thread-safety about any final fields in the remaining object's life (meaning after wrapping class's constructor execution).. Indeed, immutability in Java is a pure misnomer:

Now, in common parlance, immutability means "does not change".
  Immutability doesn't mean "does not change" in Java. It means "is
  transitively reachable from a final field, has not changed since the
  final field was set, and a reference to the object containing the
  final field did not escape the constructor".
Comment: I don't think the given definition for immutability is quite right. If a reference to an object was stored in a `final` field, but some other reference to that object also exists, I don't think the object will be "immutable" from the point of view of any reference *which has not been read or copied from a `final` field*.
Answer: Yes, this is safe. See
Java Language Specification (Java 8) Chapter 17.4.4:

The final action in a thread T1 synchronizes-with any action in another thread T2 that detects that T1 has terminated.
T2 may accomplish this by calling T1.isAlive() or T1.join().

Put this together with 17.4.5. Happens-before Order:

Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second. [..] If an action x synchronizes-with a following action y, then we also have hb(x, y).

So after you call t.join(); in your code you will see the updated changes. Since "the thread that created A instance and called A.aMethod" can impossibly read the value after calling aMethod and before t.join is called (because it is busy with method aMethod), this is safe.

Thread safety of final field


NameError: name 'setupterm' is not defined??? How can I solve it?

Question: NameError: name 'setupterm' is not defined ??
How can I solve it?
File "c:\Users", line 5, in
screen=curses.initscr()
^^^^^^^^^^^^^^^^
Answer: setupterm is one of several terminfo (low-level) functions. PDCurses implements none of those, as noted in its HISTORY.md file:

Eliminated term.h and terminfo.c, and moved mvcur() to move.c. These stub functions, done on request (with others then requesting that I take them away -- can't win), were a misguided attempt to facilitate using PDCurses with certain non-C languages -- which, apparently, they didn't end up actually doing. They're also, regrettably, specified as part of the X/Open curses standard, even though they in effect describe an entirely different interface layer (one on which traditional curses, but not PDCurses, is built).

That note was added for PDCurses 3.7, at the end of 2018.  Earlier versions had a non-functional stub file.


Nodejs/Express/Cookies: how do you set signed cookies with a secret

Question: In my directory i have app.js And Index.htmml ; I am trying to set cookies from App.js; I have tried:-
var express = require('express'),
  app = express(),
  http = require('http'),
  cookieparser = require ('cookie-parser'),
  httpServer = http.Server(app);

app.use(express.static(__dirname + '/data'));

app.get('/', function(req, res) {

 let options = {
        maxAge: 60000, // would expire after 1 minutes
        httpOnly: true,
        signed: true ,
        secret: 'secret'
    }

    // Set cookie

  app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

  res.cookie('cookieName', 'Success', options)

 res.sendFile(__dirname + '/index.html');

});

app.listen(8080);

When i run app.js from Cmd It dissappoints me with this error
Thanks in advance for help
Error: cookieParser("secret") required for signed cookies

Answer: You need to specify a secret key which will be used while signing the cookie.
You can do this by adding the following line to your code.
app.use(cookieparser("secret"));

Answer: According to the snippet, you are using the express-session module like so:
app.use(require('express-session')({ secret: 'keyboard cat', ... }));

That is already saying that you want cookies to be signed. Therefore, in your cookie options you can remove the option signed: true since it will be redundant.
And on a last note, you need to improve that code.


Evaluate integral $\int_{-1}^{1} x^2 \exp(\frac{1}{x^2-1}) dx$

Question: How to evaluate this integral?
$\int_{-1}^{1} x^2 \exp(\frac{1}{x^2-1}) dx$
If possible, I want any solution in elementary/non-elementary functions.
Many thanks.
Comment: [Here](http://math.stackexchange.com/q/145015/97236) is a similar integral, maybe you can use the result there?
Comment: Beside numerical integration, I really do not see any closed form for this one.
Comment: In terms of the [*Meijer G-function*](https://en.wikipedia.org/wiki/Meijer_G-function), we have $I=\dfrac{\sqrt\pi}2G_{1,2}^{2,0}\bigg(1;\displaystyle{5/2\choose0,1}\bigg).$
Answer: By substituting $\cosh^2t=\dfrac1{1-x^2}$ and exploiting the parity of the integrand, we finally
arrive at $I=2\Big[I_2(1)-I_4(1)\Big]$, where $I_k(a)=\displaystyle\int_0^\infty\frac{e^{-a\cosh^2x}}{\cosh^kx}~dx.~$ Also, we notice that
$-I'_2(1)=I''_4(1)=\displaystyle\int_0^\infty e^{-a\cosh^2x}~dx,~$ where the differentiation happens with regard to
the parameter a. Using the fact that $\cosh^2x=\dfrac{1+\cosh2x}2$ along with our knowledge
of Bessel functions, we evaluate the last integral to equal $\dfrac12~K_0\bigg(\dfrac a2\bigg)~\exp\bigg(\!\!-\dfrac a2\bigg).$
Unfortunately, it would seem that the latter's first and second order anti-derivatives cannot
be expressed in terms of Bessel functions. $($I might be wrong, and I hope I am, but so far
I've had no luck in finding such a closed form for them$)$. However, not all is lost, since we
can always count on the Meijer G-function to come to our rescue. Thus, $$I=\dfrac{\sqrt\pi}2~G_{1,2}^{2,0}\bigg(1;\displaystyle{5/2\choose0,1}\bigg).$$ If someone could rewrite this last expression in terms of Bessel or Struve functions, I would
be very, very grateful.


Share login data between two android apps with same credentials

Question: Problem:
I have two Android apps, which use the same login data. The product owners want to enable seamless login between those two apps, meaning that the user should only login into one app and then login into the second app without entering the credentials.
Research possible options:
I read a lot, but I haven't found a solution yet.
One option was to add a sharedUserId to the manifest, but it is said that this only works if no app his been published yet, else the user will no longer have access to his old saved data. As this is the case with one of my apps, this option has been eliminated.
Else I read about AccountManager, which is also suggested in this reddit post, but there are also concerns mentioned, that one should not save a password in the account manager. My apps don't have a token for further authentication, only a password, so I'm not sure if AccountManager is a good choice.
Also I heard that there is the KeyChain Api for system-wide credentials, but I'm not sure yet where the difference is between AccountManager and KeyChain
The newest one I found is Smart Lock, but from the documentation I didn't find out if there is a way to share credentials between apps and not between apps and websites, also as this is a password for a physical device, this is not an option for the product owners to see a Google message indicating that this password is saved somewhere in the cloud.
Question:
After looking into all these possibilities, I still don't know which option would fit my case best. What could be a good choice for saving credentials in my case?
Comment: Found any solution?
Comment: did you found any solution for this ?
Answer: You could implement a Content Provider in which you would be handling entries and updating login status.
You have these possibilities:
User logins App A -> Update Schema X -> Enters app B -> Check Schema -> if field says App A is logged, proceed.
User logins App B -> Update Schema X -> Enters app B -> Check Schema -> if field says App B is logged, proceed.
You have to be aware that logout options could be troubling if you are working online.
Good luck :)
Comment: what do you mean by it could be troubling if I'm working online? sorry if this question seems obvious, but I haven't done anything with content providers yet.
Comment: There could be some kind of syncronization issues. This is the kind of trouble that web devs has a lot.
Bad connection issues are always present. Please, mark as right answer if it fits your needs. :)
Comment: But doesn't it impose any security vulnerability. Can another app access the data stored in the content provider.
Comment: @tiago I'm assuming some session cookie will be stored in content provider, which will be shared between the apps. But is there any possibility other apps can read this data too?
Answer: You can use a Service with Android Interface Definition Language (AIDL) with a query for Android 11 (API level 30)
<manifest package="com.example.app">
  <queries>

    <package android:name="com.example.service" />
  </queries>
  ...
</manifest>