Solve the equation $2^{2x}+2^{2x-1}=3^{x+0.5}+3^{x-0.5}$

Question: Solve the equation $$2^{2x}+2^{2x-1}=3^{x+0.5}+3^{x-0.5}$$
The given equation is equivalent to $$2^{2x}+\dfrac12\cdot2^{2x}=3^x\sqrt3+\dfrac{3^x}{\sqrt3}$$ which is $$\dfrac32\cdot2^{2x}=3^x\left(\sqrt3+\dfrac{1}{\sqrt3}\right)$$ The last equation can be written as $$\dfrac32\cdot2^{2x}=\dfrac{4}{\sqrt{3}}\cdot3^x,$$ or $$\dfrac{2^{2x}}{3^x}=\dfrac{\frac{4}{\sqrt3}}{\frac{3}{2}}\iff\left(\dfrac43\right)^x=\dfrac{\frac{4}{\sqrt3}}{\frac{3}{2}}$$ How do I find $x$ from here, as it is obviously a difficulty for me? What's the approach supposed to be?
Comment: $\dfrac{\frac{4}{\sqrt3}}{\frac{3}{2}}=\frac{4}{3}\frac{2}{\sqrt{3}}=\frac{4}{3}\sqrt{\frac{4}{3}}=(\frac{4}{3})^{\frac{3}{2}}$
Comment: I haven't checked your algebra. If it's right then all you need at the last step is $\log_{4/3}$.
Comment: take $x = t + \frac{1}{2}$  to remove squared roots...comes out $  \left( \frac{4}{3} \right)^t =  \frac{4}{3} $
Comment: Note that both sides are monotone increasing in $x$, with the $4^x$ side dominating eventually.  There is only one intersection which can be found by inspection (with a little effort).
Answer: Alternative approach:

Let $r = \log_2(3).$

Note that $2^a = 2^b \iff a = b.$

Solve the equation $$2^{2x}+2^{2x-1}=3^{x+0.5}+3^{x-0.5}$$

The LHS can be re-written as
$$2^{2x} \times \left[1 + \frac{1}{2}\right] = 2^{2x} \times \frac{3}{2}.$$
The RHS can be re-written as
$$3^{x + 0.5} \times \left[1 + \frac{1}{3}\right] = 3^{x + 0.5} \times \frac{4}{3}$$
$$ = \left(2^{r}\right)^{x+0.5} \times \frac{4}{3} = \left[2^{r \times (x+0.5)}\right] \times \frac{4}{3}.$$
Since the LHS and RHS are equivalent, you know that
$$2^{2x-3} = \frac{2^{2x}}{8} = \frac{\left[2^{r \times (x+0.5)}\right]}{9} = 2^{r \times (x + 0.5 -2)}.$$
Therefore,
$$2^{2x-3} = 2^{r \times \left[x - \frac{3}{2}\right]} \implies $$
$$2x - 3 = r \times \left[x - \frac{3}{2}\right] \implies $$
$$x(2 - r) = 3 - \left[r \times \frac{3}{2}\right] \implies $$
$$x = \frac{3 - \left[r \times \frac{3}{2}\right]}{2 - r} = \frac{3}{2}.$$
Answer: Since your last step then $(4/3)^{x}=(4/3)^{3/2}$ then $x=3/2$ as Sil noticed.
Alternatively, let $x$ be a real number, then
\begin{align*}
2^{2x}+2^{2x-1}&=3^{x+1/2}+3^{x-1/2}\\
\frac{1}{3^{x+1/2}}\left(2^{2x}+2^{2x-1} \right)&=\frac{1}{3^{x+1/2}}\left(3^{x+1/2}+3^{x-1/2} \right)\\
2^{2x}\cdot3^{-(x+1/2)}+2^{2x-1}\cdot 3^{-(x+1/2)}&=3^{x+1/2}\cdot 3^{-(x+1/2)}+3^{x-1/2}\cdot 3^{-(x+1/2)}\\
2^{2x}\cdot3^{-(x+1/2)}+2^{2x-1}\cdot 3^{-(x+1/2)}&=4/3\\
\underbrace{e^{\ln 2^{2x}}\cdot e^{\ln 3^{-(x+1/2)}}}_{(*)}+e^{\ln 2^{2x-1}}\cdot e^{\ln 3^{-(x+1/2)}}&=4/3
\end{align*}
For $(*)$ note that is just $e^{(2x)\ln 2-(x+1/2)\ln 3}:=t$, then the above equation came be written as $\frac{3t}{2}=\frac{4}{3}$, that is, $t=8/9$.
Now, we need to find $x$ into $8/9=e^{(2x)\ln 2-(x+1/2)\ln 3}$. Applying logarithm both sides we have  $(2x)\ln 2-(x+1/2)\ln 3=\ln(8/9)$. Rewriting in order to find $x$ we have $(2\ln 2-\ln 3)x=1/2\ln 3+\ln(8/9)$. Thus ,
$$\boxed{x}=\frac{\frac{\ln 3}{2}+\ln\frac{8}{9}}{2\ln 2-\ln 3}=\boxed{\frac{\frac{1}{2}\ln 3+3\ln 2-2\ln 3 }{2\ln 2 -\ln 3}=\frac{3}{2}}$$


Does async function need to have await inside it even if there is await on the caller of the function?

Question: i have a confusion on how async/await works in JS.
i know await will let the exceution to wait until the awaited function is done
but in this example:
async function myAsyncFunction() {
  console.log("Inside async function");
  await new Promise(function(myResolve, myReject) {
    // "Producing Code" (May take some time)
    setTimeout(() => {
      console.log('setTimeout');
      myResolve();
    }, 3000);
  });
  console.log("Async function resumed");
}

async function callerFunction() {
  console.log("Before calling async function");
  await myAsyncFunction();
  console.log("After calling async function");
}

callerFunction();

its not clear to me why MyAsyncFunction need a promise inside of it for the callerFunction to wait for myAsyncFunction
why this solution doesn't let the excecution wait:
async function myAsyncFunction() {
  console.log("Inside async function");
    setTimeout(() => {
      console.log('setTimeout');
    }, 3000);
  console.log("Async function resumed");
}

async function callerFunction() {
  console.log("Before calling async function");
  await myAsyncFunction();
  console.log("After calling async function");
}

callerFunction();

Comment: *"why this solution doesn't let the excecution wait"* - Because within `myAsyncFunction` no `Promise` is being awaited.  In the second example there's no logic which would cause the `setTimeout` operation to be awaited.  It creates the timeout and immediately returns.
Comment: because setTimeout is asynchronous.... so it is set and forget and the code moves on.
Comment: @SaifOs: What you're missing here is that *within* the `myAsyncFunction` nothing in the second example is being awaited.  Any Promise that you want to await would need to be awaited.  Just calling `await` at the top-level is not going to instruct the code to await anything that may possibly be wrapped in a Promise everywhere in the code.  (And `setTimeout` isn't even Promise-based, so it couldn't be directly awaited even if that was how awaiting worked.)
Comment: @David adding async keyword to a function wraps it implicilty with promise right? so if myAsyncFunction is wrapped with a hidden promise why the callerFunction doesn't wait for the setTimeout to finish. or im missing something here?
Answer: When you mark a function as async:

It returns a promise which resolves to whatever the function returns.
It begins to support the await keyword.

Simply returning a promise is rarely useful. That is a necessary consequence of supporting await.

await sends the function is belongs to to sleep until the promise on the right hand side of the await has resolved.
In the second example:

async function myAsyncFunction() {
  console.log("Inside async function");
    setTimeout(() => {
      console.log('setTimeout');
    }, 3000);
  console.log("Async function resumed");
}

myAsyncFunction:

Logs Inside async function
Passes a callback to setTimeout
Logs Async function resumed

It returns a promise that resolves as undefined (since it is async and there is no return statement).
At some point in the future the timeout triggers the callback function.
At no point does it pause, because there is no await statement (so the log at step 3 above is misleading).


Transformation of the uppercase form of a number into type integer in R

Question: In my dataset, i have variables, where numbers are written in uppercase format.
For example:
18 123 thousand dollars
19123 millon dollars

How using R to transform this format to type integer?
I mean, i need this format.
18 123 000
19 123 000 000

Comment: is it just thousand and million or do you have others? If its only those two then just run `gsub` twice: `gsub("thousand dollars", "000", x)`
Comment: but 18 123 000 is 18 Million 123 thousands... How are you making logic of that?
Comment: yes, you are right, so this data comes from manager in this format! so "thousand dollar"  replace on "000"
Comment: the phrase "millon dollars" replace on "000 000"
Comment: d.b , x is mydata$var?
Answer: options(scipen=999)     //it will prevent long numbers conversion in scientific notation
df= data.frame(amount = c("18 123 thousand dollars","19 123 million dollars"))
df$amount <-  gsub("thousand dollars","000",df$amount)
df$amount <-  gsub("million dollars","000 000",df$amount)
df$amount <-  gsub("billion dollars","000 000 000",df$amount)
df$amount <-  gsub("\\s+","",df$amount)
df$amount <-  as.numeric(df$amount)
df


Using Integration Techniques, how do you manipulate specific trig identities?

Question: I've been working on this problem for the last couple hours, and I simply cannot figure out how to solve it. I've scoured the internet, checked the answer using symbolab and wolfram alpha, and yet I still cannot figure out how to make the connection between the refinements. The original problem is as follows:
$$\int\frac{1}{x^2\sqrt{x^2+9}}dx$$
I identify that this is a tangent substitution, where $x=3\tan\theta$ and $dx = 3\sec^2\theta$. After some manipulation and cancelation, I am left with:
$$\frac{1}{9}\int\frac{\sec\theta}{\tan^2\theta}\;d\theta$$
I know I am at the right spot at this point from checking symbolab, but I simply cannot figure out how to carry on from here. I've tried using the identity $\tan^2\theta = \sec^2\theta-1$, and i've also tried using a power reducing formula on $\tan^2\theta$, to no avail. Symbolab shows a refinement from this point:
$$\frac{1}{9}\int\frac{\sec\theta}{\tan^2\theta}\;d\theta = \frac{1}{9}\int\frac{1}{sin\theta}\cot\theta\;d\theta$$ but this makes absolutely no sense to me. I've spent about an hour messing around with identities but I simply cannot figure out how they came to this conclusion. My trig is a bit rusty but i'm working hard to get better at it, but after much trial and error I simply cannot figure it out. How is this conclusion reached? Should I have tackled this problem in a different manner? Any help would be appreciated as I would like to know how to solve this for future reference. Asking you folks has been my last resort. Thanks in advance.
Answer: If your problem is the last step, note that:
$$
\frac{\sec \theta}{\tan^2 \theta}=\frac{\frac{1}{\cos \theta}}{\frac{\sin^2 \theta}{\cos^2 \theta}}=\frac{1}{\frac{\sin^2 \theta}{\cos \theta}}=\frac{1}{\sin \theta}\frac{\cos \theta}{\sin\theta}=\frac{\cot \theta}{\sin \theta}
$$
Comment: Thanks, that was exactly what I was looking for. Not sure why that was so hard for me to see, but that breakdown helps me visualize it. Now I must simplify further and sub out for theta, which i think I can manage. Ty again.


Any way to see HashCode of primitive types?

Question: Mugging up basic D.S....I read that, no hashCode() method for primitive type int is available and if called on int, it will throw error

error: int cannot be dereferenced

Does this means that if int n = 10 then its HashCode will also be 10??
If i still need to see hascode for int in below program, is there a method to see it, like Integer Wrapper???
public static void main(String []args){
       String me = "hello";
       int n = 10;

       int h1 = me.hashCode();
       int h2 = n.hashCode();

       System.out.println(h1);
       System.out.println(h2);
     }

Comment: You get the error "int cannot be dereferenced" because *int cannot be dereferenced* :)
Comment: @ᴍarounᴍaroun : haha..yeah..i guess that sums up the answer for me....thankx mate!! :)
Comment: Can I ask why you want to know this? Note that there is no standard the requires a `hashCode()` to be a certain value even for non-primitive types. An implementation can probably return constant value, say `0` for `hashCode()` for *all* objects and still be compliant.
Comment: @MiserableVariable : m just learning this and read the `hashcode()` method in the libraries, out of curiosity, wanted to see the output, so that,i may implement some basic `hashcode` method on my own.....do i make sense to u?? :)
Comment: I am afraid not. The only real use of hashCode is as hashing function.
Comment: @MiserableVariable : but to understand anything, you should know the basics of its building element too...right??? I m just trying to get my base here....`real use` i understand, but ( *just for example* ) before compiling a program its always good to know little bit about compilers too..m working on this logic....now do i make sense?? :D
Comment: It makes perfect sense. You should try to find out how hashing functions work and how they provide constant time lookups. From there, you can go on good and bad hashing functions. Wikipedia has some good articles. Java's implementations are I believe very good but it is more important to understand how hashing works then to understand how hashCode is implemented.
Answer: You cannot invoke methods on primitive types.
n is declared as int. It does not have methods.
It does not make sense to think like

If i still need to see hascode for int in below program

You could create an Integer object and get its hashCode()
Integer.valueOf(n).hashCode()

Integer#hashCode() is implemented as
public int hashCode() {
    return value;
}

where value is the int value it's wrapping.

Does this means that if int n = 10 then its HashCode will also be 10??

The int doesn't have a hashcode. Its Integer wrapper will however have the value of the int it's wrapping.
Answer: New Convenience Methods (Java 8)
Java 8 brought static methods to more conveniently generate a hash code for primitive values. These methods are stored on the primitive equivalent class.
Mentioned in this discussion with bondolo (Mike Duigou?), one of the OpenJDK developers, talking about how Google Guava has influenced the core libraries in Java.

In Java 8 examples of small Guava inspired JDK additions include static hashCode methods added to the primitive types.

Boolean.hashCode
Integer.hashCode
Float.hashCode

…and so on.
Answer: Only Objects have methods. Not primitives. You might want
 int h2 = new Integer(n).hashCode();

Just create an Wrapper of int and invoke method on it.
Answer: Simple answer is int is not a Java object and there is not such thing call hashCode() for int.
Answer: int is not an Object. It doesn't have methods.
If you want some idea of how the Integer class works, you can Grep Oracle's Java code:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Integer.java#Integer.hashCode%28%29
In particular, this confirms that the return of hashCode() for an Integer object is indeed its underlying integer value.
Answer: int is not an object in Java. It is a primitive data type. However, you can use Integer class to get the hashcode of an int.
System.out.println(new Integer(n).hashCode());

Hope this helps.
Answer: It does not make sense for primitives to have hash codes. They themselves are the best hash codes you can ask for.
Integer hash code is implemented to redundantly return the value itself, so that when used in a java.util.HashSet for example, it maps to itself.
public int hashCode() {
    return value;
}


How do I troubleshoot a jQuery/AJAX issue?

Question: On a current Drupal Commerce installation, I just started experiencing issues where a field is not updating after a jQuery click event.
When a user selects an option, the price typically updates for several of the products on our store. When adding the item to the cart, the correct price is shown. (While helpful on my end that the customer is being charged the right price, it's not great that they cannot see the right price until it is in the cart.)
Everything was working well. No updates were pushed for our distribution and added modules, but this feature is no longer working.
From the Chrome Console, I pulled the error msgs below. How do I troubleshoot? Should I just restore a backup?
ui.spinner.min.js:7 Uncaught TypeError: Cannot read property 'msie' of undefined
at ui.spinner.min.js:7
at ui.spinner.min.js:22

jquery.formalize.js:13 Uncaught TypeError: Cannot read property 'msie' of undefined
    at jquery.formalize.js:13
    at jquery.formalize.js:135
commerce_kickstart_product_ui.js:6 Uncaught TypeError: $(...).spinner is not a function
    at Object.attach (commerce_kickstart_product_ui.js:6)
    at Object.<anonymous> (drupal.js:76)
    at Function.each (jquery.min.js:4)
    at Object.Drupal.attachBehaviors (drupal.js:74)
    at HTMLDocument.<anonymous> (drupal.js:504)
    at c (jquery.min.js:4)
    at Object.fireWith [as resolveWith] (jquery.min.js:4)
    at Function.ready (jquery.min.js:4)
    at HTMLDocument.q (jquery.min.js:4)

Comment: Disable admin_menu or jquery_update - admin_menu makes use of jQuery.browser which was deprecated some time back, jquery_update updates your jquery version to one after it was deprecated
Comment: @Clive - I disabled jquery_update and now my AJAX and jQuery are working well together. Should I have received an admin ping that jquery_update was deprecated? Why would this have been triggered in the last couple days, instead of months back? Seems a little strange. I have also been working on creating new views using Owl Carousel, which requires jquery_update. There are 520k+ sites using jquery_update & 22k sites using Owl, so curious about this fix.
Comment: *jquery.browser was deprecrated
Comment: jquery.browser was deprecated in jQuery, not in the jquery_update module. If you change the version of jQuery being used, you have to work with whatever that version introduces or deprecates.
Answer: It is because you are using jQuery 1.9 or superior.
To fix it, use jQuery Update version 7.x-3.0 and enable the jQuery Migrate plugin.


Installation of module node-red-node-arduino failed:

Question: I am trying to install the node-red node-arduino through the Manage Palette install feature as outlined in the node-red website instructions. Node-red is installed on my Windows 10 PC and I have an Arduino connected through a USB COM port. The Arduino has Standard Firmata loaded to the board. When I try to install the arduino-node I get a lengthy error message, that seems to be unsuccessfully searching for Python, although nothing in the requirements for the node-arduino mentions Python. Here is the error message:
prebuild-install WARN install No prebuilt binaries found (target=14.16.1 runtime=node arch=x64 libc= platform=win32)
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python checking if the py launcher can be used to find Python 2
gyp ERR! find Python - "py.exe" is not in PATH or produced an error
gyp ERR! find Python checking if Python is C:\Python27\python.exe
gyp ERR! find Python - "C:\Python27\python.exe" could not be run
gyp ERR! find Python checking if Python is C:\Python37\python.ex...

Note: above is the error message, not code, but had to mark it as such to get post accepted
I am new to Node-Red, so any assistance is greatly appreciated.
Answer: Python is a requirement for any nodejs package that has to build a native component. In this case it will need to build the node-serial module in order to access the COM port. You will need to install a supported version of Python in order to get this to work.
Comment: I was finally able to install node-arduino. Thanks so much for your assistance!!
Comment: @Hawkeyeknight https://stackoverflow.com/help/someone-answers
Comment: Facing the same issue. Can you please elaborate the answer please
Comment: @spd What more do you need? You need to have python installed on the machine in order to install the required pre-requist node, node-serial. The error message in the original question is pretty clear.


Which subspace (column space, row space, null space, left null space) of A is x a part of?

Question: Which of the four subspaces contains $x$, for the given equation:
$$A^T Ax=A^Tb$$
where $b$ is a column vector NOT in the column space of $A_{m\times n}$. (This equation is to find the best solution for $Ax=b$). Also, $A$ is assumed to have independent columns.
(Question is from one of the MIT OCW problem sets.)
My attempt: Null space of $A$ is just the zero vector. So $\mathbb R^n$ is entirely the row space. Since $x$ has to be a $n\times 1$ vector, it belongs in the row space.
Is there any other more intuitive way to visualize this? Can I generalize this to any $Ax=b$ also, if rank $=n$ for $A$?
Answer: Well, to me your attempt is as intuitive as it gets. Just a remark: you assumed that $m\neq n$ to conclude that $x$ can't be in the column space or left null space, which a priori is not given (at least, it wasn't stated in the question). But this is ok, since, if $m=n$ and $A$ has independent columns, $A$ would be an invertible square matrix, and $A^TAx=A^Tb\implies Ax=b$, but, since $b$ is assumed not to be in the column space of $A$, this case doesn't happen.
Maybe what you're asking for is a more explicit explanation? If so, Let $A=\begin{bmatrix}L_1 \\ \vdots\\ L_m\end{bmatrix}$, where $L_i$ is the $i$-th line, a $1\times n$ vector. If $b=\begin{bmatrix} b_1 \\ \vdots\\ b_m\end{bmatrix}$, we have that
\begin{align*}
A^TAx=A^Tb&\implies \begin{bmatrix} L_1 & \cdots & L_m\end{bmatrix}\begin{bmatrix}L_1 \\ \vdots\\ L_m\end{bmatrix}\textbf{x}=\begin{bmatrix} L_1 & \cdots & L_m\end{bmatrix}\begin{bmatrix} b_1 \\ \vdots\\ b_m\end{bmatrix}\\
&\implies(L_1\cdot L_1+\dots+L_n\cdot L_n)\textbf{x}=b_1L_1+\dots+b_mL_m\\
&\implies\textbf{x}=\dfrac{1}{L_1\cdot L_1+\dots+L_n\cdot L_n}(b_1L_1+\dots+b_mL_m)
\end{align*}
So $\textbf{x}$ is indeed in the row space of $A$ (notice that the denominator of the fraction is clearly non-zero).
Answer: Your solution is already perfectly simple. By the four subspaces theorem, $x$ can be written as $x = x_1 + x_2$, where $x_1 \in R(A^T)$ and $x_2 \in N(A)$. But the null space of $A$ is trivial, so $x_2 = 0$ and $x \in R(A^T)$.


Salvar imagem no banco de dados e dar restore no banco de dados com PostgreSQL

Question: Qual é a melhor maneira para salvar imagem no banco de dados PostgreSQL?
Atualmente tenho uma OID para salvar, eu consigo utilizar normalmente, tanto para salvar e para recuperar, porém quando vou dar restore na minha base de dados, ocorre o seguinte erro
pg_restore: [arquivador (bd)] Erro ao PROCESSAR TOC:
 pg_restore: [arquivador (bd)] Erro no registro do TOC 583; 1247 49153 DOMAIN lo
 postgres
 pg_restore: [arquivador (bd)] could not execute query: ERROR:  type "lo"
 already exists
    Comando foi: CREATE DOMAIN lo AS oid;
Isso porque estou fazendo o restore pelo proprio pgadmin 9.4, e quando eu tento dar restore na minha aplicação C# também não funciona. Existe outra maneira de salvar a imagem no banco de dados ou alguma maneira de dar restore para que isso funcione?
Comment: eu uso colunas `bytea` e tanto o dump quanto restore, faço pelos executaveis do próprio postgresql, `pg_dump` e `psql`
Comment: Mas como funciona? quando você recupera a imagem ela volta em byte e então você converte ela para image? do jeito que eu estou fazendo quando recupera a imagem tenho que informa um caminho para onde ela tem que ir por exemplo c:\imagem\ ... você pode me mostrar como é feito com bytea? envie como resposta que eu aceito :)
Comment: Certo, vou colocar como faço, porém agora estou no celular, assim que possível coloco, vlw
Comment: Obrigado, e no caso a coluna da tabela no pg é a bytea?
Comment: Sim, isso mesmo
Comment: Certo, estou no aguardo de sua resposta
Answer: Conforme falei nos comentários, utilizo a coluna como bytea (byte array) que pode armazenar não somente imagens, mas também arquivos de qualquer formato.
Segue o código conforme eu utilizo, porém este que coloco é apenas um exemplo utilizando a biblioteca System.Data.ODBC do .NET. Foi descartado outros trechos irrelevantes para a situação, focando apenas na seleção, inserção e atualização da coluna em bytea. Caso utilize outro método para conexão com o banco, é bem similar e acredito que não terá problemas com converter o código para sua realidade.
Uma Classe Para o objeto de exemplo:
 public class Cadastro
 {
    public byte[] Foto { get; set; }
 }

Uma Classe onde se teria a comunicação com o banco:
public class CadastroRepositorio
{
    public List<Cadastro> Select()
    {
        List<Cadastro> retorno = new List<Cadastro>();
        string sql = @"Select foto from tabela where id = 1;";
        using (OdbcConnection conexao = new OdbcConnection("string de conexao"))
        {
            conexao.Open();
            using (OdbcCommand cmd = new OdbcCommand(sql, conexao))
            {
                using (OdbcDataReader dr = cmd.ExecuteReader())
                {
                    Cadastro obj;
                    while (dr.Read())
                    {
                        obj = new Cadastro();
                        obj.Foto = new byte[0];
                        obj.Foto = (dr[0].ToString().Length != 0 ? (byte[])dr[0] : obj.Foto);
                        //obj.Foto = (dr["foto"].ToString().Length != 0 ? (byte[])dr["foto"] : obj.Foto);
                        retorno.Add(obj);
                    }

                    dr.Close();
                }
            }
            conexao.Close();
        }
        return retorno;
    }

    public int Insert(Cadastro obj)
    {
        int r = 0;
        string sql = @"insert into tabela (foto) value (?);";
        using (OdbcConnection conexao = new OdbcConnection("string de conexao"))
        {
            conexao.Open();
            using (OdbcCommand cmd = new OdbcCommand(sql, conexao))
            {
                OdbcParameter param = new OdbcParameter("foto", OdbcType.Binary);
                param.Value = (obj.Foto == null ? null : ( obj.Foto.Length == 0 ? null : obj.Foto));
                cmd.Parameters.Add(param);
                r = cmd.ExecuteNonQuery();
            }
            conexao.Close();
        }
        return r;
    }

    public int Update(Cadastro obj)
    {
        int r = 0;
        string sql = @"update tabela set foto = ? where id = 1;";
        using (OdbcConnection conexao = new OdbcConnection("string de conexao"))
        {
            conexao.Open();
            using (OdbcCommand cmd = new OdbcCommand(sql, conexao))
            {
                OdbcParameter param = new OdbcParameter("foto", OdbcType.Binary);
                param.Value = (obj.Foto == null ? null : (obj.Foto.Length == 0 ? null : obj.Foto));
                cmd.Parameters.Add(param);
                r = cmd.ExecuteNonQuery();
            }
            conexao.Close();
        }
        return r;
    }
}

Por fim, caso necessário pode-se converter o byte[] para uma Image utilizando a seguinte função: (Esta não é de minha autoria)
    ///
    /// Converte um array de bytes em um objeto System.Drawing.Image
    ///
    /// <param name="pic">byte[]</param>
    /// <returns>System.Drawing.Image</returns>
    public static Image ConvertByteToImage(byte[] pic)
    {
        if (pic != null)
        {
            try
            {
                MemoryStream ImageDataStream = new MemoryStream();
                ImageDataStream.Write(pic, 0, pic.Length);
                ImageDataStream.Position = 0;
                pic = System.Text.UnicodeEncoding.Convert(Encoding.Unicode, Encoding.Default, pic);
                System.Drawing.Image img = System.Drawing.Image.FromStream(ImageDataStream);
                return img;
            }
            catch
            {
                return null;
            }

        }
        else return null;
    }

E a função reversa, para converter uma imagem para byte[]:
    ///
    /// Converte um objeto System.Drawing.Image em um array de bytes
    ///
    /// <param name="foto">System.Drawing.Image</param>
    /// <returns>byte[]</returns>
    public static byte[] ConvertImageToByte(System.Drawing.Image foto)
    {
        if (foto == null)
            return null;
        Bitmap bmp = new Bitmap(foto);
        MemoryStream stream = new MemoryStream();
        bmp.Save(stream, ImageFormat.Png);
        stream.Flush();
        byte[] pic = stream.ToArray();
        return pic;
    }

Agora a parte do backup e restore:

Para fazer o backup, utilizo o seguinte comando:
C:\Progra~2\PostgreSQL\9.1\bin\pg_dump -h [host] -p 5432 -U postgres --inserts -c -f D:\PostgreSQL\Backups\[arquivo de backup].dump [nome database]

Para fazer o restore, utilizo o seguinte comando:
C:\Progra~2\PostgreSQL\9.1\bin\psql -U postgres -d [nome database] -f D:\PostgreSQL\Backups\[arquivo de backup].dump

Funciona perfeitamente, não só para imagens como também para arquivos (.doc, .zip, .exe, etc). Espero ter ajudado.
Obs.: Trabalho em ambiente Windows
Comment: Obrigado pela ajuda, eu utilizo C# WPF, precisei fazer algumas modificações mas deu certo com base no que você me passou aqui, porém ao salvar no banco de dados ocorre um problema pois minha biblioteca é diferente da sua e não conta com a OdbcType.Binary, caso consiga me ajudar https://pt.stackoverflow.com/questions/236577/problema-ao-inserir-bytea-no-postgresql
Comment: Você poderia me ajudar a realizar o restore? https://pt.stackoverflow.com/questions/237419/problemas-ao-restaurar-uma-base-de-dados-em-postgresql-com-c
Comment: =] feliz em ajudar. Sobre o outro problema, já respondi o que acredito ser. vlw
Comment: Depois que você monta a string para o backup ou restore como você executa ela ?
Comment: Por exemplo, eu tenho um software e instalado ele em clientes diferentes, e nem sempre o meu postgreSQL fica com o mesmo caminho, você deixa sempre estático ou faz algo para o sistema encontre o local onde está o banco?
Comment: Particularmente, tenho isso em arquivo de lotes, os famosos `.bat` que executam pelo agendador de tarefas do windows. Por dentro da aplicação você pode executar pela classe `system.diagnostics.process.start()`
Comment: Quando você usa Progra~2 com isso é possivel referenciar os dois arquivos de programas?
Comment: não... isso é o padrão de nomes do windows, quando utiliza-se a linha de comando. Como há duas pastas, `Program Files` e `Program Files (x86)` a primeira, fica como `Progra~1` e a segunda como `Progra~2`. Se houvesse uma terceira pasta, ficaria como `Progra~3`. Para ver esses nomes, digite `dir /x` na linha de comando


Replace no-phone symbols from phone in jquery with regexp

Question: I got phone number in div with id=phoneNumber in format +7 (999) 999-9999
I need to replace symbols: '(',')',' ','-' in it.
I'm trying to do it like this:
phone=$('#phoneNumber').html();
phone=phone.replace('/[\s|\(|\)]/g','');

For some reason this doesn't replace anything. What's wrong? Are there better ways to implement it?
Answer: You need to remove quote from regex:
phone = phone.replace(/[\s()]/g, '');

Also there is no need to escape ( and ) inside character class nor is the need to use pipe for alternation.
Comment: Thanx, as site allows me, I'll approve your answer.


How do I capture a price with thousand and decimal separator with regex in python

Question: I currently have a code working but the only flaw is that I did'nt set the regex python code in the optimal way.
The original text contains an amount in thousands hundred thousands and millions. With no decimal. I mean it has decimal but always ",00".
Example line in Text:

Debt 1 of 2 for an amount of: $ 58.610,00, Unpaid

Right now with the following code is capturing millions fine but less than 100,000 is skipping one digit.
regex = r"(\d+).(\d+).(\d+),(\d+)"
            match = re.search(regex, line, re.MULTILINE)
            print = "$"+match.group(1)+match.group(2)+match.group(3)

It captures like this:

$5860

But target is like this:

$58610

If the amount is in millions it captures fine, I had to do it like that because the currency that I'm working with it has big amounts. So I constantly manage those kind of quantities.
Regards
Answer: You can use the following regex to extract your expected matches and remove the thousand separator afterwards:
\$\s?(\d{1,3}(?:\.\d{3})+)(?:,\d+)?(?!\d)

You need to get Group 1 value,  remove periods from it and reappend $ at the start. See the regex demo. Details:

\$ - a $ char
\s? - an optional whitespace
(\d{1,3}(?:\.\d{3})+) - Group 1: one to three digits, and then one or more occurrences (since you only want to match thousands and more) of . and three digits
(?:,\d+)? - an optional sequence of a comma and one or more digits
(?!\d) - no digit is allowed immediately on the right.

See the Python demo:
import re
text = 'Debt 1 of 2 for an amount of: $ 58.610,00, Unpaid'
match = re.search(r'\$\s?(\d{1,3}(?:\.\d{3})+)(?:,\d+)?(?!\d)', text)
if match:
    print(f"${match.group(1).replace('.', '')}")

# => $58610

Comment: You're the man! This works Perfect! Thank you very much. I appreciate it


How to retrieve Glass XE version number?

Question: How can I retrieve information about Google Glass with GDK, e.g. which software update is currently installed on Google Glass ?
Answer: You can do this via adb
<code>adb shell getprop ro.build.version.glass
//XE12

adb shell getprop ro.build.version.release
//4.0.4
</code>
To get it programmatically IE (if XE10) do this else if (XE12)...
Follow this lead Get application version programmatically in android


Running commands inside Docker Container

Question: I created a docker container (debian:jessie) inside a fedora 21 vm(running on vmware fusion). first time when i entered vm and ran commands it works fine. i exit the vm and start again and attach to it ( docker start -a dev-001) and run few commands they just hung. not able to find the root cause any one has any clue ? i am able to successfully enter/attach the container but simple command like ps just gets hung.
any suggestions ?
Comment: I found the problem. i should run with -i when using docker start also.
Comment: This helped me strangely even though I could have sworn I used this exact same command and it wasn't starting my container for me. Maybe I got it confused for `docker run`.
Answer: You are able to execute commands in an running container with docker exec. This allows you to execute command even when the container is started in detached mode. If you want to run just some commands and then close the container again you can use docker start -i.


Showing a relation is transitive

Question: Problem:
Let $A = \{(a,b)\}$, determine whether the relation $R = \{(b,a)\}$ is transitive.
Claim:
No, $R$ is not transitive.
Proof:
Since $a,b\in A$ and $a\in R$ but $b,a\notin R$.
I am not sure if this is a sufficient proof. Any suggestions would help.
Comment: Do you mean $A = \{a, b\}$, a two element set containing $a$ and $b$, instead o the one element set $\{(a, b)\}$ containing the single ordered pair $(a, b)$?
Answer: Well, it is transitive (with $A=\{a,b\}$). The definition is
$$\forall a,b,c\in A: aRb \wedge bRc\Rightarrow aRc$$
where $R\subseteq A\times A$.
The point is that if the premise is not fulfilled, the relation is transitive (since then the implication becomes true).
For instance, $R=\{(a,b)\}$ (where $A=\{a,b\}$) and $R=\{(a,b),(a,c)\}$ are all transitive, but $R=\{(a,b),(b,c)\}$ is not since $(a,c)$ is missing.

Showing a relation is transitive


Finding the sides of a right triangle given sine and one side length

Question: The Question:
Consider a right triangle with a side of length x opposite angle A, a side of length y opposite angle B,  and a hypotenuse of length z opposite the right angle. If sinB= 1/√3 and x=4, find the length of the other side (y) and the length of the hypotenuse (z).
Explanation:
This is how I sketched the problem
right triangle diagram
It seems to me that the question has already gave us the value of y and z because sinB = opposite/hypotenuse = 1/√3 = y/z
When I enter 1 as the value for y and √3 as the value for z, I get the answer wrong.
What's the correct way to solve this problem? What am I not getting?
Comment: $y/z = 1/\sqrt 3$ does not imply that $y=1, z=\sqrt 3$. You current diagram violates Pythagoreas' Theorem (and the triangle inequality); you need to account for the scaling.
Comment: how do I account for scaling or what is the correct way of looking at this problem?
Comment: It does violate the Pythagorean theorem
Answer: From $\sin B = \frac1{\sqrt 3} = \frac yz$ we have $z= \sqrt 3 y$.
By Pythagoreas' Theorem, we have $x^2+y^2=z^2$.
Hence:
$$16 + y^2 = (\sqrt3 y)^2 = 3y^2$$
This gives $y^2 = 8 \leadsto y = 2\sqrt 2, z = 2\sqrt 6$.
Comment: Can you help me understand the first line you wrote?
Comment: $\sin B = 1/\sqrt 3 = y/z$ is what you wrote. I simply multiplied both sides by $z\sqrt 3$.
Comment: I don't get how you got √3y
Comment: I got it, you rock!


Getting error for drush site-install :Unable to find a matching SQL Class

Question: I have created a drupal project using composer:
composer create-project drupal-composer/drupal-project:8.x-dev ./ --stability dev -vv

Then I downloaded drush using this command:
composer global require drush/drush

Now I try to install the drupal site using this drush command:
drush si standard --db-url=mysql://***:***@localhost/recommande_db --site-name=***** --account-name=*** --account-pass=*** --account-mail=*****

I'm getting this error:
exception 'Drush\Sql\SqlException' with message 'Unable to find a matching SQL Class. Drush cannot find your[error]

database connection details.' in

/Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/sql/sql.drush.inc:588

Stack trace:

#0 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/sql/sql.drush.inc(573):

drush_sql_get_class(Array)

#1

/Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/commands/core/site_install.drush.inc(117):

drush_sql_get_class()

#2 [internal function]: drush_core_pre_site_install('standard')

#3 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(366):

call_user_func_array('drush_core_pre_...', Array)

#4 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(217):

_drush_invoke_hooks(Array, Array)

#5 [internal function]: drush_command('standard')

#6 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/command.inc(185):

call_user_func_array('drush_command', Array)

#7 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67):

drush_dispatch(Array)

#8 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/includes/preflight.inc(66):

Drush\Boot\BaseBoot->bootstrap_and_dispatch()

#9 /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendor/drush/drush/drush.php(12): drush_main()

#10 {main}

I tried all the suggestions found in several forum but no solution.
Can you help please!
For your information here the result of the "drush status" command:

PHP executable         :  /usr/bin/php

 PHP configuration      :

 PHP OS                 :  Darwin

 Drush script           :  /Applications/MAMP/htdocs/dev.recommandemoi.ma/vendo

                           r/drush/drush/drush.php

 Drush version          :  8.1.2

 Drush temp directory   :  /tmp

 Drush configuration    :

 Drush alias files      :

Comment: Make sure you have php_mysql installed (e.g. `dpkg -l | grep php` on ubuntu)
Comment: both php and mysql are installed. I'm using mac os and the php already installed in the os. I'm also using mysql of phpmyadmin
Answer: Make sure that you execute drush from the web folder.
Comment: I would prefer saying "within the **Drupal** folder"
Comment: yes it's the "web" folder in my case since I've created with composer create


Passar valores de um Objeto para outro form C#

Question: Tenho um sistema, onde após o usuário fazer login, eu puxo de um XML vários dados sobre ele e guardo em atributos de um objeto, porém existe um outro form para fazer a alteração de senha ,onde eu necessito do User_ID do primeiro form... Como eu consigo passar valores de um objeto para outro form no c#? Obrigado
Answer: Olá, acredito que variáveis globais são a solução para isso:
public class Main
{
    public static string User_ID { get; set; }
}

uma variável public static(global) pode ser chamada em outros forms da aplicação com o nome da classe e seu nome:
Main.User_ID

para mais detalhes pesquise sobre tipos globais.
Comment: Muito obrigado!
Answer: Você pode criar uma propriedade do tipo da sua classe no formulário que deseja receber o objeto e passar o objeto no construtor dor formulário, veja um exemplo abaixo.
Formulario que vai receber o objeto:
public partial class Form2 : Form
{
    private User user;

    public Form2(User user)
    {
        InitializeComponent();

        this.user = user;
    }
}

E o formulário que vai enviar o objeto para o formulário que ele esta chamando:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        User user = new User
        {
            User_ID = 1,
            Name = "Fulano",
            Email = "firstname.lastname@example.com"
        };

        var form = new Form2(user);
        form.Show();
    }
}

Desta forma você pode manipular os valores do seu objeto dentro do formulário sem qualquer tipo de interferência.


How to read external file into a variable for post-build events in Visual Studio?

Question: Is there a way to read the contents of an external file into a variable in a Visual Studio post-build event?
The reason I want to do this is that we're going to want a post-build event that every developer runs to copy a built assembly to a certain local UNC path, but each developer will likely have a different UNC path.  So we can't hardcode the path into the project file.  If we could read fro an external file we could then ignore that in source control and just rely on setting the path value in that file.
If reading in a file isn't possible is there any other way we could achieve this?
Answer: As far as I can tell, you can't read an external file into a variable in a VS post-build event.  However, you can run an external batch file and provide it with arguments.  This allows us to do per-developer post-build batch scripts by excluding such scripts from source control, then checking for their existence in the post-build event and executing them if they exist, like so:
CD "$(ProjectDir)"
IF EXIST postBuild.bat (
@ECHO Post-build script exists at: $(ProjectDir)postBuild.bat - executing...
CALL "$(ProjectDir)postBuild.bat" "$(TargetPath)" "$(TargetDir)"
)

Obviously the batch file and post-build can later be expanded to pass more arguments as and when they are needed.  The batch file postBuild.bat in the project dir then looks something like this:
@REM **********
@REM Post-build script; assumes params:
@REM postBuild.bat "$(TargetPath)" "$(TargetDir)"
@REM **********

@ECHO TargetPath: %1
@ECHO TargetDir: %2

[...]


Pegar valor de um input especifico usando AJAX

Question: Seguinte, tenho um form que será enviado com AJAX, porém a URL irá variar de acordo com o ID, exemplo:
site.com/ajax/remove/100 <- ID
site.com/ajax/remove/200 <- ID

Este valor do ID está num campo hidden do formulário, como posso pegar este valor e passar para o ajax? exemplo do código:
jQuery(document).ready(function() {
    jQuery('#send_request').submit(function() {

        var dados = jQuery(this).serialize();
        //var id =

        jQuery.ajax({

            url : 'site.com/'+id,
            dataType : 'JSON',
            type : "POST",
            data : dados,
            success : function(response) {
                //alert(response.message);
                if (response.success == 1) {
                    //tudo ok
                } else {
                    //deu ruim,zé
                }
            }
        });
        return false;
    });
});

Answer: jQuery(document).ready(function() {
    jQuery('#send_request').submit(function() {

        var dados = jQuery(this).serialize();
        var id = $("#campo-hidden").val(); /// <<<<<

        jQuery.ajax({

            url : 'site.com/'+id,
            dataType : 'JSON',
            type : "POST",
            data : dados,
            success : function(response) {
                //alert(response.message);
                if (response.success == 1) {
                    //tudo ok
                } else {
                    //deu ruim,zé
                }
            }
        });
        return false;
    });
});


Angular: inserir somente data no input

Question: No sistema existe um campo para inserir uma data. Quero bloquear o input para inserir somente os valores dd/mm/aaaa
<mat-form-field class="input-full-width">
<mat-label>Data citação</mat-label>
<input matInput  [matDatepicker]="datePickerCriacao" [max]="hoje"  (click)="datePickerCriacao.open()" id="dataCitacao" placeHolder="Data citação" [(ngModel)]="dataCitacao" name="dataCitacao" maxlength="10">
<mat-datepicker-toggle matSuffix [for]="datePickerCriacao"></mat-datepicker-toggle>
<mat-datepicker #datePickerCriacao></mat-datepicker>
</mat-form-field>

Comment: tenta adicionar um type date ou number no input
Answer: Você pode conseguir isso com a ajuda do angular2-text-mask
Component
public mask = {
    guide: true,
    showMask : true,
    mask: [/\d/, /\d/, '/', /\d/, /\d/, '/',/\d/, /\d/,/\d/, /\d/]
 };

Template
<mat-form-field>
  <input matInput [textMask]="mask" [matDatepicker]="picker" placeholder="Selecione uma data">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Angular: inserir somente data no input


continuous mapping from a topology to a product topology

Question:
Let $(Y,\tau)$ and $(X_i,\tau_i)$, $i= 1,2,\ldots,n$ be topological spaces. Further for each $i$, let $f_i$ be a mapping of $(Y,\tau)$ into $(X_i, \tau_i)$. Prove that the mapping
$$f:(Y,\tau)\longrightarrow \prod(X_i,\tau_i),$$
given by $f(y) =\langle f_1(y),f_2(y),\ldots,f_n(y)\rangle$,is continuous if and only if every $f_i$ is continuous. Hint: $f_i=p_i(f)$ where $p_i$ is the projection mapping of the $i$th component.

This seems trivial for both directions so I'm not sure if I'm missing something.
Assume each $f_i$ is continuous. The take an open set $A$ in the product topology where its basis are open sets from each $X_i$. Since $f$ is continuous, the preimage of $A$ in the product topology is an $n$-tuple of open sets in $Y$ which means each component $f_i$ is continuous.
For the other direction, we assume $f$ is open and show each $f_i$ is open. Using the hint, each $f_i=p_i(f)$ which is a composition of two continuous functions since the projection mapping is continuous. Then each $f_i$ has to be continuous.
Comment: It is as easy as that. You have a correct proof.
Comment: Use MathJax please, see [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference), e.g.
Comment: The $f$ open part is not irrelevant, is it? The quoted question asks for continuity, not openness.
Answer: Your proof is almost correct. If $f = (f_1, \ldots, f_n)$ and all $f_i$ are continuous, then for a basic open subset $O=\prod_{i=1}^n O_i$, where $O_i \subseteq X_i$ is open for all $i$, we have that $$f^{-1}[O] = \{y \in Y\mid f(y) \in \prod_{i=1}^n O_i\}= \{y \in Y\mid \forall i \in \{1, \ldots n\}: f_i(y) \in O_i \} = \bigcap_{i=1}^n f_i^{-1}[O_i]$$
which is a finite intersection (not product or $n$ tuple!) of open subsets by the continuity of the component mappings $f_i$, and hence open. As inverse images under $f$ of basic open subsets are open, the same holds for all open subsets of the product topology and so $f$ is continuous.
The reverse indeed simply follows from $f_i = \pi_i \circ f$ for all $i$ and the fact that compositions of continuous maps are continuous.
It's easy to see how this generalises to infinite products (if you've treated these as well), but not to the box topology on such a product.
Comment: Thanks. By the way, just a question about most of these proofs in product topology. Open sets in a product topology are not just basic open sets (product of open sets of each component topology which only forms a basis but not the whole product topology), but also all their unions. A lot of proofs assumes we are only dealing with basic open sets which are just the product of open sets of each topology. Is that always sufficient or allowed? In this specific case, since the preimage of unions are unions of preimage, it seems ok.
Comment: oh one question about the intersection for the first part of the proof, where did that come from? Are we assuming each fi is like the projection mapping where the preimage of say pi(U) = X1 x X2 x X3 x X4 x pi^-1(U) x X5.....Xn? I'm not sure if that is the case for each fi though. Each fi maps Y to Xi, so the preimage of each fi is just elements of Y instead of a n- tuple so there should be no need to take the intersection at the end right?
Comment: @willyx888 Yes, basic elements are enough in continuity proofs, for the reason you mentioned. Often this is some separate proposition or theorem. It's one of the advantages of working with a base of more concrete sets instead of having to work with all of them. You *do* need the intersection because you need the simultaneous condition that $f_i(y) \in X_i$ for all $i$ in order for $f(y)$ to be in the rectangle set $U_1 \times \ldots \times U_n$. But you wrote in the question that the inverse image consisted of $n$-tuples which is not true, it's a subset of $Y$.
Comment: Ahh that makes senses. Yes the inverse image are all just subsets of Y. It's like taking the minimum of finite sets in real analysis proofs.
Comment: @willyx888 Indeed, you could see it a bit like that. It's like why *finite* intersections of open sets are open but not necessarily all infinite ones.


How to add an image upload field in a custom Field Type

Question: I'm defining a new custom Field Type in Drupal 8, let's say MyFieldType, with custom widget and formatter also.
Such Field Type should have these two fields:

text: a simple text value
image: a field where the user that use this Field Type can upload an image, as the built-in image field type.

I created the custom field type with the text field with no problems. Now I'm trying to add the image field also, but I'm stuck and I don't understand how to proceed.
What is the correct way to add an image upload field in a custom Field Type?

What I tried
Below there are the main parts from the custom Field Type. All files are from the folder modules\custom\my_field_type\src\Plugin\Field.
From the file FieldType\MyFieldType.php:
class MyFieldType extends FieldItemBase {

  //

  public static function propertyDefinitions(
    FieldStorageDefinitionInterface $field_definition
  ) {

    $properties['text'] = DataDefinition::create('string')
        ->setLabel(t('Text Value'));

    // $properties['image'] ... go here?
    // ...

    return $properties;
  }

  //

  public static function schema(
    FieldStorageDefinitionInterface $field_definition
  ) {

    $columns = array(

      'text' => array(
        'type' => 'varchar',
        'length' => 255,
      ),

      // What column for the 'image' field?
      // ...

    );

    $schema = array(
      'columns' => $columns,
    );

    return $schema;
  }

}

From the file FieldWidget\MyFieldTypeWidget.php:
class MyFieldTypeWidget extends WidgetBase {

  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {

    $element['value'] = [
      '#type' => 'textfield',
      '#title' => t('Value'),
      '#default_value' => isset($items[$delta]->value) ?
          $items[$delta]->value : null,
      '#empty_value' => '',
    ];

    $element['image'] = [
      '#type' => 'file',
      '#title' => t('Image'),

      '#default_value' => isset($items[$delta]->image) ?
        $items[$delta]->image : null,

      '#empty_value' => '',
    ];

    return $element;
  }

}

I can see the file upload field in the edit form (adding a new field with this custom type), but I don't know how to go on and (eventually) how to handle the uploaded image inside the class MyFieldType.
Answer: What you want to do, is to save a reference to the file which is uploaded.
Since what you are making is an image upload with extra text field, you should consider using either

\Drupal\image\Plugin\Field\FieldWidget\ImageWidget
\Drupal\image\Plugin\Field\FieldWidget\FileWidget

as foundation to your widget. That way you should be able to reuse much of the trick image/file handling and just add custom parts or overrides for your custom widget.
You should also consider using either

\Drupal\image\Plugin\Field\FieldType\ImageItem
Drupal\file\Plugin\Field\FieldType\FileItem

as foundation to your field type, since they also handle a lot of things for you. The image variant adds a lot of stuff, like alt, height, width, which is something you probably want/need at some point, so no reason making all of this yourself.


Upgrading Server 2016 to 2019

Question: I have a physical Dell T320 that I'm trying to upgrade to 2019.
It is an in place upgrade. I've tried the options with and without doing updates first, and it still fails. I've also tried pulling the network cable.
The failure code is 0xC1900101 - 0x40017
Windows updates are current. Drivers/firmware is current, and there is 35GB+ free on the C drive.
Comment: The T320 isn't listed as a supported model for Windows Server 2019 so I wouldn't count on getting it to install. - https://downloads.dell.com/manuals/all-products/esuprt_solutions_int/esuprt_solutions_int_solutions_resources/s-solution-resources_white-papers2_en-us.pdf
Comment: That code usually indicates a problem with third party drivers, most often antivirus.
Comment: You probably need more free space on the HD before doing that upgrade.  I don't know what that specific failure code is, but I don't think that's enough space to complete the upgrade.
Answer: As Michael Hampton points out, you probably have a driver or a piece of software installed that is incompatible with Server 2019. Given the age of the T320 it may not be possible to find 2019-compatible drivers.
We've seen this before on 2019 upgrades. Ours were Intel NVMe storage drivers (dated 2016) and getting 2019-compatible drivers from Intel was like getting blood out of a stone (but eventually we did get them).
Your first step though is to make sure that every driver and piece of software you have is up to date, and then trying again. However, given the age of the T320 you may have limited success.
You state that everything on firmware and drivers and Windows updates are current. If you have an antivirus or some other piece of integral software that also cannot be updated any further, this may just spell the end of the road for Windows upgrades for that server.
Comment: Antivirus is just built in Windows Defender.
My bet is the H310 as not being compatible. I'll wait and see if Dell releases drivers for it.

Upgrading Server 2016 to 2019


Paperclip custom crop for rails 4

Question: I've looked at numerous Paperclip cropping tutorials and I don't know what I'm doing wrong but I can't get it to work for me. The tutorials are all outdated so I'm wondering if that's the issue...
The latest tutorial I used is found here but the error I get is not descriptive. I get
An error was received while processing: #<Paperclip::Error: There was an error processing the thumbnail for 1dc9f9eee29a7fd2f3f68e9c264b6d5420141014-13-v9mj79
which is followed by a Rollback on Heroku and:
ActionView::MissingTemplate (Missing template profiles/failed to update, application/failed to update with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby]
I don't have any views as this is just a server side to my mobile app. I assume the latter error is not related since it shows up after the Rollback but I could be mistaken.
The data sent from my mobile app to my controller is of the form:
Parameters: {"profile"=>{"picture1_url"=>"http://a_url_here.com/sdfsdf.jpg", "crop_x"=>384, "crop_y"=>0, "crop_w"=>201, "crop_h"=>182}, "id"=>"123"}
And finally, my code is listed below. What am I doing wrong that is preventing me from cropping? Alternatively is it possible to pass commands into the model's has_attached_file so that I don't even use the processor? Something like this in my model:
# I tried this already and it didn't work but is there some other way to do this?
# Also keep in mind I will need to pass variables crop_y,crop_x, etc.
has_attached_file :picture1, styles: {
  crop: "-crop '#{crop_w}x#{crop_h}+#{crop_x}+#{crop_y}"
}

My actual code is listed below:
my model profile.rb:
has_attached_file :picture1, styles: {
  crop: {processors: [:cropper]}
}, url: "pictures/:facebook_id/:style/1:dotextension",
path: ":rails_root/public/:url"

attr_accessor :crop_x, :crop_y, :crop_w, :crop_h

My controller profiles_controller.rb:
def profile_params
    # I have other things I permit but only showing the crop values
    params.require(:profile).permit(:crop_w,:crop_x,:crop_h,:crop_y)
end

My processor cropper.rb:
module Paperclip
  class Cropper < Thumbnail
    def initialize(file, options = {}, attachment = nil)
      super
      @current_geometry.width = target.crop_w
      @current_geometry.height = target.crop_h
    end
    def target
      @attachment.instance
    end
    def transformation_command
      crop_command = ["-crop","#{target.crop_w}x#{target.crop_h}+#{target.crop_x}+#{target.crop_y}"]
      crop_command + super
    end
  end
end

Answer: The issue was that the processor was not recognizing target.crop_w etc.
I couldn't figure out how to get target.crop_w to be recognized in the processor.
In the end I passed the variables into the style through a lambda instance. For example:
has_attached_file :picture1, styles: lambda {|a| {
     crop: {processors: [:cropper],
            crop_w:a.instance.crop_w,
            crop_x:a.instance.crop_x,
            crop_y:a.instance.crop_y,
            crop_h:a.instance.crop_h}
    }
    }

a.instance.crop_w will only exist if you set crop_w to the instance. So for me, in my controller I had something like
@profile = Profile.find_by_id(params[:id])

#
@profile.picture1_from_url(params[:profile][:picture1_url],params[:profile][:crop_w ...)

and picture1_from_url was how I downloaded images with paperclip from urls. This method is in the model like so:
def picture1_from_url(url,crop_w,crop_x,crop_h,crop_y)
    self.crop_w = crop_w
    #repeat above line with crop_h crop_y crop_x
    self.picture1 = URI.parse(url)
end

By setting self.crop_w = crop_w I attached that variable to the instance which is why it was accessible in styles with lambda.
Finally, by passing it like this it could be accessed in the processor through the options hash. In my processor:
def options
  @options
end

def transformation_command
  crop_command = ["-crop","#{options[:crop_w]}x#{options[:crop_h]}+#{options[:crop_x]}+#{options[:crop_y]}"]
  crop_command + super
end

And that's how I got it to work.

Paperclip custom crop for rails 4


Moriarty's calculator: some bizarre and deceptive graphical anomalies

Question: Background: This is a problem I first came across a few years ago in a calculus textbook (a James Stewart one), where it addressed some of the pitfalls of using graphing calculators. The original context addressed issues with the TI-83 calculator, but seeing as that most people use the vaunted TI-89 nowadays, I thought I would consider some issues with that one. My first few considerations proved to be simple to handle (and I will outline them below), but there is one that I have no idea how to address properly. I think it is sufficiently bizarre so as to call the challenge problem Moriarty's Enigma.
Necessary information: The TI-89 Guidebook gives information on how the calculator draws objects given the screen dimensions of the calculator. Screen dimensions for all TI graphing calculators may be found here. The relevant information from the guidebook may be found here (link provided so as not to make an already long post even longer).
The main point is that the graphing window is $159$ pixels wide and we want to start with $x=0$ and $x=2\pi$ (the reason for this will become very clear in a moment). Since there are $158$ "gaps" between pixels, the distance between pixels is $\frac{2\pi-0}{158}$. Thus, the $x$-values that the calculator actually plots are $x=0+\frac{2\pi}{158}\cdot n$, where $n=0,1,2,\ldots,158$.
Elementary, my dear TI-89: First consider the graph of $y=\sin(161x)$, which is graphed below in dot mode on the window $0\leq x\leq 2\pi, -1.5\leq y\leq 1.5$ (this will be the window used in all examples so that my results will be reproducible by other users if desired):

Now consider when the functions $y=\pm\sin(3x)$ are graphed simultaneously in square mode:

It certainly looks as if $\sin(161x)=\pm\sin(3x)$. This actually makes sense in terms of the pixel information noted earlier: for $y=\sin(161x)$, the actual points plotted by the calculator are $\left(\frac{2\pi}{158}\cdot n,\sin\left(161\cdot\frac{2\pi}{158}\cdot n\right)\right)$ for $n=0,1,2,\ldots,158$. But
\begin{align}
\sin\left(161\cdot\frac{2\pi}{158}\cdot n\right) &= \sin\left(158\cdot\frac{2\pi}{158}\cdot n+3\cdot\frac{2\pi}{158}\cdot n\right)\\[1em]
  &= \sin(2\pi n)\cos\left(3\cdot\frac{2\pi}{158}\cdot n\right)+\sin\left(3\cdot\frac{2\pi}{158}\cdot n\right)\cos(2\pi n)\quad\text{[$\sin(\alpha+\beta)$]}\\[1em]
  &= \pm\sin\left(3\cdot\frac{2\pi}{158}\cdot n\right),\qquad n=0,1,\ldots,158
\end{align}
Thus, the $y$-values, and hence the points, plotted for $y=\sin(161x)$ lie on either $y=\sin(3x)$ or $-\sin(3x)$, as confirmed by the previous graph.
The same reasoning can be used to show that all of the $y$-values for $\sin(158x)$ are plotted as zero:

At this point, I was feeling confident about my ability to understand and detect graphing anomalies for trigonometric functions due to periodicity and the like, but the next function has thus far thwarted my analysis completely.
Moriarty's Enigma: Graph $\sin(77x)$ in line mode:

I can deduce how $\pm\sin(2x)$ comes into the mix (similar to the $\sin(161x)$ example), but I cannot see how $\pm\cos(2x)$ fits in. The $y$-values for $\sin(161x)$ seem to be a mixture of $\pm\sin(2x),\pm\cos(2x)$, and an array of different trigonometric functions. Here is the graph when all five functions are plotted simultaneously ($\sin(77x)$ plotted in line mode while $\pm\sin(2x),\pm\cos(2x)$ in square mode):

As if that were not weird enough, graph $\sin(77x)$ and $\pm\sin(81x)$ in line mode:

Finally, graph $\sin(77x)$ and $\cos(77x)$ in line mode:

What other functions might be hidden in $\sin(77x)$ when graphing on the window $0\leq x\leq 2\pi, -1.5\leq y\leq 1.5$ for the TI-89? Where do $\pm\cos(2x)$ come into play? What about $\sin\left(\frac{77x}{79}\right)$ [fills in the diamond-looking regions] or $-\sin\left(\frac{77x}{79}\right)$ [runs tangent to / crosses middle max], etc.
Comment: My reaction to the last image was the last image itself... xD
Comment: This is related to sampling-theory it seems. Ever heard of the [Niquist-Shannon sampling theorem](http://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem)?
Comment: See [an animation](http://i.imgur.com/es73dVt.gif) of $\sin\left(q\frac{\pi}{158}n\right)$ for $q=1..158$ and samples at $n=1..158$. There you'll see sort of a "reflection" of the series near the end. Of course it is related to Nyquist-Shannon sampling theorem. Various patterns from points appear even at about $q=40$.
Comment: @AvZ Yeah, I thought that gif summed things up perfectly--like what in the deuce is going on here. Bizarre.
Comment: I had encountered something similar when I plotted an animated plot of $y=\sin(10xt)$ where $t$ is the time. You can add that GIF. It'd illustrate this effect very well.
Comment: @AvZ I really wanted to add the plots as gifs so people could see them being graphed. I mean it's truly weird. I didn't even include some of my other observations simply because of the already ridiculous length of the post. But $\sin(77x)$ is just...confounding.
Comment: @Raskolnikov No, I can't say that I have. I'll make sure to read up on your link and related material. I find it thoroughly fascinating.
Comment: What happens when you plot $\sin(158x)$ in dot mode? I've been experimenting a bit with my calculator and I figured out it has 126 pixels horizontal res. When I plot $\sin(126x)$ I get a near zero curve. When I plot $\sin(157x)$, I'll get the phenomenon with a $\sin$ curve and a $\cos$ curve which is rather easy to explain because $157 = 126 + 31$ and $31$ is $0.5$ away from being a quarter of $126$.
Comment: I missed your plot of $\sin(158x)$ somehow, never mind.
Comment: @Ruslan Very interesting. Thanks for the gif! Some really interesting behavior going on there. Certainly looks like the Niquist-Shannon sampling theorem is important here. Maybe someone on MSE who knows about that can chime in (I plan to read up on it sometime this week). Very useful animation though.
Comment: Yes check out the Nyquist-Shannon sampling theorem and also amplitude modulation can be of interest.
Comment: I think I have almost figured it out. If you do your $\sin(77x)$ in dot mode, you will not get the $\cos$ behaviour. What happens in line mode is that your graphing calculator "interpolates" extra values and it looks like you plotted $\sin(77\pi x/158)$ instead of $\sin(77\pi x/79)$.
Comment: @Ruslan I was curious about what you used to produce your animation. Was it Mathematica or something else?
Comment: @Raskolnikov I just now tried graphing $\sin(77x)$ in `dot` mode, and I actually got the $\pm\cos(2x)$ behavior and the $\pm\sin(2x)$ behavior (just as before). You are using a TI-89 to make your observations right? And the window I included in the main text?
Comment: @crash yes, it's Mathematica.
Comment: @Ruslan Thanks for the info. Think you might be able to share the notebook on dropbox or something? I'd like to toy around with it if you don't mind. Plotting $\sin(77x)$ in `dot` mode did yield some insight actually--it looks like *only* the four different aforementioned functions are being plotted. The question still remains how to coax out the $\pm\sin(2x)$.
Comment: @crash well, I didn't save it as a notebook because it's a trivial thing. Here's a line you can use to look this in interactive mode inside Mathematica: `Manipulate[Show[Plot[Sin[q \[Pi]/158 n], {n, 1, 158}, PlotStyle -> Opacity[0.5], PerformanceGoal -> "Quality"], ListPlot[Table[Sin[q \[Pi]/158 n], {n, 1, 158}]]], {q, 1, 158, 1}]`.
Comment: @Ruslan Cool. Thanks. I'm going to try to crank this thing out sometime later tonight. Really been bugging me. Freaking Moriarty!
Comment: @crash, then there's something worng with your initial assumption that the TI-89 plots the $2\pi n/158$ points with $n \in \{0,\ldots,158\}$ . It must mean it plots $\pi n/158$ with $n \in \{0,\ldots,2\cdot158\}$ like Ruslan suggests.
Comment: @Raskolnikov Very interesting observation. Maybe my transition from examining the TI-89 as opposed to the TI-83 is flawed then? Because I know that "assumption" is right for the TI-83. You would think the programming would be consistent for the calculators. That is a very good point though.
Answer: Don't actually know how exactly Nyquist-Shannon theorem is related to this, but here's a crackdown of what happens with $\sin\left(77\frac{\pi}{158}n\right)$ for $n=1..158$ (equivalently, $\sin(77x)$ with $x=\frac{\pi n}{158}$):
$$f(n)=\sin\left(77\frac{\pi}{158}n\right)=\sin\left(\left(\frac{79}{158}\pi-\frac{2\pi}{158}\right)n\right)=\\
=\sin\left(\left(\frac\pi2-\frac\pi{79}\right)n\right)=\sin\frac{\pi n}2\cos\frac{\pi n}{79}+\cos\frac{\pi n}2\sin\frac{\pi n}{79}.$$
Now consider 4 cases:

$n=1+4k,\,k\in\mathbb Z$, then $f(n)=\cos\frac{\pi n}{79}$
$n=2+4k,\,k\in\mathbb Z$, then $f(n)=-\sin\frac{\pi n}{79}$
$n=3+4k,\,k\in\mathbb Z$, then $f(n)=-\cos\frac{\pi n}{79}$
$n=0+4k,\,k\in\mathbb Z$, then $f(n)=\sin\frac{\pi n}{79}$

This is exactly what you asked about $\pm\sin(2x)$ and $\pm\cos(2x)$ functions inside samples of $\sin(77x)$, where $x=\frac{\pi n}{158}$.


It's not returning the value of the Clipboard

Question: using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ConsoleApp11
{
    internal class Program
    {
        static void Main(string[] args)
        {
            GetClipboard();
            Matcher();
            Console.ReadLine();
        }

        static void Matcher()
        {
            string filePath = "C:\\Users\\bener\\Downloads\\wordlist.txt";
            string fileContents = File.ReadAllText(filePath);
            string pattern = @"\b\w+mb\b";
            Regex regex = new Regex(pattern);
            MatchCollection matches = regex.Matches(fileContents);

            foreach (Match match in matches)
            {
                Console.WriteLine(match.Value);
            }
        }

        static String GetClipboard()
        {
            string clipboardContent = Clipboard.GetText(TextDataFormat.Text);
            Console.WriteLine("Clipboard Content: " + clipboardContent);
            return clipboardContent;
        }
    }
}

My code is returning an empty string "" and not the value of the clipboard.
I'm using Windows 10 and it's not a permission issue, I already ran Visual Studio as admin
I was expecting to get the contents of the clipboard, but even after verifying that I did copy a text to it, the code does not return anything.
Comment: How are you verifying that there _is_ something on the clipboard? Are you 100% certain that it is plain text (and not Unicode, HTML, or RTF text)?
Comment: Please include the exact version of runtime you use and confirm you run on Windows. (And double check you did all shown in https://stackoverflow.com/questions/17762037/current-thread-must-be-set-to-single-thread-apartment-sta-error-in-copy-stri). Ideally if you can trim code to just an [mre] it would be nicer too.
Comment: I verified using the clipboard history and yes I'm 100% certain
Comment: From which application do you copy the text? What happens if you copy text from Notepad?
Comment: it still returns an empty string
Answer: I needed to add [STAThread] to my code that was it ):
Comment: Crucially missing an indication of  the instruction that was faulting. So where exactly did you add `[STAThread]`? Without this knowledge, readers of your Q/A don't get any wiser.


How can I change the value of a property on the call of a reusable component on Reactjs?

Question: I have a modal with a form where I am attempting to render a component which could be use anywhere with different output.
For example:
This is the component:
import { Select, SelectItem } from 'carbon-components-react';
import React from 'react';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';
import { uniqBy } from 'lodash';
import GetShipmentsAddresses from './containers/GetShipmentsAddresses';

const AddressesSelect = ({ t, handleAddresses, value }) => (
  <GetShipmentsAddresses>
    {({ data }) => {
      const unique = uniqBy(data, 'originationAddress.description');
      const renderAddresses = unique.map(addresses => (
        <SelectItem
          value={addresses.originationAddress.description}
          key={addresses.id}
          text={addresses.originationAddress.description}
        />
      ));
      return (
        <Select
          id="select-3"
          defaultValue="Shipped From"
          labelText={t('shipments.shippedFrom')}
          onChange={handleAddresses}
        >
          <SelectItem
            disabled
            hidden
            value=""
            text={t('shipments.selectLocation')}
          />
          <SelectItem value="" text={t('shipments.allLocations')} />
          {renderAddresses}
        </Select>
      );
    }}
  </GetShipmentsAddresses>
);

AddressesSelect.propTypes = {
  t: PropTypes.func.isRequired,
  handleAddresses: PropTypes.func.isRequired,
};

export default translate()(AddressesSelect);

And I need to call that on a parent component like this:
const ParentComp = ({ VALUE }) => (

          <AddressesSelect
            handleAddresses={this.handleChange('shippedFrom')}
            VALUE="originationAddress" // this is would be VALUE
            title={t('shipments.shippedFrom')}
          />

          <AddressesSelect
            handleAddresses={this.handleChange('shippedTo')}
            VALUE="destinationAddress" // this is would be VALUE
            title={t('shipments.shippedFrom')}
          />

)

So, the only thing that is going to change from call to the other is that instead of saying addresses.originationAddress.description it has to say addresses.destinationAddress.description
The only word changing is going to be originationAddress to destinationAddress.
So let's say I will like to do something like this:
const AddressesSelect = ({ t, handleAddresses, VALUE }) => (
  <GetShipmentsAddresses>
    {({ data }) => {
      const unique = uniqBy(data, 'VALUE.description');
      const renderAddresses = unique.map(addresses => (
        <SelectItem
          value={addresses.VALUE.description}
          key={addresses.id}
          text={addresses.VALUE.description}
        />
      ));
      return (
        <Select
          id="select-3"
          defaultValue="Shipped From"
          labelText={t('shipments.shippedFrom')}
          onChange={handleAddresses}
        >
          <SelectItem
            disabled
            hidden
            value=""
            text={t('shipments.selectLocation')}
          />
          <SelectItem value="" text={t('shipments.allLocations')} />
          {renderAddresses}
        </Select>
      );
    }}
  </GetShipmentsAddresses>
);

Where VALUE could be change in the call of the component to destinationAddress or originationAddress.
How can I achieve that?
Answer: Use template strings
   const ParentComp = ({ value }) => (
          <AddressesSelect
            handleAddresses={this.handleChange('shippedFrom')}
            VALUE={`${value}Address`} // this is would be VALUE
            title={t('shipments.shippedFrom')}
          />)

and in your component use it as
        <SelectItem
          value={addresses[value].description}
          key={addresses.id}
          text={addresses[value].description}
        />

just like dot notation you can use address['originatingAddress'] and here you can just replace it with your value variable
Comment: Can you be more clear? Like I know what a template string is. But can you elaborate a bit more your answer.


How to align a number to the right in Jupyter notebook math mode

Question: Apologies if this is a stupid question, but I searched a lot and couldn't find out how to do this. In math mode if I'm trying to write the equations
$$x=2  x=3$$

How do I align the x=3 to the right side of the page? I tried \hfill but it didn't seem to do anything. Thanks!
Comment: I know nothing about Jupyter, but try `$$\makebox[\textwidth]{$x = 2$\hfill$x = 3$}$$`.
Answer: Placing right-align text with markdown code is not possible. However, if you add a \tag{xx}, i.e. for equation number, you get the tag's content on the right side. And the the equation in the center. For example:-
$$x=2  x=3 \tag{2.a}$$

You get something like:        x=2 x=3                                                      (2.a)
To get what you want, you need to use HTML code instead. For example, write this code:

x=2 x=3

in a markdown cell and run it, you should get the result you want.


Coordinates of a rhombohedron

Question: I have found this question (Coordinates for vertices of the "silver" rhombohedron.) which asks:
"The "silver" rhombohedron (a.k.a the trigonal trapezohedron) is a three-dimensional object with six faces composed of congruent rhombi. You can see it visualised here.
I am interested in replicating the visualisation linked to above in MATLAB, but to do that I need to know the coordinates of the rhombohedron's eight vertices (I am using the patch function).
How do I calculate the coordinates of the vertices of the silver rhombohedron?"
The question has this answer:
"Use vectors e1=(1,0,0), e2=(cosα,sinα,0) and e3=(cosα,0,sinα) as basis.
Then vertices are set of all points with each coordinate 0 or 1: (0,0,0), (0,0,1), ..., (1,1,1).
Or 0, e1, e2, e3, e1+e2, ..., e1+e2+e3.
Multiply coordinates by constant if needed."
Using this methodology I find that two of the faces of the resulting rhombohedron are not congruent and do not have angle "α".
What vectors would I use for all faces of the rhombohedron to be congruent?
Answer: One construction is to choose the basis $$e_1 = (a,b,b), \quad e_2 = (b,a,b), \quad e_3 = (b,b,a),$$ with $a > 0$ and $b \not \in \{-a/2, a\}$.  This symmetry guarantees the congruence.  All that is needed now is to normalize the edge length, which is to say, divide by $$\sqrt{a^2 + 2b^2}.$$  To obtain the interior angle $\alpha$, it is a straightforward calculation of the dot product:  $$e_1 \cdot e_2 = 2ab + b^2 = |a||b| \cos \alpha = (a^2 + 2b^2) \cos \alpha,$$ consequently $$\alpha = \cos^{-1} \frac{2ab + b^2}{a^2 + 2b^2}.$$  We can express $b$ in terms of $a$, then after normalization, obtain a basis solely in terms of $\alpha$.
Comment: A bit beyond me.  Could you tell me what the vectors would be for e1, e2, and e3 in a form like e2=(cosα,sinα,0)?

Coordinates of a rhombohedron


What Affects "Tonality" on a Violin

Question: In a Certificate of Merit test, I was told by the judge to work on "tonality," which, as I am told by my teacher, is kinda sorta related to timbre (not pitch or rhythm, but maybe similar to articulation?). This seems kind of vague.
What are the things that affect tonality? What is a good definition of tonality? What are some exercises that can help with developing a good ear for tonality? Are there any examples of tonality in, maybe, a good recording or something?
Thank you, that's quite a list!
Comment: Huh? "Tonality" usually means (warning, over-simplified definition!) whether a piece is in a major or minor key. That has nothing much to do with "timber", or even with "timbre".
Comment: @alephzero Hmm. Maybe I'm using the wrong term (thanks for the typo-check!). Honestly, I'm just as confused as you are. I'm pretty sure that that's the term the lady used, but I can check. (EDIT: I can't check right now, don't have the papers) I think it has to do with how the note sounds. Beginner violinists tend to just play the notes, and either with or without dynamics there is no sensitivity to the tone of the sound. That's what I took it to mean.
Answer: They could have meant 'tone' or 'musicality'.  So, as you say in your comment, you can be 'technically perfect', hitting all the right notes at the right time, but perhaps not 'feeling' the music.  Also like you say in your question, listening to great recordings is a good way of hearing good musicality and tone!  However whether you like someone's specific tone or not can be subjective.
Having said that, there are things you can do to help you develop your own special tone and you musicality.  Do you ever record yourself and listen back?  If not, then try it, it doesn't have to be a great quality recording, even just using your phone/computer's basic record function to hear how you sound can be a great help!  It can be embarrassing to listen to yourself... (like listening to your own voice) but try it!  Then see if you think you sound 'wooden' or 'lacking feeling' in certain phrases, and try and add more feeling.  Find a recording of a piece you love and try and emulate that sound.  Listen to lots of versions of the same piece to find one you love, and try and copy that style.  Eventually you will be able to define your own style.
Also try playing with other people if you don't already, either accompanying someone (this will depend on what instrument you play) or jamming together can help you modify your style for different situations, so that you develop that 'tone' and 'musicality' control over your playing.  This way, you will automatically learn how to blend in with other sounds, or to stand out (for example if you have a particular phrase that you should accentuate at a specific point in the music, like a solo).
This is an important part of learning how to control your instrumental tone, but when you get it right it will be really satisfying!
Comment: Dang it, hit the return key instead of the shift... Great suggestions! I do record myself, and I agree -- it's an awesome thing. I am a Suzuki learner, therefore listening to music is part of my routine, but I will start looking for the things you mentioned! Thanks!
Answer: I figured it out!
The judge had meant "tonalization," which is Suzuki speak for "A play on the word "vocalization," Suzuki developed this as a way for a student to recognize and produce a ringing, beautiful tone from their violin."

What Affects "Tonality" on a Violin


If $f_n \to f$ almost uniformly, then $f_n \to f$ a.e. and in measure.

Question: I want to prove following statement in Folland: If $f_n \to f$ almost uniformly, then $f_n \to f$ a.e. and in measure.
This is what I did: For $k \in \mathbb{N}$, we choose $F_k$ s.t. $\mu(F_k) < \frac{1}{k}$ and $f_n \to f$ uniformly on $F_k^c$ (so I can do this, how can I verify that there exists such $F_k$?). Then, take $E = \bigcup_1^{\infty} F_k$. Then $f_n \to f$ on $E^c$ (is it uniform or not?), and I try to verify $\mu(E) = 0$ (but have problems also), so if this is valid, things are OK for a.e. convergence.
What can I further do for convergence in measure?
This is a homework question, so if you give reasonable hints, I will be very happy. Thanks!
Answer: Your first step is good. We can remove a set of measure less than $1/k$ and get uniform convergence on the compliment -- this is true by the definition of almost uniform convergence.
Now, we will prove convergence in measure. Pick $\epsilon > 0$. We want to show that
$$m(\{x:|f_n - f| \geq \epsilon \}) \to 0 $$
Well, on the complement of $F_k$, we have some integer $N_{k,\epsilon}$ such that for $n \geq N_{k,\epsilon}$
$$ |f_{n} - f| < \epsilon$$
Why is this the case? Can you show that the set
$$\{x :|f_{n} - f| \geq \epsilon\}$$
is contained in $F_{k}$ for $n \geq N_{k,\epsilon}$?
Use that to show
$$m(\{x:|f_n - f| \geq \epsilon \}) \to 0 $$


Erro ao abrir dialog com recyclerview, ao adicionar o clique no item da lista

Question: Erro: RecyclerView﹕ No adapter attached; skipping layout
Vi vários itens realmente parecidos com este erro aqui, mas nenhum solucionou meu problema.
A lista é carregada normalmente, somente depois de adicionar a interface, que criei, de clique em um item da lista (esta interface de clique é utilizada em outras situações, normalmente), é que o erro ocorre. E o recyclerview é criado em alertDialog.
Tentei alterar a posição do código, pois vi que poderia ser que a lista não estivesse preenchida ou o adapter ainda não carregado, mas não funcionou.
Após ir ao servidor, retorno uma lista com itens e somente depois deste retorno, crio os itens relacionados ao recyclerview e adapter. Trabalho com asyncTask, este retorna à activity através de um método que é sobrescrito.
segue os códigos
Activity/dialog:
public void buildDialogToPredicted(String whichDialog) {
//método criado, após o retorno para a criação do dialog com a lista de itens preditos.
        startVoiceWave(this, this);
        View viewAlertDialog = LayoutInflater.from(this).inflate(R.layout.predict_layout, null);
        recyclerView = viewAlertDialog.findViewById(R.id.recycler_predict);
        recyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);

        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setView(viewAlertDialog)
                .setCancelable(true);
        final AlertDialog dialog1 = dialog.create();
        Button close = viewAlertDialog.findViewById(R.id.btn_close_predic);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vpPager.setCurrentItem(vpPager.getCurrentItem() + 1, true);

                dialog1.dismiss();

            }
        });

        dialog1.show();
        dialog1.getWindow().setLayout(1050, 1400);
        switch (whichDialog) {
            case "predicaoCid.sucesso":
                final List<CidVo> list = MyApplicationInstance.getInstanceApplication().getCidVo();
                recyclerViewAdapterPredictCid = new CustomRecyclerViewAdapterPredictCid(list, this, new CustomItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        list.remove(position);
                        recyclerViewAdapterPredictProd.notifyDataSetChanged();
                    }
                });

                recyclerView.setAdapter(recyclerViewAdapterPredictCid);
                break;

            case "predicaoProc.sucesso":
                final List<PredicaoProcedimentoVo> listProc = MyApplicationInstance.getInstanceApplication().getProcedimentoVosList();
                recyclerViewAdapterPredictProd = new CustomRecyclerViewAdapterPredictProd(listProc, this, new CustomItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        listProc.remove(position);
                        recyclerViewAdapterPredictProd.notifyDataSetChanged();
                    }
                });

                recyclerView.setAdapter(recyclerViewAdapterPredictProd);
                break;

        }

    }

Adapter:
public class CustomRecyclerViewAdapterPredictProd extends
        RecyclerView.Adapter<CustomRecyclerViewAdapterPredictProd.ViewHolder> implements CustomItemClickListener {

    private AppCompatActivity appCompatActivity;
    private List<PredicaoProcedimentoVo> mDataset;
    // Animation
    private int lastPosition = -1;
    private RadioButton lastCheckedRB = null;
    private ItemAgendaVo itemAgendaVo;
    private CustomItemClickListener listener;
    private View v;

    // Provide a suitable constructor (depends on the kind of dataset)
    public CustomRecyclerViewAdapterPredictProd(List<PredicaoProcedimentoVo> myDataset, AppCompatActivity appCompatActivity, CustomItemClickListener listener) {

        this.appCompatActivity = appCompatActivity;
        this.mDataset = myDataset;
        this.listener = listener;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(
            ViewGroup parent, int viewType) {
        // create a new view
        v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_predict, parent, false);
        // set the view's size, margins, paddings and layout parameters

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        PredicaoProcedimentoVo predicaoCidVo = getProcVo(position);

        setAnimation(holder.txtCID, position);

        holder.txtCID.setText(predicaoCidVo.getTextPredictedProc());
        listener.onItemClick(v,position);//erro ocorre nesta linha TODO

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {

        if (mDataset != null) {

            return mDataset.size();
        }
        return 0;
    }

    /**
     * @param position
     * @return
     */
    public PredicaoProcedimentoVo getProcVo(int position) {

        return mDataset.get(position);
    }

    /**
     * Here is the key method to apply the animation
     */
    private void setAnimation(View viewToAnimate, int position) {
        // If the bound view wasn't previously displayed on screen, it's
        // animated
        if (position > lastPosition) {

            Animation animation = AnimationUtils.loadAnimation(
                    appCompatActivity, android.R.anim.slide_in_left);
            // Animation animation = AnimationUtils.loadAnimation(
            // appCompatActivity, R.anim.slide_top_to_bottom);
            // Animation animation =
            // AnimationUtils.loadAnimation(appCompatActivity,
            // R.anim.clockwise_rotation);
            // animation.setRepeatCount(Animation.START_ON_FIRST_FRAME);
            viewToAnimate.startAnimation(animation);

            lastPosition = position;
        }
    }

    @Override
    public void onItemClick(View v, int position) {

    }

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView txtCID;
        TextView txtCIDDesc;

        ViewHolder(View v) {
            super(v);

            txtCID = itemView.findViewById(R.id.txtCard1_item1);
            txtCIDDesc = itemView.findViewById(R.id.txtCard1_item2);

        }
    }
}

Erro ocorre no adapter, quando passa pelo listener.onItemClick(v,position)
Agradeço a ajuda.
Answer: Opa, tudo bem!?
Segue uma maneira simples e objetiva para a implementacao do código que está precisando:

Meu adapter, onde RacaClickListener é minha interface, declaro ela e assino o método de clique.

public class RacasAdapter extends RecyclerView.Adapter<RacasAdapter.ItemViewHolder> {
private static List<String> dataList;
private LayoutInflater mInflater;
private Context context;
private RacaClickListener clicklistener = null;
private boolean marcado = false;

public RacasAdapter(Context ctx, List<String> data) {
    context = ctx;
    dataList = data;
    mInflater = LayoutInflater.from(context);
}

public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private TextView txtRaca;

    public ItemViewHolder(View itemView) {
        super(itemView);

        itemView.setOnClickListener(this);

        txtRaca = itemView.findViewById(R.id.txtRaca);
    }

    @Override
    public void onClick(View v) {

        if (clicklistener != null) {
            //assinando o clique na posicao xx
            clicklistener.itemClicked(v, getAdapterPosition());
        }
    }
}

public void setClickListener(RacaClickListener listener) {
    this.clicklistener = listener;
}

@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_racas, parent, false);
    ItemViewHolder itemViewHolder = new ItemViewHolder(view);
    return itemViewHolder;
}

@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    holder.txtRaca.setText(dataList.get(position));
}

@Override
public int getItemCount() {
    return dataList.size();
}

}

Interface RacaClickListener

public interface RacaClickListener {
void itemClicked(View view, int position);
}

Na minha activity implemento a interface

public class RacaPetActivity extends AppCompatActivity implements RacaClickListener

e implemento seu método:
@Override
public void itemClicked(View view, int position) {
//aqui vc fará suas acoes, no meu caso setei um objeto e chamei minha proxima atividade passando o mPet(que é minha classe model).
    mPet.setRaca(mListaGenerica.get(position));
    Intent intent = new Intent(this, SexoPetActivity.class);
    intent.putExtra("mPet", mGson.toJson(mPet));
    startActivity(intent);
}

Abraços meu caro!
Comment: valeu, acabei respondendo no ingles e não aqui. O erro estava no listener, não havia implementado ele dentro de um CLICK. Agradeço e marco como resposta!


how to configure dns mapping in netgear router for local server

Question: I have a server which act as a webserver in our LAN. its ip address is 192.168.137.70 and it has local domain name mapping with name "kf.kobo.local" in hosts file

I need to access the server from other laptops in the LAN using domain kf.kobo.local instead of ipaddress.
What are the steps i need to take?
Answer: As your web server IP address (192.168.137.70) is constant, providing you with steps for static Domain Name System server.If you want to go with a Dynamic Domain Name System(DDNS) then refer to the detailed steps provided here .
DDNS service automatically updates the IP address information that is assigned to your host (domain) name.
To set static DNS servers on your NETGEAR router:

Launch a web browser from a PC that is connected
to your NETGEAR router.

Visit www.routerlogin.net.

Enter the username and password.
The default username is admin. The default password is password.

Select the Internet. The Internet Setup page displays.

Under the Domain Name Server (DNS) Address section, select the radio
button for Use these DNS Servers.

Enter your primary DNS and secondary DNS addresses.
If you do not know your primary and secondary DNS addresses, contact your ISP for assistance.

Click Apply.
Comment: A DNS server (bind9) was installed in the ubuntu server machine and problem solved
Comment: Thanks for the reply. This is local network and there is no internet. What DNS primary address can i give. Are we making router as dns server following the above steps.


Fetch sempre retorna "TypeError: Body has already been consumed." , como corrigir?

Question: Estou utilizando a função fetch abaixo:

var url = "https://jsonplaceholder.typicode.com/users/2";

fetch(url).then(function(response) {
  if (!response.ok) {
    alert("Response not ok" + response.statusText);
    throw new Error(response.statusText);
  } else {
    alert(" Response Swal  Json:" + response.json());
  }

  return response.json();
}).catch(function(error) {
  alert("DeuErro -> " + error);

  swal.showValidationError(
    'Erro: ' + error
  )
})

Porém ela sempre dispara o erro:

TypeError: Body has already been consumed.

O que poderia estar ocorrendo?
Quais as formas de corrigir?
Comment: Dentro do `else`, você já consome o corpo da resposta quando faz `response.json()`; quando você tenta retornar o mesmo valor, já não haverá conteúdo para ser consumido. Por que não atribui isso a uma variável e a reutiliza nesses dois lugares?
Comment: Obs.: No modal do snippet que utilizou para inserir o código existe o botão "Organizar". Utilize-o para formatar corretamente os códigos antes de criar a pergunta para facilitar a leitura dos códigos.
Comment: Obrigado pela dica @Woss, não conhecia esse botão
Answer: O método response.json irá retornar uma nova promessa, então precisa lidar com ela corretamente. O mais fácil é tratá-la com then encadeados:

var url = "https://jsonplaceholder.typicode.com/users/2";

fetch(url)
  .then(function(response) {
    if (!response.ok) {
      throw new Error(response.statusText);
    }

    return response.json();
  })
  .then(function (data) {
    console.log(data);
  })
  .catch(function(error) {
    console.error("DeuErro -> " + error);
  })

Assim, a promessa retornada por response.json será processada e o corpo da resposta será passada ao próximo then já tratado como JSON.
Uma forma equivalente (e menos encadeada) seria utilizando o async/await:

async function get_user_details(id) {
  const url = `https://jsonplaceholder.typicode.com/users/${id}`;
  const response = await fetch(url);

  return await response.json();
}

get_user_details(2).then(user => {
  console.log(user);
})


Why a uniform limit of a sequence of bounded derivative is a derivative?

Question: Assume that a sequence $(f_n)$ of functions $f_n:[0,1] \rightarrow \mathbb R$ is uniformly convergent to a function $f:[0,1]\rightarrow \mathbb R$. Moreover let (for each $n\in \mathbb N$)  $f_n$ be bounded and $f_n$ be a derivative of some $F_n: [0,1]\rightarrow \mathbb R$.
How to show that $f$ is a derivative of some $F:[0,1]\rightarrow \mathbb R$?
My attempt: by assumptions follows easily that $f_n$ (as derivative)
 is measurable , consequently (as measurable and bounded) $f_n$ is
integrable. Hence $F_n$
 is absolutely continuous. We have also that
$f$ is integrable and bounded (as a
consequence of uniformly convergence). Let
$$G_n(x)=
\int_0^xf_n(t)dt.$$
Then (using definition of uniform convergence)
$$\lim_{n\rightarrow \infty} G_n(x)=
\int_0^x f(t)dt=:G(x) \textrm{ for } x\in [0,1].$$
I'm not sure whether
$G'(x)=f(x)$ for all
$x∈[0,1]$., because I know only that absolutely continuous function has derivatives  almost everywhere.
Comment: @Dimitris Why $f$ is continuous? Derivative of function has only the Darboux property.
Comment: @L.T: Hint: you may imitate the proof of that uniform convergence limit of continuous functions is continuous to show $G'=f$. If you need me to elaborate, could you please add the content in your first comment to the body of your question? It would be helpful for me/others to answer your question in details.
Comment: Because of uniform convergance we have that $f$ is continuous on $[0,1]$. $f_n$ are bounded because $[0,1]$ is compact. So $f$ as continuous on the compact $[0,1]$ is bounded and thus is integrable
Comment: @L.T, I believe some background regarding your level of familiarity with calculus/integration-theory will be very helpful in tailoring the answer to your needs.
Comment: correct.i just assumed that $f_n$ are continuous
Comment: Ok then, $f_n$ are Riemann integrable and by taking the same partition of $[0,1]$ show  the convergance of the sums due to the uniform convergance of $f_n->f$
Comment: @Dimitris even functions with a positive-measure set of discontinuities can have an antiderivative.
Comment: @Girafe I have added this comment to the question.
Comment: @L.T: Thank you for your edit. There is already an answer sharing the same idea with me.(The spelling of my user name in your reply to me is wrong; I didn't receive any message.)
Comment: @Giraffe, Sorry for mistake.
Comment: @L.T: Never mind. In fact it frees me from typing so many words! :)
Answer: To show that $G'(x) = f(x)$ for an $x \in [0,1]$, we must, for every $\varepsilon > 0$, find (establish the existence of) a $\delta > 0$ such that
$$0 <\lvert h\rvert < \delta \land (x+h)\in[0,1] \Rightarrow \left\lvert \frac{G(x+h)-G(x)}{h} - f(x)\right\rvert < \varepsilon.$$
Let $\varepsilon > 0$ be arbitrary. By the uniform convergence of $f_n \to f$, choose an $N\in \mathbb{N}$ such that $\lvert f_N(y) - f(y)\rvert < \varepsilon/3$ for all $y \in [0,1]$. For that $N$, by the assumed differentiability of $F_N$ in $x$, choose $\delta > 0$ such that
$$0 <\lvert h\rvert < \delta \land (x+h)\in[0,1] \Rightarrow \left\lvert \frac{F_N(x+h)-F_N(x)}{h} - f_N(x)\right\rvert < \varepsilon/3.$$
Then, for admissible $h$, we have
$$\begin{align}
\left\lvert \frac{G(x+h)-G(x)}{h} - f(x)\right\rvert &= \left\lvert \frac1h \int_0^h f(x+t)\,dt - f(x) \right\rvert\\
&= \Biggl\lvert \frac1h \int_0^h \bigl(f(x+t) - f_N(x+t)\bigr)\,dt\\
&\qquad + \left(\frac1h \int_0^h f_N(x+t)\,dt - f_N(x)\right)\\
&\qquad + \bigl(f_N(x) -f(x)\bigr)\Biggr\rvert\\
&\leqslant \frac1{\lvert h\rvert} \int_0^{\lvert h\rvert} \lvert f(x+ \sigma(h)t)-f_N(x+\sigma(h)t)\rvert\,dt\tag{*}\\
&\qquad + \left \lvert\frac{F_N(x+h)-F_N(x)}{h} -f_N(x)\right\rvert\\
&\qquad + \lvert f_N(x) - f(x)\rvert\\
&< \frac{\varepsilon}{3} + \frac{\varepsilon}{3} + \frac{\varepsilon}{3},
\end{align}$$
so we see that $G$ is differentiable in $x$ with derivative $G'(x) = f(x)$.
In $(*)$, $\sigma(h)$ is the sign of $h$, $\pm 1$.
Comment: Many thanks for answer!!!