Using int vs Integer

Question: I came across a class using Integer variables to capture size to be used in a for loop. Is this good practice or should we use the int primitive data type?
Integer size = something.getFields().size();
for (Integer j = 0; j < size - 1; ++j)

Comment: Possible duplicate: **[int or Integer](http://stackoverflow.com/a/423718/500725)**
Comment: the Integer class is provided so that values can be boxed/unboxed in a pure OO manner.  use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.
Comment: possible duplicate of [int or Integer](http://stackoverflow.com/questions/423704/int-or-integer)
Answer: the Integer class is provided so that values can be boxed/unboxed in a pure OO manner. use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.
Java Int vs Integer

However, very different things are going on under the covers here. An int is a number; an > Integer is a pointer that can reference an object that contains a number.

...

An int is not an object and cannot passed to any method that requires
objects. A common case is in using the provided collection classes (
List , Map , Set ) - though it is possible to write versions of these
classes that provide similar capabilities to the object versions. The
wrapper classes ( Integer , Double , etc) are frequently required
whenever introspection is used (such as in the reflection API).

A better description of when to use one vs. the other:
Choosing between int and Integer

I'll start with how these types should be used before going into
detail on why.

Prefer int for performance reasons
Methods that take objects (including generic types like List<T>)
will implicitly require the use of Integer
Use of Integer is relatively cheap for low values (-128 to

because of interning - use Integer.valueOf(int) and not new
Integer(int)

Do not use == or != with Integer types
Consider using Integer when you need to represent the
absence of a value (null)
Beware unboxing Integer values to int with null values
Comment: You answer is very good.  Please note the performance benefit in mobile/resource-restricted applications of using primitive values.
Comment: "An int is not an object and cannot passed to any method that requires objects."

How about doSomething(911) ??

public Object doSomething (Object o) {
        // do something!!!
        return o;
    }
Comment: Why not use == or != with Integer types ? Won't it auto unbox to int ?
Comment: @MuhammadShahab using == or != compares the references instead of the integer values. This https://stackoverflow.com/a/5279515/7126092 is a great answer explaining the equality of Integers.
Answer: If you can use int do so.  If the value can be null or is used as an Object e.g. Generics, use Integer
Usually it doesn't matter which one you use but often int performs slightly better.
Comment: In many cases `int` performs not just *slightly*, but a whole lot better, especially in tight loops :)
Comment: Also it's trivial to change back & forth using `Integer#intValue(Integer)` and `Integer#valueOf(int)`
Comment: I think you mean `Integer.intValue()` ;)  With auto-boxing and unboxing introduced in Java 5.0, you don't need to do this.
Answer: This approach is not good in practice, use int whenever possible. Usage of Integer indicates that this particular variable can be null (or it was inside a collection, damn generics...) - which is not the case.
Also using Integer introduces an extra overhead of boxing and unboxing.
Answer: This is a potential disaster waiting to happen in large projects. The coder here forgot that each Integer is actually a new object, and, to use it as an int, there has to be boxing and unboxing all the time. Not only is it inefficient, it's also not going to run as expected. You are best advised to always use int where possible, and only use Integer for placing these values into lists, containers or for database storage.  Remember, comparing Objects using >, < and == means something else than when you are using the same operators to compare primitives.
Answer: Promote primitive types always where it is possible.
primitive types can not be used as GenericArgument or a null.
Answer: Dont use it only to loop.  Use the primitive type int (better performance), which is not the same as the Class Integer.

The Integer class wraps a value of the primitive type int in an
  object. An object of type Integer contains a single field whose type
  is int.
In addition, this class provides several methods for converting an int
  to a String and a String to an int, as well as other constants and
  methods useful when dealing with an int.

So, use Integer if you need to call the Integer functions or need to assign a null value to it.
You will also need to use Integer instead of int for generics like List
Answer: When there is a need of using objects, you have to use the Wrapper classes,
 like Integer, Double, Float, etc...
eg:
 int n = Integer.parseInt("10");

Here we are converting the string to an integer (Primitive type) ,
but method parseInt(String str) works only on Wrapper classes (ie Object),
so we used it... you will find many more use of it in java.
Comment: Noob question: Isn't this equivalent to: int n = Integer.parseInt("10").intValue; ?
Answer: There can be a performance penalty due to boxing and unboxing, as you incur the overhead of converting between a primitive and a reference type.
However, the Integer class adds additional methods that can be very useful.
Answer: You can't use == or != with Integer types as it'll compare their "pointer location".
In order for auto-unboxing to kick off, at least one of the elements must be int.
If you are comparing Integer1 == Integer2, what actually happens is that Object.equals gets called as in: Integer1.equals(Integer2) which (unless overridden) compares the references.
(This is meant to be a reply to @Muhammad Shahab but I cannot add comments yet)
Answer: I normally use Integer because of purely OO. Performance of int is definitely far better than its object counterpart but it is noticeable only when you are looping millions time in the loop.
IMHO, If performance is paramount importance in you application and you want to squeeze even single nano second then use int without any brain. But if OO  and readability is main concerned then use Integer.

Using int vs Integer


I don't understand such a difference in the accuracy, please help

Question: When I use a normalized values for the values of the target column in the following DL regression model I get a very good accuracy, and if I don't, the accuracy is a mess.
However I've reading that normalize the target values should not affect the behavior, so I'm confused and I don't understand what's going on in this case.
Can I please get a feedback about what I'm doing right or wrong?
I've paste the code below, nevertheless, for those of you that prefer an .ipynb view, you can visit the following:
https://github.com/Mike76b/Deep-Learning-Regression-model/blob/master/BkFriday-Demo.ipynb
And if you have troubles opening the .ipynb copy the link above and paste it in the following page:
https://nbviewer.jupyter.org/
Thanks.
Source of the data (kaggle)
https://www.kaggle.com/mehdidag/black-friday
Modules used
<code>import pandas as pd
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
%matplotlib inline

...
</code>
Using TensorFlow backend.
For explanatory purpose only:
<code>...

bkFriday_df = pd.read_csv('D:/ProgramData/Data Resources/BlackFriday/BlackFriday.csv', sep=',')

bkFriday_df.head()
User_ID     Product_ID  Gender  Age     Occupation  City_Category   Stay_In_Current_City_Years  Marital_Status  Product_Category_1  Product_Category_2  Product_Category_3  Purchase
0   1000001     P00069042   F   0-17    10  A   2   0   3   NaN     NaN     8370
1   1000001     P00248942   F   0-17    10  A   2   0   1   6.0     14.0    15200
2   1000001     P00087842   F   0-17    10  A   2   0   12  NaN     NaN     1422
3   1000001     P00085442   F   0-17    10  A   2   0   12  14.0    NaN     1057
4   1000002     P00285442   M   55+     16  C   4+  0   8   NaN     NaN     7969

bkFriday_df.shape
(537577, 12)

bkFriday_df.columns
Index(['User_ID', 'Product_ID', 'Gender', 'Age', 'Occupation', 'City_Category',
   'Stay_In_Current_City_Years', 'Marital_Status', 'Product_Category_1',
   'Product_Category_2', 'Product_Category_3', 'Purchase'],
  dtype='object')

bkFriday_df.describe(include = 'all')
    User_ID     Product_ID  Gender  Age     Occupation  City_Category   Stay_In_Current_City_Years  Marital_Status  Product_Category_1  Product_Category_2  Product_Category_3  Purchase
count   5.375770e+05    537577  537577  537577  537577.00000    537577  537577  537577.000000   537577.000000   370591.000000   164278.000000   537577.000000
unique  NaN     3623    2   7   NaN     3   5   NaN     NaN     NaN     NaN     NaN
top     NaN     P00265242   M   26-35   NaN     B   1   NaN     NaN     NaN     NaN     NaN
freq    NaN     1858    405380  214690  NaN     226493  189192  NaN     NaN     NaN     NaN     NaN
mean    1.002992e+06    NaN     NaN     NaN     8.08271     NaN     NaN     0.408797    5.295546    9.842144    12.669840   9333.859853
std     1.714393e+03    NaN     NaN     NaN     6.52412     NaN     NaN     0.491612    3.750701    5.087259    4.124341    4981.022133
min     1.000001e+06    NaN     NaN     NaN     0.00000     NaN     NaN     0.000000    1.000000    2.000000    3.000000    185.000000
25%     1.001495e+06    NaN     NaN     NaN     2.00000     NaN     NaN     0.000000    1.000000    5.000000    9.000000    5866.000000
50%     1.003031e+06    NaN     NaN     NaN     7.00000     NaN     NaN     0.000000    5.000000    9.000000    14.000000   8062.000000
75%     1.004417e+06    NaN     NaN     NaN     14.00000    NaN     NaN     1.000000    8.000000    15.000000   16.000000   12073.000000
max     1.006040e+06    NaN     NaN     NaN     20.00000    NaN     NaN     1.000000    18.000000   18.000000   18.000000   23961.000000

...
</code>
Columns that I will use to build the model
<code>...

Some of them
toAdd_df = pd.get_dummies(bkFriday_df[['Gender', 'Age', 'City_Category', 'Stay_In_Current_City_Years']])
toAdd_df.shape
(537577, 17)

Predictors DataFrame
All of them
pred_df = bkFriday_df[['Occupation', 'Marital_Status']].join(toAdd_df)
pred_df.shape
(537577, 19)

pred_df.head()
    Occupation  Marital_Status  Gender_F    Gender_M    Age_0-17    Age_18-25   Age_26-35   Age_36-45   Age_46-50   Age_51-55   Age_55+     City_Category_A     City_Category_B     City_Category_C     Stay_In_Current_City_Years_0    Stay_In_Current_City_Years_1    Stay_In_Current_City_Years_2    Stay_In_Current_City_Years_3    Stay_In_Current_City_Years_4+
0   10  0   1   0   1   0   0   0   0   0   0   1   0   0   0   0   1   0   0
1   10  0   1   0   1   0   0   0   0   0   0   1   0   0   0   0   1   0   0
2   10  0   1   0   1   0   0   0   0   0   0   1   0   0   0   0   1   0   0
3   10  0   1   0   1   0   0   0   0   0   0   1   0   0   0   0   1   0   0
4   16  0   0   1   0   0   0   0   0   0   1   0   0   1   0   0   0   0   1

pred_df.isnull().any()
Occupation                       False
Marital_Status                   False
Gender_F                         False
Gender_M                         False
Age_0-17                         False
Age_18-25                        False
Age_26-35                        False
Age_36-45                        False
Age_46-50                        False
Age_51-55                        False
Age_55+                          False
City_Category_A                  False
City_Category_B                  False
City_Category_C                  False
Stay_In_Current_City_Years_0     False
Stay_In_Current_City_Years_1     False
Stay_In_Current_City_Years_2     False
Stay_In_Current_City_Years_3     False
Stay_In_Current_City_Years_4+    False
dtype: bool

#Normalizing Occupation column
pred_df['Occupation'] = pred_df['Occupation']/pred_df['Occupation'].max()

...
</code>
Here is where the code of the model/questions begin
Purchase (target) column info
MIN val: 185
MAX val: 23961
MEAN val: 9333.859
STD val: 4921.022
<code>...

#Normalizing Purchase (target) column
targ_df = bkFriday_df['Purchase']/bkFriday_df['Purchase'].max()

targ_df.head()

0    0.349318
1    0.634364
2    0.059346
3    0.044113
4    0.332582
Name: Purchase, dtype: float64

targ_df.shape
(537577,)

targ_df.isnull().any()
False

#Define classification model

def regression_model():
    # create model
    model = Sequential()
    model.add(Dense(50, activation='relu', input_shape=(19,)))
    model.add(Dense(50, activation='relu'))
    model.add(Dense(1))

    # compile model
    model.compile(optimizer='adam', loss='mean_squared_error')
    return model

# build the model
model = regression_model()

#Using a normalized target

model.fit(pred_df, targ_df, validation_split=0.3, epochs=10, verbose=2)

Train on 376303 samples, validate on 161274 samples
Epoch 1/10
 - 8s - loss: 597019.1829 - val_loss: 2.6506
Epoch 2/10
 - 8s - loss: 0.6978 - val_loss: 0.0456
Epoch 3/10
 - 8s - loss: 0.0436 - val_loss: 0.0434
Epoch 4/10
 - 8s - loss: 0.0433 - val_loss: 0.0431
Epoch 5/10
 - 7s - loss: 0.0430 - val_loss: 0.0430
Epoch 6/10
 - 8s - loss: 0.0429 - val_loss: 0.0431
Epoch 7/10
 - 8s - loss: 0.0428 - val_loss: 0.0430
Epoch 8/10
 - 8s - loss: 0.0427 - val_loss: 0.0428
Epoch 9/10
 - 8s - loss: 0.0426 - val_loss: 0.0431
Epoch 10/10
 - 8s - loss: 0.0426 - val_loss: 0.0428

<keras.callbacks.History at 0x2d64e63d4e0>

#Using a target that is NOT normalized

targ_df1 = bkFriday_df['Purchase']

model.fit(pred_df, targ_df1, validation_split=0.3, epochs=10, verbose=2)

Train on 376303 samples, validate on 161274 samples
Epoch 1/10
 - 10s - loss: 27449712.1709 - val_loss: 24691241.0429
Epoch 2/10
 - 9s - loss: 24545862.6251 - val_loss: 24694663.1769
Epoch 3/10
 - 9s - loss: 24547027.7592 - val_loss: 24691479.8413
Epoch 4/10
 - 9s - loss: 24549062.7868 - val_loss: 24693882.1764
Epoch 5/10
 - 9s - loss: 24546786.5014 - val_loss: 24694371.9963
Epoch 6/10
 - 9s - loss: 24548953.5945 - val_loss: 24693229.1358
Epoch 7/10
 - 9s - loss: 24546170.8858 - val_loss: 24692611.7169
Epoch 8/10
 - 9s - loss: 24547501.0794 - val_loss: 24700711.9410
Epoch 9/10
 - 9s - loss: 24548278.9858 - val_loss: 24690487.4462
Epoch 10/10
 - 9s - loss: 24548030.6103 - val_loss: 24702105.0564

<keras.callbacks.History at 0x2d64c66ff60>

targ_df1.dtype
dtype('int64')

#end.
</code>
Answer: The main problem is that you are trying to evaluating a regression problem with a classification metric (i.e. accuracy).
Accuracy tells you how many predictions you got right as a percentage of your total predictions. For example if your model makes $10$ predictions and gets $7$ of them right, you have a $70\%$ accuracy.
In regression problems, you are trying to predict a continuous value, in this case the amount of the purchase in dollars. For this you need a metric suitable for regression. These metrics show you how close you are to the target price. For example, if the target price is $9.99$ and your model predicts $10.50$ it's better than if it predicted $11.34$. If you used accuracy both of these two predictions would be counted as misses and we'd have no information over which one is better. For this reason we need a regression metric, e.g. Mean Absolute Error, Mean Squared Error, etc.
TL;DR: Don't use accuracy to evaluate regression models!
Comment: Thanks for you answer, I thought that I was evaluating the model with the Mean Squared Error when I set `loss='mean_squared_error'` now I changed that line of code to `model.compile(optimizer='adam', loss='mean_squared_error', metrics = ['mean_squared_error'])` Is it all I had to do? and if so, could you please tell me how can I see the performance now? I mean, after running the model, what function/line of code should I use to see how well it was with the new setting. I know it might be too simple questions but is just that I'm starting to learn all these concepts and tools. Thanks rgds
Comment: The performance of your model can be measured through the MSE on the validation/test set. A *lower* MSE means a *better* model (because the predictions fall closer to their actual values).


real solution for `No input file specified.` (nginx, fpm)

Question: Most answers to this question are, set fastcgi_param SCRIPT_FILENAME and it will work (italic formatting is broken?!).
I have set this variable (correct) but it still shows the error instead of a 404 page, because the root of the problem is here:
location ~ \.php$ {
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

A nonexistent path is passed to php5-fpm, this in return prints the error, which in the log looks like:
FastCGI sent in stderr:
"Unable to open primary script: ... (No such file or directory)"
while reading response header from upstream

So before the line fastcgi_pass  there must be a condition to check whether the file really exists, or, if the fpm worker returns "file not found", to guide nginx to return a 404 page.
How can I do this?
Answer: Using try_files  $uri =404; first!
location ~ \.php$ {
        try_files  $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
}

Thanks to http://nginxlibrary.com/resolving-no-input-file-specified-error/
Answer: In some old tutorials you often find something like this
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    if (! -f $document_root$fastcgi_script_name) {
            return 404;
    }

But as https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ states you should better use try_files instead
Just a side note: It's dangerous to use the config you posted without an if/try_files block because it can allow execution of arbitrary code under some circumstances! In fact there are a lot of tutorials on the net that don't cover this aspect so I'd recommend everyone to check if their config is not just working but also secure.
Comment: Thx for the hint and the link. Using `try_files` now, hope I'm safe with it.
Comment: With your fastcgi_split_path_info statement, you are safe when you also have cgi.fix_pathinfo=0 in php.ini.


Como contar quantas ocorrências de um atributo de uma lista são iguais a um valor? JSF

Question: Estou precisando contar quantos status são iguais a '1'. Utilizei isso para contar quantos objetos tinha na lista e funcionou. Agora não consigo contar só os que tem status igual a 1.
<h:outputText value="#{fn:length(cur.listaProdutosManutencao)}" />

Esse daí foi o que usei e funcionou.
Tentei este abaixo para pegar o status e não funcionou:
<h:outputText value="#{fn:length(cur.listaProdutosManutencao.status eq '1')}" />

Tentei este outro também, e não funcionou:
<h:outputText value="#{fn:join(cur.listaProdutosManutencao.status, '1')}"

Alguém pode me ajudar? Gostaria de seguir o primeiro que fiz.
Comment: você pode informar mais detalhes? Postá seu beans com isso vc pode criar um método para isso.
Comment: Cara, listaProdutosManutencao é  uma List de um objeto com string nome e string status. Apenas isso. Como ficaria?
Comment: Cria um método que que realize isso para você. Onde você verificaria  o status dentro de um for ficarias mais fácil.
Answer: Coso, você esteja usando JDK 8 pode usar  lista.forEach(action). Eu varia um método para isso.
public Integer totalStatus ( List<ProdutoManutencao> lista, String status){
      Integer  result = 0;
      //validacao para a  lista null ou status.
     for (ProdutoManutencao object : lista) {
         result += object.stattus.equals(status) ? 1 : 0;
      }
     return result;
  }
}

No seu .xhtml você pode chamar o seu método. Poder ser um método mais curto que ja faca isso direto no seu Bean sem  precisar passar parâmetros.
<h:outputText value="#{cur.totalStatu( cur.listaProdutosManutencao() ,"1") }" />


how to obtain remote access port in azure webservice

Question: I deployed a web service, I enabled remote access. I can connect to the VM through the MS remote connector using the file downloaded from portal.
But where I can find the VM remote access port?
the "connect" filed downloaded from Azure portal do not include PORT.
any Idea?
Comment: Which Azure service are you actually using? (1) Azure Virtual Machine, (2) Azure Cloud Service or (3) Azure Web App?
Comment: @AlexLau Azure Cloud Service
Answer: You can find the enabled endpoints inside the cloud service dashboard under input endpoints on the right.
RDP is usually 3389. Azure RDP is a bit more complicated than usual, since the file you download to connect to a particular instance contains routing information that defines how the client will connect to the particular instance since the cloud service has a single public ip and a single port which is load balanced between the instances.
You will find that it is quite hard to setup the RDP connection in a third party app without somehow using the downloaded file.
Comment: Yes I see that it is hard to setup in third party, this why I'm asking here maybe someone know how :(
Comment: It depends on what the remote desktop client is, so you might want to include this in your question. (i.e. remote desktop client for mac works fine)


Vectors which do not belong to column space also pass the test which is the passed by the vectors in column space

Question: In the book Linear algebra and it's application by Gilbert Strang, it is given that
We have an augmented matrix for system of linear equations $ Ax=b$ as:
\begin{bmatrix}1&2&3&5&b_1\\2&4&8&12&b_2\\3&6&7&13&b_3\end{bmatrix}
After applying gaussian elimination:
\begin{bmatrix}1&2&3&5&b_1\\0&0&2&2&b_2-2b_1\\0&0&0&0&b_3+b_2-5b_1\end{bmatrix}
Description of Column space of A:  The column space contains all vectors with $b_3+b_2−5b_1=0$.
That makes $Ax = b$ solvable, so $b$ is in the column space. All columns of $A$ pass this
test $b_3 +b_2 −5b_1 = 0$. This is the equation for the plane (in the first description of
the column space).
My question is this: is correct to say that "The column space of $A$ contains all vectors with $b_3+b_2−5b_1 = 0$"?
I know that all the vectors in column space of $A$ will pass this test $b_3+b_2-5b_1$ but wont there be vectors outside the column space of $A$ which also pass this test? So, should we say " the column space of $A$ contains all vectors which pass the test"?
Answer: You can prove the converse as well. If $b_3+b_2-5b_1=0$ then we will be able to solve the augmented system with infinitely many solutions and hence $b$ will belong to the column space. As an example, $A[0,0,5b_2/4-3b_1,2b_1-3b_2/4]^T=b$.
Comment: Thanks! this is simple argument to prove it. I was trying to find general equation of the plane formed by column space and proving that there exists a vector [d1,d2,d3] which doesn't belong to this plane of column space and d2+d3-5d1=0.


Trigonometric Idntities under the condition $A+B+C=π$

Question: If $$A+B+C=\pi$$, prove that
$$\cos\frac{A}{2}+\cos\frac{B}{2}+\cos\frac{C}{2}=4\cos\frac{\pi-A}{4}.\cos\frac{\pi-B}{4}.\cos\frac{\pi-C}{4}$$.
My solution:
Here
$$A+B+C=\pi$$
$$A+B=\pi-C$$
Taking 'sine' on both sides gives
$$\sin(A+B)=\sin C$$.
Now,
$$L.H.S=\cos\frac{A}{2}+\cos\frac{B}{2}+\cos\frac{C}{2}$$
Which formula should I use now? Please help.
Comment: Any particular reason for taking sine
Comment: @Archis, I haven't any particular reason for taking sine.
Answer: \begin{align}\textrm{LHS}&= \left(\cos\frac{A}{2}+\cos\frac{B}{2}\right)+\cos\frac{C}{2}\\ &= 2\cos\frac{A+B}{4}\cos\frac{A-B}{4} + \sin\frac{A+B}{2}\\ &= 2\cos\frac{A+B}{4}\cos\frac{A-B}{4} +2\sin\frac{A+B}{4}\cos\frac{A+B}{4}\\&=2\cos\frac{A+B}{4}\left[\cos\frac{A-B}{4} + \sin\frac{A+B}{4}\right]\\ &= 2\cos\frac{A+B}{4}\left[\cos\frac{A-B}{4} +\cos\left({\pi\over 2} - \frac{A+B}{4}\right)\right]\\ &= 2\cos\frac{A+B}{4}\left[2\cos\frac{\frac{A-B}{4}+\frac{\pi}{2}-\frac{A+B}{4}}{2}\cos\frac{\frac{\pi}{2}-\frac{A+B}{4}- \frac{A-B}{4}}{2}\right]\\ &=2\cos\frac{A+B}{4}\left[2 \cos\frac{\pi -B}{4}\cdot \cos\frac{\pi-A}{4}\right] \\ &= 4\cos\frac{\pi -A}{4}\cdot \cos\frac{\pi -B}{4}\cdot \cos\frac{\pi-C}{4}  \\ &= \rm {RHS}\;.\end{align}
Comment: Why the downote?
Comment: oops! it seems you have literally copied this answer.
Comment: @Bhaskara-III: WTF!
Comment: @Bhaskara-III: BTW, whose answer have I copied from?
Answer: Let $\dfrac{\pi-A}4=x$ etc. $\implies A=\pi-4x$
and $\sum4x=3\pi-\sum A=2\pi\iff x+y+z=\dfrac\pi2$
$$\cos\dfrac A2=\cdots=\sin2x$$
$$\sin2x+\sin2y+\sin2z=2\sin(x+y)\cos(x-y)+2\sin z\cos z$$
$$=2\sin(\pi/2-z)\cos(x-y)+2\cos z\sin\{\pi/2-(x+y)\}$$
$$=2\cos(z)\cos(x-y)+2\cos z\cos\{(x+y)\}$$
$$=2\cos(z)\{\cos(x-y)+\cos(x+y)\}$$
Can you take it from here?
Comment: which formula did you use in the second step as I haven't read about it till now and hence, did not understand...
Comment: @Iaamuseruser, Are you talking about $\sin2x+\sin2y,$ then see http://mathworld.wolfram.com/ProsthaphaeresisFormulas.html
Comment: I  am asking about $$\sum4x=3\pi-\sum A$$
Comment: @Iaamuseruser, $$4x=\pi-A$$ right  $$4(x+y+z)=3\pi-(A+B+C)$$ and $A+B+C=\pi$
Answer: Notice, the trig identity: $\cos x+\cos y=2\cos\left(\frac{x+y}{2}\right)\cos\left(\frac{x-y}{2}\right)$,
Now, consider $$LHS=\cos\frac A2+\cos\frac{B}{2}+\cos \frac C2$$
$$=\left(\cos\frac A2+\cos\frac{B}{2}\right)+\cos \frac C2$$
$$=2\cos\left(\frac{\frac{A}{2}+\frac B2}{2}\right)\cos\left(\frac{\frac{A}{2}-\frac B2}{2}\right)+\cos \left(\frac{\pi-A-B}{2}\right)$$
$$=2\cos\left(\frac{A+B}{4}\right)\cos\left(\frac{A-B}{4}\right)+\sin \left(\frac{A+B}{2}\right)$$
$$=2\cos\left(\frac{A+B}{4}\right)\cos\left(\frac{A-B}{4}\right)+\sin 2\left(\frac{A+B}{4}\right)$$
$$=2\cos\left(\frac{\pi-C}{4}\right)\cos\left(\frac{A-B}{4}\right)+2\sin \left(\frac{A+B}{4}\right)\cos \left(\frac{A+B}{4}\right)$$
$$=2\cos\left(\frac{\pi-C}{4}\right)\cos\left(\frac{A-B}{4}\right)+2\sin \left(\frac{A+B}{4}\right)\cos \left(\frac{\pi-C}{4}\right)$$
$$=2\cos\left(\frac{\pi-C}{4}\right)\left[\cos\left(\frac{A-B}{4}\right)+\cos \left(\frac{\pi}{2}-\frac{A+B}{4}\right)\right]$$
$$=2\cos\left(\frac{\pi-C}{4}\right)\left[2\cos\left(\frac{\frac{A-B}{4}+\frac{\pi}{2}-\frac{A+B}{4}}{2}\right)\cos\left(\frac{\frac{A-B}{4}-\frac{\pi}{2}+\frac{A+B}{4}}{2}\right)\right]$$
$$=4\cos\left(\frac{\pi-C}{4}\right)\left[\cos\left(\frac{\pi-B}{4}\right)\cos\left(\frac{\pi-A}{4}\right)\right]$$
$$=4\cos\left(\frac{\pi-A}{4}\right)\cos\left(\frac{\pi-B}{4}\right)\cos\left(\frac{\pi-C}{4}\right)=RHS$$
Comment: @ Harish, could you please tell me that your book 'Advance Geometry' is for which level(or grade/class)?
Comment: Thanks for asking. This book is not actually class specific, however anyone, interested in Geometry usually at higher level, can  refer to it as it mainly deals with the detailed study of solid angle in 3-D & some other articles in 2-D Geometry.
Comment: is it available for sale in India only or overseas, too?
Comment: Yes, it is available in India & overseas by online distributors like Amazon, Flipkart etc.
Comment: What is its MRP then?
Comment: Its MRP may vary depending on the distributor. You can get all details about book's  MRPs through the link: https://notionpress.com/read/advanced-geometry-1294526


Get information to create ALTER TABLE ADD FOREIGN KEY

Question: How to get the information to update an already existing foreign key..
When updating a foreign key referemce in phpmyadmin this query is sent to the server
ALTER TABLE `dimension` ADD FOREIGN KEY (`test_id`) REFERENCES `db`.`test`
(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

But how do I get the status ON DELETE and ON UPDATE to sending and updating the alter table query?
Answer: You can't.  You have to drop the existing foreign key constraint and add a new one.
However, you can fetch the existing reference_option from the INFORMATION_SCHEMA:
SELECT CONSTRAINT_NAME, UNIQUE_CONSTRAINT_NAME, UPDATE_RULE, DELETE_RULE
FROM   INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
WHERE  CONSTRAINT_SCHEMA = DATABASE()
   AND UNIQUE_CONSTRAINT_SCHEMA = DATABASE()
   AND TABLE_NAME = 'dimension'
   AND REFERENCED_TABLE_NAME = 'test'

Or else from SHOW CREATE TABLE:
SHOW CREATE TABLE dimension

Comment: Added `CONSTRAINT_NAME` in the Select list, as you may have more than one FKs from one table to another.
Comment: yes, but how can I retrieve the ON DELETE and ON UPDATE status from an existing key?
Comment: @eggyal You may also want to add `AND UNIQUE_CONSTRAINT_SCHEMA = DATABASE()` in the conditions (that's the database of the referenced table (`test` here) and the `UNIQUE_CONSTRAINT_NAME` in the Select list (that's the referenced Unique (or Primary) Key (in test here).
Comment: @ypercube:  All true enough!  Thanks for thinking so thoroughly about it.  :)


Static IPv4 and dynamic IPv6 on same interface

Question: I am trying to set up a CentOS 5.4 box to use a static IPv4 address, while getting a dynamic IPv6 address at boot time.
I have only one interface, apart from the loopback interface, eth0. It has a static v4 and internet connectivity (I can SSH in). However, it doesn't get an IPv6 by default.
I have enabled IPv6 in /etc/sysconfig/network and I have added IPV6INIT=yes to the config in /etc/sysconfig/networking/devices/.
If I use dhcp6c it does get a valid IPv6 address, but the main question is how do I configure it to get one at boot-time?
Answer: In the end, the answer is simple. One has to put several options in the /etc/sysconfig/networking/devices/ files.
The first is IPV6INIT=yes, obviously, to enable IPv6 on that interface. Now, to enable DHCPv6 so you get an adress at boot time, you also have to add DHCPV6C=yes. That fixed it for me.
So you have at least these two lines:

IPV6INIT=yes
  DHCPV6C=yes

That's it :-)
Answer: The first step would be to check if the interface is getting the default link-local fe00:* and any-castff00: addresses.
If you are not using dhcp6 (and i personally prefer not to) then you need to configure the router to broadcast teh default routs etc. perhaps you have already done this?
You can use the radvdump program to verify that the router is sending advertisements and they are getting to this box.
Comment: It does get a link-local address, this is not the problem. Due to the infrastructure of the network I need dchp6c. There is no ra daemon running on our network.
Comment: if you see the link local addresses then ip6 is basically working. The RA stuff wont help you, though I will leave it in for others who come across this question.


Nginx, Bad Request and percent in URL

Question: I have an url like this: "mydomain.com/dictionary/Elastizit%E4t.htm".
I know the url sucks, I'm migrating a very old site and for SEO reasons we need to make redirects from the old urls to the new ones. So for the time being I have something like 14000 URLs like this and I need to redirect them to their new companions or follow some redirect rules defined in my django/python webserver.
If the URL would hit my python app, I'd be able to handle it like this:
<code>>>> from urllib.parse import unquote
>>> unquote('Elastizit%E4t.htm', encoding='latin')
'Elastizität.htm'
</code>
However, nginx itself breaks with a 400 Bad Request.
My Nginx config is very simple:
<code>server {
    listen 80;
    server_name mydomain.com;
    client_max_body_size 10M;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /srv/mydomain.com/shared/public;
    }

    location / {
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;

        include proxy_params;
        proxy_pass http://unix:/srv/mydomain.com/current/gunicorn.sock;
    }
}
</code>
It's important to me, that the webserver itself utf-8, I don't want to have iso-8859-1 and friends as my default encoding.
Comment: `recv() not ready (11: Resource temporarily unavailable)` while nginx is trying to talk to gunicorn... This has nothing to do with character encoding.
Comment: What do your nginx debug logs say?
Comment: Interestingly, the debugging log contains the correct encoding ... https://dpaste.de/OomL
Comment: Hm, I'm not sure if that really belonged together. If I now do it again, the debug log does not fill at all.
Comment: oh, it belongs together, sorry. there is a debug log. However, my webapp has a 400 Page that isn't shown. Therefore it should happen in gunicorn, which in turn has nothing in it's logs.
Comment: I can see it in the gunicorn logs if i enable debug mode there. So nginx is out of the way.
Answer: It turned out to be a bug in most python frameworks, aka https://code.djangoproject.com/ticket/25623 and https://github.com/Pylons/pyramid/issues/2047.

Nginx, Bad Request and percent in URL


Why are spin bowler classed as either an off spin or leg spin bowler?

Question: It just seems to be weirdly specific for a bowler to only bowl one type of spin.
Isn't there a strategic advantage in being able to spin the ball both ways and therefore can surprise the batsmen? Is there a technical reason why a spin bowler would only focus on one type of spin?
Answer: The thing to remember here is that what is traditionally described as "leg spin" and "off spin" is actually a description of the technique used to spin the ball: leg spinners use the wrist to impart spin, while off spinners use the fingers. They are completely different techniques, which is why bowlers typically do only one or the other.
That said, both wrist spinners and finger spinners have always had variations which do spin differently from the their stock ball. While for a right-armed wrist spinner the stock ball turns from right to left as viewed by the bowler:

The googly turns from left to right.
The topspinner has no significant turn but instead has extra bounce, aiming to induce an error from a batter who expects the ball to turn when it does not.
The flipper is the inverse of the topspinner and has no significant turn but instead less bounce.

There are then also balls with mixed spin, for example the slider which is a combination of the stock ball's sidespin and the flipper's backspin. As you can see from all those, wrist spinners already have the ability to spin the ball so that the axis of rotation is pointing in almost any direction1.
Finger spinners have traditionally had less variation; the arm ball was for many years essentially the only variation, again achieving success due to the lack of turn rather than turning significantly in the opposite direction. In recent years, the doosra, which does genuinely turn in the opposite direction to the finger spinner's stock ball, has been invented, along with controversy and changes to the Laws as to whether it can be bowled legally or not. Finger spinners have also been experimenting with other techniques, most notably the carrom ball.
tl;dr: spinners do spin the ball in "both" directions, they just do it via different techniques.

1. Any direction with the axis of rotation parallel to the ground anyway - i.e. pitch and roll in aeronautical terms. No spinner can produce any significant amount of "yaw" spin with the axis of rotation perpendicular to the ground just because of the way the arm works.


performFetchWithCompletionHandler não sendo chamado em produção

Question: Estou implementando um app em Swift 2 que faz requisições à um feed xml de tempos em tempos, e dispara uma notificação local. Para tal, estou usando o método performFetchWithCompletionHandler no AppDelegate. Localmente, usando meu aparelho, o método é chamado normalmente. Mas já em produção, testando via Testflight, ele nunca é chamado... Eu preciso implementar algo para que ele dispare em produção? O que acontece nesse caso que meus beta testers não recebem notificações automáticas?
PS: estou usando Parse.com, e quando mando notificações manuais, eles recebem
Comment: As requisições de tempos em tempos, seria em torno de quanto tempo? O app está em estado terminado? Se possível coloque o código em que você realiza estas questões
Comment: @Gian, o tempo seria o mínimo possível... Agradeço muito pela ajuda, mas como precisava de algo mais rápido, encontrei uma maneira de resolver esse problema usando Push Notifications com o Parse.com mesmo... Vou postar o código explicando como fiz, pra deixar de informação futura :)
Answer: O problema foi contornado, utilizando agora Push Notifications ao invés de Local Notifications. O próprio parse.com oferece um recurso chamado Cloud Code, onde é possível escrever uma task para ler o feed de tempos em tempos e disparar push notifications. Segue o código comentado abaixo:
Lembrando que o código é feito em Javascript, referenciando as bibliotecas XMLReader e SAX
var xmlreader = require('cloud/xmlreader.js');

var url = "http://www.zelda.com.br/rss.xml";

function SavePost(title, link){
    var PostClass = Parse.Object.extend("Post");
    var post = new PostClass();
    post.set("title", title);
    post.set("link", link);
    post.save();
}

function SendPush(title, link){
    var query = new Parse.Query(Parse.Installation);
    Parse.Push.send({
        where: query,
        data: {
            url: link,
            alert: title,
            sound: "default"
        }
        }, {
            success: function() {
                SavePost(title, link);
            },
            error: function(error) {
            console.log("Error sending push: " + error);
        }
    });
}

Parse.Cloud.job("fetchPosts", function(request, response) {
    Parse.Cloud.httpRequest({
        url: url,
        success: function(httpResponse) {
            var responseText = httpResponse.text;

            xmlreader.read(responseText, function (err, res){
                var newPost = res.rss.channel.item;

                var title = newPost.array[0].title.text();
                var link = newPost.array[0].link.text();

                var PostClass = Parse.Object.extend("Post");
                var query = new Parse.Query(PostClass);
                query.equalTo("link", link);
                query.find({
                    success: function(results) {
                        if (results.length == 0){
                            SendPush(title, link);
                        } else {
                            response.error("Post already pushed");
                        }
                    }
                });
            });
        },
        error: function(httpResponse) {
            console.error('Request failed with response code ' + httpResponse.status);
            response.error("Error fetching posts from feed");
        }
    });
});


How do I build a form for creating a post that belongs to a user?

Question: Im a rails beginner on rails 4 and I'm learning by doing. I have users and posts on my simple test app. My user model
has_many :posts

My post model
belongs_to :user

I have a form partial for creating a new post like this
<%= form_for @post do |f| %>
<% if @post.errors.any? %>

        <% @post.errors.full_messages.each do |msg| %>

<%= msg %>

        <% end %>

<% end %>
<%= f.label :title %>
<%= f.text_field :title %>

<%= f.label :body %>
<%= f.text_area :body %>

<%= f.submit %>

My routes file
resources :users do
  resources :posts, except: [:index]
end

When i try to create a new post, I get a
No route matches [POST] "/posts"
Im assuming that its not working because of how my form partial is set up. I think that the
form_for @post do |f|

needs to be different, but I'm not sure what to change it to. Any suggestions? Thanks.
Comment: It should be something like `form_for [@user, @post] do |f|`
Answer: for this route
resources :users do
  resources :posts, except: [:index]
end

You must create form with
form_for [@user, @post] do |f|

or
form_for [current_user, @post] do |f|

Comment: Thanks, that was it. I used the [current_user, @post] and its working. Now I need to figure out how to print the name of the user that posted it.
Answer: You should remove the except: [:index] from the route. That must block /posts access.
Comment: Thanks for the reply. I have the except, [:index] in there so I can view all the posts in the app regardless of the user that posted them. I have it redefined as resources :posts, only [:index] later, but I kept that out of this question for brevity.
Comment: @oobie11 Run `rake routes`. Do you see something like `/posts`? It should be `users/:id/posts` instead. And also you need to remove `except` part.
Comment: Your link for "index" is "GET /posts". And for the "create" is "POST /posts". I think if you are blocking index, so the create will be blocked too and you created form won't work.


Jordan form and basis for 5 x 5 matrix

Question:

Is anybody able to explain the solution to part c of this question above? I don't understand how the characteristic polynomial was determined, or how the basis was found.
Comment: Sorry, I meant minimal polynomial above. Since the characteristic polynomial has same roots as the minimal polynomial, it must be $x^5$. The minus is irrelevant: some people define characteristic polynomial as $\det(A- x I)$ while others define it as $\det (xI-A)$. The difference is simply a sign.
Comment: The picture is hardly readable. I think this solution is cheating because, when asked to calculate characteristic polynomial, nobody would ever try calculating $A^3$ first. My advice is don't read this solution. Instead go through the general algorithm of Jordan normal form computation.
Comment: @WhatsUp How does $A^3=0$ determine the characteristic polynomial? Also the general algorithm gets very messy with this matrix, so I'm definitely missing something.
Comment: $A^3 =0$ means the characteristic polynomial divides $x^3$, and $A^2 \neq0 $ means the characteristic polynomial does not divide $x^2$.
Comment: In general computations with matrices of size $5$ or larger are indeed messy to do with hands. That's why we need computers. But at educational level one should probably do some examples by hand to understand the method.
Comment: Do you mean $x^3$ divides the characteristic polynomial? Also where did the negative come from in the characteristic polynomial? I think the point of the question is that it can be done without using a computer, I just don't understand the tricks used.
Comment: Do you know how the basis vectors were found? I'm not familiar at all with the method used above.
Comment: @WhatsUp It's not at all unreasonable to examine powers of the matrix here since it's traceless, hence nilpotent. We therefore already know its characteristic polynomial.
Comment: @amd But traceless only says that the sum of eigenvalues is zero, not that it's nilpotent. E.g. $\begin{pmatrix} 0 & 1\\1 & 0\end{pmatrix}$.
Comment: @WhatsUp Its determinant is also obviously zero.
Comment: @amd Even then it only says that sum of eigenvalues is zero and product of eigenvalues is zero. E.g. $\begin{pmatrix}0 & 1 & 0\\1& 0 & 0\\0& 0& 0\end{pmatrix}$.
Comment: @WhatsUp Fair enough. The two observations enough to suspect a nilpotent matrix in an articificial exercise, at any rate, so my initial comment stands: it's not unreasonable to examine powers of this matrix before grinding through generic methods. Not sure that really saves much work overall, though.
Comment: @amd Imagine there are five complex numbers. You know that their sum and product are zero. And you guess "are they all zero?" and the guess costs you some time (doing two matrix multiplications) while there are methods that guarantee to find the answer in not so much more time. If the guess fails then you don't get anything...
Comment: @WhatsUp You know a lot more than that in this case. It's quite easy to see by inspection that at least three of those numbers are zero.
Answer: First of all, from examining simple linear combinations of $A$'s columns, we can quickly see that its rank is at most two. In addition, its first two rows are obviously linearly independent, hence its rank is exactly two. So, we know that it has zero as an eigenvalue with geometric multiplicity $3$, and therefore that $x^3$ divides its characteristic polynomial.
Since the matrix is also traceless, instead of computing the characteristic polynomial directly as $\det(\lambda I-A)$, the solution makes a leap of faith (or uses insider knowledge) and guesses that $A$ might be nilpotent. Since we know that the geometric multiplicity of $0$ is three, this only requires checking at most $A^2$ and $A^3$. I'm not sure that this really saves that much work over the general method, though. As we see in the solution, $A^2\ne0$ but $A^3=0$, so the matrix is indeed nilpotent. Nilpotent matrices only have $0$ as an eigenvalue, which gives us the characteristic polynomial $x^5$, with minimal polynomial $x^3$. It looks like this text uses $\det(A-\lambda I)$ instead of $\det(\lambda I-A)$, which is why the book solution has $(-x)^5$ instead. The latter equivalent definition guarantees a monic polynomial for any order matrix.
The solution proceeds conventionally from there. There's only one nontrivial Jordan block, so a simple-looking vector that's not in $\ker(A^2)$ is chosen to start the chain. After that, the remaining two basis vectors are found by inspection. The first two columns of $A$ are equal, so $\mathbf e_1-\mathbf e_2$ is a null vector of $A$, as is $\mathbf e_5$ because the last column is zero. You should verify that the three vectors in the Jordan chain together with these two are linearly independent.

Jordan form and basis for 5 x 5 matrix


How to manually define props type in vue3 with typescript

Question: I can do
defineComponent({
  props: {
    name: { type: String as PropType<string> }
  }
})

to tell vue3 that my props type is { name: string }, but if I have several component have the same props type, how can I share the defination?
If I define props in :
const props = {
  name: String as PropType<string>
}

then use it like this:
defineComponent({
  props: props,
})

It won't work, the type I got in setup function of props is not right.
Answer: this answer is purely addition to @Xinchao's answer.
one way is to destructure common props like following:
// taken from @Xinchao's answer
const commonProps = {
  name: { type: String as PropType<string> }
}

defineComponent({
  props:{
    ...commonProps,

    extra: { }

  }
})

another way is to write function which returns specific object like following
function getStringProp(required=false) {
    return {
       type: String as PropType<string>,
       required,
       default: '',
    };
}

defineComponent({
  props:{
    name: getStringProp(true),
    nickName: getStringProp(),
    extra: { }

  }
})

this case specifically come handy where prop is Array or Object; where we can cast the type like following
function getArrayProp<T>(required=false) {
    return {
       type: Array as PropType<T[]>,
       required,
       default: () => [],
    };
}

defineComponent({
  props:{
    options: getArrayProp<Options>(true),
    stringOptions: getArrayProp<string>(true),
  }
})

Answer: The props options provided for defineComponent is a plain js object solely for type annotation purpose, so you can employ whatever technics in javascript for sharing structures between objects:
// in common.ts
export const commonProps = {
  name: { type: String as PropType<string> }
}

// in your component.vue
import commonProps from "./common.ts";

defineComponent({
  props:{
    ...commonProps,

    extra: { }

  }
})

Answer: If you're using the composition API with Vue 2 in preparation for switching to Vue 3, you have to use the PropType from that package instead of the vue package.
// Wrong for Vue 2
import Vue, { PropType } from 'vue'
import { defineComponent } from '@vue/composition-api'

// Right for Vue 2
import { defineComponent, PropType } from '@vue/composition-api'

Comment: This was not the question, the author explit wrote "Vue3" not "Vue2"


Mimimum of entire function over unit disc

Question: I'm trying to solve the following question:

Let: $f:\mathbb C\to \mathbb C$ be an entire function, $|f(0)|=1$ and $f$ has exactly $n$ roots in $D(0,\frac{1}{2})$. (Not necessarily distinct)
  Prove that: $$2^n\le Max\{|f(z)|\,;|z|=1\}$$

My idea is the following:
Since $f$ has $n$ roots, so we can write: $$f(z)=(z-z_1)(z-z_2)...(z-z_n)g(z)$$ Which: $g(z_i)\neq 0$ when $z_i$ are the roots of $f$ for $i=1,2,...,n$. because of $\,\,|f(0)|=1$, we shoud have: $$|\Pi_{i=1}^nz_i||g(0)|=1$$ By the hypothesis, $|z_i|\lt\frac12\,$, which mean's: $|g(0)|\gt 2^n$
Now define: $$h(z)=(z-z_1)(z-z_2)...(z-z_n)$$ If i prove that: $1\le Max\{|h(z)|\,;|z|=1\}$, I am done?
Answer: One neat trick to see $\max \{ \lvert h(z)\rvert : \lvert z\rvert = 1\} \geqslant 1$ is to look at the function
$$k(z) = z^n h(1/z).$$
Then $k(0) = 1$, hence
$$1 \leqslant \max \{ \lvert k(z)\rvert : \lvert z\rvert = 1\}.$$
(Note: since $k$ is not constant, the inequality is in fact strict.)
But we have
$$\max \{ \lvert k(z)\rvert : \lvert z\rvert = 1\} = \max \{ \lvert h(z)\rvert : \lvert z\rvert = 1\}.$$
However, as you noted, the maxima of $\lvert h\rvert$ and $\lvert g\rvert$ on the unit circle need not occur at the same point(s), so the maximum of the product can be smaller than the product of the maxima.
A small modification of the argument fixes that, however. The case $n = 0$ is clear, hence we assume $n > 0$ in the following.
If we replace $h$ with a function with the same zeros, the same value at $0$, and $\lvert h(z)\rvert = 1$ for all $z$ on the unit circle, then the assertion follows from $\lvert g(0)\rvert \geqslant 2^n$.
The automorphisms of the unit disk are precisely the functions of the form
$$T_{a,\lambda}(z) = \lambda\frac{z-a}{1-\overline{a}z},$$
where $\lvert a\rvert < 1$ and $\lvert\lambda\rvert = 1$. In particular, we have $\lvert T_{a,\lambda}(z)\rvert = 1$ for $\lvert z\rvert = 1$.
So instead of $(z-z_1)\cdot \dotsc \cdot (z-z_n)$, we look at
$$\tilde{h}(z) = \prod_{k=1}^n \frac{z-z_k}{1-\overline{z_k}\cdot z}.$$
Then $\tilde{h}$ is holomorphic in a neighbourhood of the closed disk $\{ z : \lvert z\rvert \leqslant 2\}$, $\tilde{h}$ has precisely the $z_k,\, 1 \leqslant k \leqslant n$ as zeros,
$$\lvert\tilde{h}(0)\rvert = \prod_{k=1}^n \lvert z_k\rvert < 2^{-n},$$
and $\lvert \tilde{h}(z)\rvert = 1$ for $\lvert z\rvert = 1$.
Then writing $f(z) = \tilde{h}(z) \cdot \tilde{g}(z)$, we have $\lvert \tilde{g}(0)\rvert > 2^n$ and by the maximum modulus principle it follows that
$$\max \{ \lvert f(z)\rvert : \lvert z\rvert = 1\} = \max \{ \lvert \tilde{g}(z)\rvert : \lvert z\rvert = 1\} > 2^n.$$
Comment: oh.... I made a mistake in my idea about the solution of the problem... that's not necessary to have $max(|f|)=max(|g|)max(|h|)$ on the unit circle...
Comment: Right. Missed that. But no big deal, something very similar to $k$ helps. Let me edit.
Comment: I've added a correct proof of the assertion, a small modification, @hamidkamali.
Comment: Nice proof... thanks.


Convert ColdFusion Struct - assign custom key

Question: I am newbie in CFML language and I have a question concerning structs and arrays in ColdFusion. Notice that i am using openBD CFML server.
I have the following object(struct):
<code>{
   "docs":{
      "23_id":{
         "content":[
            "I am"
         ]
      },
      "1_id":{
         "content":[
            "the most"
         ]
      },
      "7_id":{
         "content":[
            "crap coder"
         ]
      },
      "39_id":{
         "content":[
            "in the whole universe!"
         ]
      }
   }
}
</code>
The question: can i modify the above object to(and also retain the order if possible):
<code>{
    "docs": [
        {
            "id": "23_id",
            "lola": "I am"
        },
        {
            "id": "1_id",
            "lola": "the most"
        },
        {
            "id": "7_id",
            "lola": "crap coder"
        },
        {
            "id": "39_id",
            "lola": "in the whole universe!"
        }
    ]
}
</code>
Notice that i need to assign custom keys (id and assign "lola" instead "content"). Are there any pointers to study in order to accomplish the above task?
Any help is appreciated!
Answer: Easy, create a new array, loop your struct, and append the array as you go like so:
<code><cfset str = {
   "docs":{
      "23_id":{
         "content":[
            "I am"
         ]
      },
      "1_id":{
         "content":[
            "the most"
         ]
      },
      "7_id":{
         "content":[
            "crap coder"
         ]
      },
      "39_id":{
         "content":[
            "in the whole universe!"
         ]
      }
   }
}>

<cfset docs = { docs: []}>

<cfloop collection="#str.docs#" item="itm">
    <cfset arrayAppend( docs.docs, {id: itm, lola: str.docs[itm].content[1]} )>
</cfloop>

<cfdump var="#serializeJson(docs)#">
</code>
Comment: "I need to retain the original index"  Just note, that structures do not have a guaranteed order. So the final content will be correct, but there's no guarantee the array elements will be in the same order.
Comment: That's entirely true, we can only be so certain of the order when working with structures, as they are key based and not index based like arrays.
Answer: Do you mean that you want to take the structure and turn it into an array? If so, then yes, you can do that. However, structures don't have an inherent order so you can't retain the order. Your result may come out in the same order, but there's no particular reason why it should.
Basically you want to create a new empty array: []. Then loop over the keys inside docs (use cfloop collection="..."). For each key, append a structure to your array, so your result is an array of structures. Then insert that inside the original variable. Can't be specific without variable names.
Comment: leptinella - I agree with your statement that there is no inherent order to a struct. But there is a "structSort()" function that is relatively powerful.
Comment: I don't need to sort struct. I need to retain the original index
Comment: One more comment. Notice that the first object is a response. So the keys are unknown
Comment: Note that structSort() doesn't return a sorted structure. It returns an array of sorted keys.
Answer: You can definitely do what you say you want to do in the above code. You will end up with an array called doc each index of which will contain a struct with in ID key and a LOLA key. If that is what you want then your code above will work.
I'd say your data construct looks like it might benefit from something else - probably a query object.  But possibly xml or json would be a good choice as well. It looks a little tortured :)
Comment: Thank you for the reply. Of what "your code above will work" are you talking about? I need pointers on how to do this. Thank you again.


PowerEdge 2950: Can E2118 result in E1422

Question: The past few days I've been setting up a used Dell PowerEdge 2950 server. It's been running fine until just now, when it suddenly stopped while running a fairly heavy task (svnadmin verify). The LCD was and is showing the following message:
PowerEdge 2950   E1422 CPU Machine Chk   E2118 Fatal NB Mem CRC
Now, the memory error E2118 seems straightforward. One of the banks is probably broken. I'm running memtest right now.
Update: Well, memtest didn't find any errors, so it's not that easy.
E1422, less so. Is this likely a separate problem, or just a result of E2118? Googling for this code says "update the BIOS" which isn't very specific as to the cause of the problem.
Comment: You're probably going to have to contact Dell to get the definitive answer here.
Answer: E1422 CPU Machine Chk means that the CPU detected an hardware error and stopped operations. It can be related to the other error - memory problem.
You can see here and here for more details.
Answer: If the CPU or memory is having an issue, such as a voltage regulation problem, then it could drop voltages on the shared bus between the memory and the CPU and fault them both.  I was reading some release notes last week for different model Dell server (maybe an R710) where issues can be caused by Intel SpeedStep changing the CPU speed and there being a delay before the memory adjusted speed.   This set up a condition where there could be a fault in the time between.  In that particular case, a BIOS update addressed that issue.
Run a CPU benchmark and a memory benchmark to see if you can recreate the fault.  If so, maybe you can narrow it down to one component or the other.


Imporperly closed questions

Question: Can someone explain to me why my question was closed: Troubleshooting Magento 18.104.22.168 with PHP 7
The linked answer doesn't help anyone resolve the issue I outlined and the selected "answer" isn't even for the right version of Magento.
People aren't reading, they are just clicking to close votes. If I look at the history of the people who voted to close (I wont link accounts) but the action is always Close, Close, Close.
I voted to re-open but quite frankly I am getting fed up.
Comment: It's reopened now.
Comment: You are #1 @Marius - thanks!
Answer: We're very sorry that this keeps happening. We're working hard to combat this problem on Magento.SE.
The question (which was linked as a duplicate) was removed from the comment history. This is the question which was incorrectly marked as a duplicate:
Is Magento ready for PHP 7?
This question is problematic and has been the focus of a number of Magento / PHP7 false duplicates. The close votes tend to pile on, especially quickly when it comes to "duplicate" questions - and so we're actively monitoring for this.
We're watching Meta closely - and Marius caught this very quickly:
From Marius in his reopen:

This is not a duplicate - people can't read! Please remove this flag as it will actually be incorrectly closed. Others have had this issue and it has nothing to do with the link provided.

A way forward
Just so you know this is a problem I've taken upon myself to drive the community and moderator team to resolving. I have opened many meta threads to address just this issue. Here is a blog by Fabian recapping our MageStackDay panel:
https://www.schmengler-se.de/en/2016/06/magestackday-5-and-the-moderation-discussion/
And here's the panel discussion when I expanded on my thoughts that as a community we need to do better on Magento.SE:
https://youtu.be/uthuA56x6Es
Comment: I very much appreciate the thorough answer and that there is a plan to monitor this type of situation. This community is growing and with it comes issues and I'm happy that you and the moderation team have a handle / pulse on it.
Comment: I just had a look at those links, I have to say you guys are awesome, I had absolutely no idea of how much time you guys have been putting in; please accept my apologies for the tone of my comments, I have a new appreciation for what you guys have done / are doing for this community.
Comment: Not a problem. You are one of the helpful people here - please don't get discouraged. Feel free to reach out to me directly when you feel that things are frustrating.
Comment: Again much appreciated :)

Imporperly closed questions


Print staments are lost when execute a python file from subprocess.call method

Question: I am running a Python code where I am executing a command to run another python file by using subprocess.call() method.
The file I execute inside the subprocess.call() has some print statements in it but those statements are not printed on the console when I run this code.
Is there a way I can get them printed on the console ? Everything works fine when I execute this file standalone and not through the subprocess.call().
If I redirect the output of this command to a file then it gets printed in the file, but could not find a way to see it on console at runtime.
Any help would be appreciated
Comment: Double check that you really need to use subprocess to run a python program and can't just import it. There are many reasons to do this way, and it will most likely solve your problem either
Comment: Please [edit] to include your current code.
Answer: subprocess call has default params: stdout=None, stderr=None which you need to configure or use capture_output=True, see following docs: https://docs.python.org/3/library/subprocess.html
Answer: You might want to use subprocess.PIPE:
p = subprocess.call(..., stdout=subprocess.PIPE)
output, _ = p.communicate()
print(output)

(Written in the browser, but should work)
Btw, it's hard to understand your problem and suggest a solution when you don't provide any code (neither which you run with subprocess nor which uses it). Please, add it to get more specific and/or relevant answers
Comment: @Ashgonline, did this help?


How to add html to the "My user points" page (user points module)

Question: I am building a Drupal 7 site using the User Points module.
I have some issues that I am not able to solve, you can see the issue here.
I can go around these issues if I will be able to edit the HTML of the "my user points" page (the page that every user can see the points he got and the reason he got them).

Mainly, I want to add a link in this page, that will link to another page on my site.
In addition, I want to add some text beneath the title of the page (original title).
Third thing I want to do is make sure the output on the "Reason column" will be longer, and won't cut off and be too short with "..." in the end.

How can I achieve that?
Where and how I can find the HTML of this page, and edit & add some HTML code?
Answer: You can find the menu path defined for " My User Points " page in userpoints.module file in hook_menu implementation..
<code>  $items['myuserpoints'] = array(
    'title' => 'My !points',
    'title arguments' => userpoints_translation(),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('userpoints_list_transactions'),
    'access callback' => 'userpoints_access_my_points',
    'file' => 'userpoints.pages.inc',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu',
  );
</code>
As you see above..
Page callback drupal_get_from with arguments "userpoints_list_transactions" is defined in "userpoints.pages.inc" file...
<code>/**
 * Displays a detailed transaction report for an individual user.
 *
 * @param $account
 *   For which account to display. Defaults to the current user.
 */
function userpoints_list_transactions($form, &$form_state, $account = NULL, $tid = NULL) {

  // If this is an AJAX request, update $_GET['q'] so that table sorting and
  // similar links are using the correct base path.
  if ($_GET['q'] == 'system/ajax') {
    $q = 'myuserpoints';
    if (!empty($account)) {
      $q = 'user/' . $account->uid . '/points';
    }
    $_GET['q'] = $q;
  }

  if (empty($account)) {
    global $user;
    $account = $user;
  }

  $settings = array(
    'show_user' => FALSE,
  );
  $header = userpoints_get_transaction_header($settings);

  $query = db_select('userpoints_txn', 'p')->extend('PagerDefault')->extend('TableSort')
    ->fields('p')
    ->condition('p.uid', $account->uid)
    ->orderByHeader($header)
    // Enforce consistent sort order.
    ->orderBy('p.txn_id', 'DESC')
    ->limit(variable_get(USERPOINTS_REPORT_LIMIT, 10));

  if (module_exists('taxonomy')) {
    $query->leftJoin('taxonomy_term_data', 't', 'p.tid = t.tid');
  }

  $unapproved_query = db_select('userpoints_txn', 'p')
    ->condition('uid', $account->uid)
    ->condition('status', USERPOINTS_TXN_STATUS_PENDING);
  $unapproved_query->addExpression('SUM(points)');

  $values = userpoints_filter_parse_input($form_state, $tid);
  $active_category = userpoints_filter_query($query, $values);
  userpoints_filter_query($unapproved_query, $values);

  if (isset($active_category)) {
    drupal_set_title(t('!Points for @username (%category category)', userpoints_translation() + array('%category' => $active_category, '@username' => format_username($account))), PASS_THROUGH);
    $total_title = t('Total !points (%category category)', userpoints_translation() + array('%category' => $active_category));
  }
  else {
    drupal_set_title(t('!Points for @username', userpoints_translation() + array('@username' => format_username($account))));
    $total_title = t('Total !points', userpoints_translation());
  }

  $rows = array();
  foreach ($query->execute() as $transaction) {
    $rows[] = userpoints_get_transaction_row($transaction, $settings);
  }

  // Store context in the output array so that modules have access to it.
  $output = array(
    '#account' => $account,
    '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'userpoints') . '/userpoints.css',
      ),
    ),
  );

  $output['form'] = userpoints_filter_form($account, $values);

  $output['list'] = array(
    '#type' => 'container',
    '#id' => 'userpoints_list_wrapper',
  );
  $output['list']['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No !Points earned', userpoints_translation()),
    '#weight' => -5,
    '#attributes' => array('class' => array('userpoints-myuserpoints-list')),
  );
  $output['list']['pager'] = array(
    '#markup' => theme('pager'),
    '#weight' => 0,
  );

  // Fetch pending (not yet approved) points according to the category filter.
  $pending = (int)$unapproved_query
    ->execute()
    ->fetchField();

  // Display both pending and approved points in a simple table.
  $output['list']['summary_table'] = array(
    '#theme' => 'table',
    '#header' => array(
      array(
        'data' => $total_title,
        'colspan' => 2,
      ),
    ),
    '#rows' => array(
      array(
        'data' => array(t('Approved !points', userpoints_translation()), userpoints_get_current_points($account->uid, isset($values['tid']) ? $values['tid'] : 'all')),
        'class' => array('userpoints-myuserpoints-total-approved'),
      ),
      array(
        'data' => array(t('Pending !points', userpoints_translation()), $pending),
        'class' => array('userpoints-myuserpoints-total-pending'),
      ),
    ),
    '#weight' => 10,
    '#attributes' => array('class' => array('userpoints-myuserpoints-total')),
  );

  // For simplicity, the generated output is passed to a custom alter function.
  // This would also be possible through hook_page_alter(), but that hook is
  // hard to use.
  drupal_alter('userpoints_list_transactions', $output);

  return $output;
}
</code>
In the end you can see generated output is passed to a custom alter function
<code>  drupal_alter('userpoints_list_transactions', $output);
</code>
By implementing hook_TYPE_alter()  in your custom module you can able to change the output..
i.e YOURMODULENAME_userpoints_list_transactions_alter function you need to implement..
<code>/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
}
</code>
$output is a form variable.. You can add a new element to $output ..
<code>/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
  $output['custom_text']['my_link'] = array(
    '#markup' => l("LINK", "Your Link"),
  );
  $output['custom_text']['my_text'] = array(
    '#markup' => 'Blah Blah',
  );
}
</code>
Comment: thank you for the quick answer! Mainly, I want to add a link in this page, that will link to another page on my site. In addition, I want to add some text in some place. How can I achieve that? Does "changing $output" is just writing HTML?
Comment: See my updated answer .. $output is a form variable..
Comment: Working Great! Thanks! Can I control the place the HTML output will be? I know I can play with the CSS as well, but is there a way to do that with the custom module I created? I want to insert a sentence with link beneath the h2 title, can I even do that?
Comment: Can you update your Question with screenshot or post another question with details ?
Comment: I updated my question. Please let me know if you need any more info.


The characteristic polynomial of $A$ is $\lambda^3(\lambda-1)$. Is $x\mapsto Ax$ surjective?

Question:
Suppose the characteristic polynomial of $A\in M_4(\mathbb R)$ is $p(\lambda)=\lambda^3(\lambda-1)$. The mapping
  $A:\mathbb{R}^4 \rightarrow \mathbb{R}^4 $ defined as $A(x)=Ax$ is surjective for some matrices $A$ and for some not. True or false?

My approach:
Since the mapping is from/into the same space, if the operator is surjective then it's also injective ( $\mathbb{dim}N(A)=0$). We know the eigenvalues for this operator: $\lambda_1=1,\lambda_2=\lambda_3=\lambda_4=0$. Since $\mathbb{dim}N(A-\lambda I)\neq0$ (if it was $=0$ then $(A-\lambda I)x=0$ would be true only for $x=0_v$ which is impossible). So we conclude that for the given eigenvalues there isn't such a matrix $A$ that is surjective. So the statement is FALSE.
Comment: That's correct. You can make it shorter: the key point is indeed that surjective $\leftrightarrow$ injective. Then you can simply observe that $0$ being an eigenvalue exactly means  the linear map is *not* injective.
Comment: @Bernard thank you for the hint
Comment: Is $p$ the characteristic polynomial of $A$?
Comment: Yes it is. @lhf
Answer: What Bernard said in comments sums it up, but for the sake of having answer, I'll write it down.
First of all, your argumentation is correct. Just a few observations.
As you said, if you have linear map $A\colon V\to W$ such that $\dim V = \dim W < \infty$, then $A$ is injective iff $A$ is surjective iff $A$ is bijective. This is a simple consequence of rank-nullity theorem.
That said, if $\lambda$ is eigenvalue of $A\in L(V)$, then by definition it means that there exists $v\neq 0$ such that $Av = \lambda v$, i.e. eigenspace $\ker(A-\lambda I)$ of $\lambda$ is non-trivial. It follows that $A-\lambda I$ is not injective, and hence not invertible, or $\det(A-\lambda I) = 0$. The converse is true as well, which gives us that eigenvalues are precisely the roots of the characteristic polynomial.
But, the point we need here is that $A$ is not injective if and only if $0$ is eigenvalue of $A$. Since your operator has $0$ as eigenvalue, it is not injective, and hence not surjective.
Comment: Thank you for the clear explanation


What is diffence between the use of obj.to_i and Integer(obj) in Ruby?

Question: What is diffence between the use of obj.to_i and Integer(obj) in Ruby?
For example:

a = "abc"
a.to_i returns 0

but, if I use:

Integer(a)

The return is:

ArgumentError: invalid value for Integer(): "abc"

Why?
Comment: Because 'abc' isn't and integer and to_i returns 0 because no integer was found
Comment: Also, an error isn't a return. The integer function require an integer parameter, and to_i takes a string and parses and integer if found.
Comment: Hi, I am newbie here... and I can't find other duplicate questian...
Answer: The difference is there in the manual:
String#to_i:

If there is not a valid number at the start of str, 0 is returned.

Kernel#Integer:

In any case, strings should be strictly conformed to numeric representation. This behavior is different from that of String#to_i.


Analytic version of Hahn-Banach using geometric version

Question: When studying the Hahn-Banach theorem, one can demonstrate the geometric version from scratch and use it to prove the analytic version, as is outlined in Hahn-Banach theorem: 2 versions.
To do so, it is necessary to show that the cone $ C = \{(x,t)\,:\,p(x) \lt t\} \subset X $ is open. ¿How is this done?
Answer: The topology you use on $C $ is the product topology, so basic open sets are products of an open set in $E $ and an open set in $\mathbb R $. We can write
$$
C=\bigcup_{t>0}\{x:\ p (x)<t\}\times (-\infty,t).
$$
Comment: Continuity with respect to what? The topology on $E$ is the one given by $p$, so it is generated by the sets $\{x:\ p(x-y)<r\}$.
Comment: And how do we know $ \{x:\ p (x)<t\} $ is open? p is supposed to be semilinear but I'm not sure if that implies continuity
Comment: I'm considering $E$ with a previously defined topology, given by a norm. Now I start to think that this proof doesn't apply to this situation
Comment: That's your choice. But then you are not following the proof in the answer you quoted. And what's your $p$, if it is not related to the topology?
Comment: In my version of the geometric version (from the book by Brezis) $p$ is the Minkowsky functional and the space is normed. I wanted a similar setting to go back. That's because I say that now I see there are different situations
Comment: In a normed space, the Minkowsky functional is the norm.
Comment: I meant the Minkowsky functional for a convex subset, as in the other proof. But I see your point


Registering file type and custom document icon in .NET

Question: I have application that produces files. I would like to connect those files with application so that double-click on file launches my application.
Everything works properly except for annoyance that icon looks same like icon of my application. I would like to have one icon for application and one icon for it's documents.
DefaultIcon value in registry requires "app.exe,1" syntax where 1 is icon index. It seems that .NET resources are not Win32 resources.
I tried following but without success:

Selecting "Embedded Resource" as
file's build action.
Adding icon to resource file.

Only thing that worked is having icon file separated from executable and pointing to it. However, that seems to me like surrender.
Any ideas how to solve this?
Answer: Have you tried setting 2 as the icon index?
EDIT:
I found a way but you have to do it again for every new build.

Open the .exe file in Visual Studio (File -> Open File)
Right click the icon folder and select Add resource
Click the button Import
Select your .ico file
You might have to mess with the icon numbers, I think the lowest number (example 101) will be the application's icon
Remember the new icon number and set it as the index

EDIT 2:
Try this article: http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx
Comment: Yes, I tried quite a few numbers. Only one that returns anything is 32512. And that is my application icon. No number will return icon for document.
Answer: If you are using the Wix toolset (http://www.wixtoolset.org) to install your application, you can get Wix to take care of the file type and document icon registration
Here is my magic Wix incantation:

    <File
        Id="MaAppExe"
        Name="MyApp.exe"
        Source="MyApp.exe" KeyPath="yes" >
    </File>

    <File
        Id='IconMyAppDoc.ico'
        Name='IconMyAppDoc.ico'
        Source='$(var.MyApp.ProjectDir)\Resources\Images\Icons\docicon.ico' />

    <-- File Extension and associated document icon -->
    <ProgId
        Id='MyApp.MyAppExtension'
        Description='My App Data File'
        Icon='IconMyAppDoc.ico'>
        <Extension
            Id='MyApp'
            ContentType='text/plain'>
            <Verb
                Id='open'
                Command='Open'
                TargetFile="MyAppExe"
                Argument='"%1"' />
         </Extension>
    </ProgId>
</Component>

Answer: DefaultIcon will also accept a path to a valid .ico file as an Icon.
Comment: That works, as I pointed in my question, but it doesn't seem right.
Answer: You have to make sure that you have Win32 icons in your project not just .net icons.  I HOPE that someone points out an easy way to do this, but in the mean time, here goes...
Compile your assembly, then from Visual Studio select "File -> Open -> Open File", open the compiled assembly.  Add the icon you want to use for documents and set its ID to something above the one in use for your app.  Save the assembly.  Now you have Win32 resources available.
-- Edit --
After editing his post ZippyV appears to have a very good answer.


Views, adding I like, Retweet - best approach

Question: I have several views.
Now I need to add FB I like and retweet button to those views.
I search for modules, but all I get doesn't goes with Views well.
I would like to pass nid of node as excluded field and use Views Custom Field to create those links, but is this possible to get data from another field in custom field?
Answer: I also searched for modules that would allow Social Sharing - what I ended up doing was just adding the code manually to the templates.  It's just a couple lines of javascript, usually.  I ended up using AddThis for the main group and then just pulled the Facebook like code from their website.
IMO, somtimes a module is overkill.
Comment: Thanks, I agree. Now I see that only adding social links in custom JS script make sense.


TwinCAT - using a single input link to read 18 individual bytes from an EtherCAT slave

Question: I have a weigh scale controller I am connecting to my TwinCAT PLC.
The ESI file from the manufacturer maps 18 input bytes individually, but the information read is grouped into 4 byte (DINT) or 2 byte (UINT) chunks.
I'm trying to avoid the need to individually link each of the bytes to the physical IO.
Is it possible to map only to byte0, but still read all 18 bytes?
I would then break the 18 bytes out into chunks to generate the tags I need.
At present I am going to have to map each of the 18 input bytes individually then copy them into a UNION struct so I can generate the outputs.
Makes the mapping painful, so hoping to find a way to avoid this.
Any advice gratefully received!
Comment: I think you can link all of them at once if you have a `STRUCT` which has the same number of elements and types as your 18 byte input from the IO. See https://stackoverflow.com/questions/73009732/how-can-link-bit2-type-to-a-variable
Answer: The magic is in Change Multi Link. I tested Roald's suggestion and it does work with Multi Link, in fact the structure doesn't even need to have the same variable types or sizes as long as the total size is the same as the combined size of the items you selected on the mapping screen; it maps them on a byte-for-byte basis. If you have Matching Size turned on in the link screen, it will show a single item for any structures or variables that match the size of your selected I/O.
Another approach would be to use arrays, which could be mapped in the same easy fashion, but this offers less flexibility since you couldn't have varying data types.
Comment: This worked for my needs.

An array of 18 bytes can be mapped to the IO in a single action as follows:
 - Right click the array (not the individual bytes)
 - select 'Change Link...'
 - shift-click to select all 18 bytes from the IO Box.
 (If I/O vars are not showing, try selecting 'Array Mode' from the filters)

This will map all individual bytes into the byte array.

Thanks for the pointers!


O que é o método Accessor e Mutating no Swift ?? Para o que serve?

Question: Quando nós criamos uma struct em Swift, podemos utilizar o método
Mutating e Accessor.
Qual é o propósito ? O que ele soluciona e para que funciona.
Answer: Mutating indica que o método modifica o estado interno da Struct.
Em Swift, há uma importante diferença entre Value Types e Reference Types.
Enum e Struct são Value Types. Class é Reference Type.
Por padrão, é um erro de programação declarar um método que modifica o estado de um Value Type.
struct MyStruct {
    var value = 0

    func changeValue() {
        value = 10 //Erro: Cannot assign to property: 'self' is immutable
    }
}

Declarando o método com o modificador mutating, é possível modificar o estado do objeto:
struct MyStruct {
    var value = 0

    mutating func changeValue() {
        value = 10 // OK
    }
}

É possível até mesmo mudar a valor de self:
struct MyStruct {
    var value = 0

    mutating func changeValue() {
        self = MyStruct(value: 32)
    }
}

Comment: Ficou claro o uso do `mutating` mas quando o usuário pergunta *O que é o método Accessor e Mutating no Swift* acredito eu, posso estar equivocado e considero contra-argumento, que quando ele diz *método Accessor* queira saber além de como funciona o `mutating`  também queira saber como funciona o `setter` em propriedades computadas e propriedades encapsuladas e suas diferenças.


Rectangle packing with static rectangles

Question: I've implemented a rectangle packing class similar to the one mentioned here. My ultimately goal is to pack a number of smaller sprites into a large spritesheet.
The difficulty I'm experiencing is figuring out a way to expand that algorithm to allow for static rectangles. That is: rectangles whose positions remain static during the packing process and are effectively treated as obstacles that are to be avoided.
Is there another algorithm I should be considering or perhaps a more efficient way to of doing this?
Answer: I would say a good place to start would be here:
http://en.wikipedia.org/wiki/Bin_packing_problem
Its hard to say without seeing your direct algorithm, but generally speaking you must find a way to set that bin to always be full so that nothing else can go there. Then your algorithm should be able to recognize what is and isn't empty space, so that it knows if it can put something there. A simple first fit algorithm would probably work if modified to your needs.
Hope that helps. Cheers.


Pegar valor de uma celula[0] de um .data()

Question: Eu consegui puxar todos os dados da minha linha selecionada. Mas eu quero acessar somente o valor de uma propriedade, como por exemplo id_produto. Como faço?
Já consegui imprimir todos os dados no console:

$( document ).ready(function() {
 var table = $('#tbl_estoque').DataTable( {
  "ajax": "data.php",
  "bPaginate":true,
  "bProcessing": true,
  "pageLength": 5,

  "columns": [
   { mData: 'cod_produto' } ,
   { mData: 'cat_produto' },
   { mData: 'descricao_produto' },
   { mData: 'qnt_total' },
   { mData: 'qnt_vendido' },
   { mData: 'valor_produto' },
   { mData: 'valor_total' },
   {defaultContent: "<button>Click!</button>"}
  ]
 });
 $('#tbl_estoque tbody').on( 'click', 'tr', function () {
    console.log( table.row( this ).data() );

} );
 $('#btn_load').click( function () {
  table.ajax.reload(null, false);
 });
});

Após colocar o console.log( table.row( this ).data('id_produto') );
olha o console como ficou:
Comment: Ao invés de usar uma foto, poste o código em formato de texto usando a formatação de bloco de código. :)
Comment: Desculpe! Coloquei o código.
Answer: Conforme mostra a documentação do método data, você pode passar uma chave como primeiro argumento e o valor correspondente será retornado.
Você também pode usar a notação de acessar propriedades de um objeto (obj.propName).
Um exemplo que tange as duas possibilidades mencionadas:

const $el = $('time')

console.log($el.data())

// Usando a API do jQuery:
console.log($el.data('country'))

// Através da notação de objeto:
console.log($el.data().timezone)

<time data-country="BR" data-timezone="-3">22:00</time>

Portanto, você pode fazer:
console.log( table.row( this ).data('id_produto') );

Comment: não deu certo, postei o resultado na pergunta
Comment: Tente fazer assim: `table.row( this ).data().id_produto`. Funciona?
Comment: Deu certinho. Porém quando eu faço: document.getElementById("categoria").value = table.row( this ).data().cat_produto; que no caso ele escreve no meu select de id=categoria o valor da celula. ELE NAO ESCREVE NO SELECT. Somente nos input text. O que pode ser?


How to load String by BufferedReader?

Question: I need to load in a given String which will be type in as an input String:
             20 6
             ....................
             ..XXXXX..XXX.XXX..X.
             ..X.X.X..X.XXX.X..X.
             ..XXXXX..XX.X..X....
             ..XX......XXXXXX..X.
             ....................

something like that. It contains 2 integers and a String with "." and "X"
Now I just want to ask 2 questions:
1)I need to load the 2 integers first,but how can get the first two integers by BufferedReader?(the 2 int is divide by space between each other and the rest)
2)Then after loading the two integers,how can I load the following rest string char by char?(Like everytime I need to just load one char,then I go to some function,then come back and load the next char;and between there is no blank space)
Here is part of my code:
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String str=br.readLine();
       number1 = Integer.parseInt();
       number2 = Integer.parseInt();

And now I don't know how to continue...Anyone can help me to load it?
Comment: Use `Scanner` instead.
Answer: For 1) you just need to do a split
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   String str=br.readLine();
   String ints[] = str.split(" ");
   number1 = Integer.parseInt( ints[0] );
   number2 = Integer.parseInt( ints[1] );

Then for 2) once you have a String you can have it length and so get them char by char ;)
String lol = "......XXX..XX...";
for( int i = 0; i < lol.length(); i++ )
    System.out.println(lol.charAt(i));

With this you will get all your string char by char
Answer: It is much better if you use Scanner then you can read int and the String easier.
I suppose you input two integers as col and row.
Example like this:
Scanner scan = new Scanner(System.in);
int col = scan.nextInt();
int row = scan.nextInt(); //input two int first
scan.nextLine();
for(int i = 0; i < row; i++) {
    String s = scan.nextLine();
    for(int j = 0; j < col; j++) {
        char c = s.charAt(j);
        //your code here
    }
}

Comment: @user3390163 I mean if the program doesnt know how many lines you will input and there is no symbol that you have finished the input, the program will always wait for your input. Isn't it?
Comment: ignore it by checking for it and dumping it in the loop.
Comment: @user3390163 If you input the string from console and there are "/n", how do you mark the end of your input?
Comment: Can you describe a little more?Because I still don't get it...Thanks!
Comment: @locoyou actually the second number is how many line there is,the first number is how many column there is.But I don't know when I use Scanner ,it not working for load the String after load 2 integers from input...
Comment: @user3390163 What's the problem? `scan.nextLiine()` will read a whole line of your input
Comment: @locoyou I want get the data char by char,which is seems not work for scan.nextLine() .
Comment: @user3390163 OK, I dont know how to get it char by char with Scanner. You may try InputStreamReader. But I wonder its necessity to read data char by char from console. I tried my best :(
Comment: but there are lots of problems about "/n" when I input the data,which is always wrong.How to fix that?

How to load String by BufferedReader?


Erro popular dropdown PHP com array

Question: Olá,
Tenho a seguinte função que me retorna os dados necessários para popular o meu dropdown:
    function listaRedes($conexao){
    $dados = array();

    $resultado = mysqli_query($conexao, "SELECT DISTINCT rede FROM evolucao_originacao");
    while($valores = mysqli_fetch_array($resultado)){
        array_push($dados, $valores);
    }
    return $dados;
};

E no meu dropdown, estou fazendo o seguinte código:
 <?php $redesBanco = listaRedes($conexão); ?>

            <select class="form-control" id="dropdown-parceria">
                <option value="0">---SELECIONE---</option>
                <?php
                    while($redesBanco){
                        echo "<option value='".$redesBanco."'>".$redesBanco."</option>";
                    }
                ?>
            </select>

Porém na hora que ele popula o meu dropdown, o resultado é o seguinte:
Comment: Quando voce faz o while você ainda esta iterando sob arrays, tente ver o que possui dentro do array com `var_dump($redesBanco)`,
Comment: @RafaelAcioly o array está com todos os dados que busquei do banco.
Comment: O `var_dump` é para vermos a estrutura do seu `array`.
Answer: use foreach para percorrer o array:
<?php $redesBanco = listaRedes($conexão); ?>

                <select class="form-control" id="dropdown-parceria">
                    <option value="0">---SELECIONE---</option>
                    <?php
                        foreach ($redesBanco as $chave){
                            echo "<option value='".$chave[0]."'>".$chave[1]."</option>";
                        }
                    ?>
                </select>

Answer: Tente colocar $redesBanco[0]. Pois você esta tentando dar um echo em um array, é recomendado você dar uma var_dump para ver a estrutura para escrever por exemplo, <?php echo "".$redesBanco['acesse'].""; ?>
Mas tambem pode ser feito da primeira maneira, informando o indice com o numero $redesBanco[0].
No caso do seu exemplo deveria ser feito de uma forma tipo essa...:
<?php $redesBanco = listaRedes($conexão); ?>

        <select class="form-control" id="dropdown-parceria">
            <option value="0">---SELECIONE---</option>
            <?php
                while($redesBanco){
                    echo "<option value='".$redesBanco[0]."'>".$redesBanco[1]."</option>";
                }
            ?>
        </select>

Espero ter ajudado de alguma forma
Comment: da um var_dump($redesBanco); e coloca o resultado ai, para eu poder ajudar melhor, caso nao tenha conseguido
Comment: não funcionou @localhost

Erro popular dropdown PHP com array


reinterpret_cast(char*) vs. static_cast(static_cast(char*)) -- which to use?

Question: When you've dynamically allocated a buffer of type char * and want to cast it to a particular type, should you use something like
reinterpret_cast<int *>(char *)

or something like
static_cast<int *>(static_cast<void *>(char *))

and why?
I'm personally tempted to use the latter, because to me, it's not really a "reinterpretation" of the data (rather just a mechanical way of allocating the buffer) and it doesn't look like it would be a source of bugs in the same way as a typical reinterpret_cast might be, but is this the correct intuition?
Comment: @KerrekSB: its completely defined and even used in the implementation of vector (at least in my sgi version).
Comment: The answers so far seem to treat this as an abstract problem. For a real world example, I run into this situation with sockets or reading data from a file sometimes. I read an array of unsigned char * but the data in the array is actually ints. In this case I want to "reinterpret" my array of unsigned chars as an array of ints. Isn't that exactly what reinterpret_cast is for?
Comment: You shouldn't do this at all, as it's undefined behaviour.
Comment: KerrekSB: What is "this" referring to, exactly?
Comment: Those two forms are exactly identical for standard-layout types. per `§5.2.10/7` (C++11)
Answer: According to Dave Abrahams, using the chained static_casts is the correct, standard way to coerce pointer types.
Personally, I use reinterpret_cast in these cases because I never have to deal with architectures that would do one thing with the chained static_casts and a different thing with the single reinterpret_cast.


Is there any way to construct System.Web.Services.Protocols.InvokeCompletedEventArgs?

Question: This is possibly a dumb question since I'm new to all the technologies I'm using here (C#, .NET and SOAP).  There just may not be anyway to do what I want to do here.
I've got an asynchronous SOAP call (code generated from WSDL) that I'm trying to alter in such a way that within my library, I'm actually making multiple calls to multiple different web servers and then aggregating the results to return back to the caller.  The problem is that the SendOrPostCallback method of the asynchronous SOAP call expects to take an argument of InvokeCompletedEventArgs.  I can't construct this because the constructor is declared internal.  So while I can hide what I'm doing internally, and call the callback when what I'm doing is complete, I can't return the Results to the caller.  Any suggestions?
Old Code:
public void getStatusesAsync(RequestId[] requestIds, object userState)
{
  if ((this.getStatusesOperationCompleted == null))
  {
    this.getStatusesOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetStatusesOperationCompleted);
  }
  this.InvokeAsync("getStatuses", new object[] {
                    requestIds}, this.getStatusesOperationCompleted, userState);
}

private void OngetStatusesOperationCompleted(object arg)
{
  if ((this.getStatusesCompleted != null))
  {
    System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
    this.getStatusesCompleted(this, new getStatusesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
  }
}

New Code:
public void getStatusesAsync(RequestId[] requestIds, object userState)
{
  if ((this.getStatusesOperationCompleted == null))
  {
    this.getStatusesOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetStatusesOperationCompleted);
  }
  asyncExecuteMultipleSoapCalls("getStatuses", new object[] { requestIds}, this.getStatusesOperationCompleted, userState);
}

private System.IAsyncResult asyncExecuteMultipleSoapCalls(string methodName, object[] args, System.Threading.SendOrPostCallback callback, object asyncState)
{
  Thread backgroundSoapCalls = new Thread(new ParameterizedThreadStart(asyncThreadRun));
  object[] threadArgs = new object[] { methodName, args, callback, asyncState };
  backgroundSoapCalls.Start(threadArgs);
  return null;//How to return AsyncResult?
}

private RequestStatus[] multiSoapCallResults = null;

private void asyncThreadRun(object args)
{
  string methodName = (string)(((object[])args)[0]);
  object[] methodArgs = (object[])(((object[])args)[1]);
  System.Threading.SendOrPostCallback methodCallback = (System.Threading.SendOrPostCallback)(((object[])args)[2]);
  object asyncState = (((object[])args)[3]);

  //To make a long story short, I'm using this thread to execute synchronous
  //SOAP calls, then call the event.  The reason is that different requestIds
  //in the passed in array may reside on different Web Servers.  Hopefully,
  //this will work similarly to the original Asynchronous call
  multiSoapCallResults = executeMultipleSoapCalls(methodName, methodArgs);

  //Now that I'm done, I want to pass the evenArgs to the SendOrPostCallback
  RequestStatus[] returnStatusArray = new RequestStatus[multiSoapCallResults.Length];
  multiSoapCallResults.CopyTo(returnStatusArray, 0);
  multiSoapCallResults = null;

  //This line doesn't compile of course, which is the problem
  System.Web.Services.Protocols.InvokeCompletedEventArgs eventArgs = new System.Web.Services.Protocols.InvokeCompletedEventArgs(null, false, null, returnStatusArray);

  //Need to pass event args here
  methodCallback(eventArgs);
}

Comment: Been thinking about this.  Possibly I can add my own event type and override/change the event handlers and callbacks.  Then I could avoid having to construct this particular type of event altogether.  That would break client code of this library that might be listening to the events and using the corresponding delegates, but maybe I can deprecate the old versions and/or provide some meaningful feedback if they try to use the "old" versions.
Answer: Turns out it was a dumb question.  The wsdl generation already subclasses that InvokeCompletedEventArgs.  The class I suggested making in my comment above already exists in the generated code.  I just needed to find it.


AutoScroll Android ListView and sync up with Audio file

Question: I want to create a listview that would automatically scroll based on the playing of an audio file in the background.
Say the audio file is 10 mins long. I will have a list view that contains English translation of the audio playing in a different language. So each list item will have sentence by sentence translation.
I know a listview can be programmatically scrolled to a known position but I'm trying to sync it up with the audio file. If the user click on a list item the audio file should play from the position of the list item.
Any ideas how this can be achieved in the most simplest way?
Answer: You might find the smoothScrollByOffset() or smoothScrollBy() methods of ListView most useful.  In particular smoothScrollBy() takes both a distance to scroll and a duration over which the scroll animation should take place.  With this method you can control precisely how far to scroll the list.
HTH


Can you choose to play a fault serve in racquetball?

Question: Scenario: My opponent serves the ball short, but I'm in a good position to return it.
Does a fault serve automatically end the rally? Or can I choose to return the serve and continue the rally?
Answer: If your opponent's serve is short, then the ball is dead immediately and the rally is over.
You don't have a choice to return a short serve.
This is unlike a serve that's going long, which you can choose to play before it goes long, provided you do so before it hits the back wall and becomes a dead ball.
This is because the ball is still in play until it actually touches the back wall, at which point it's dead and you can no longer return it. With a short serve, the ball is dead before you have any opportunity to play it.
Your opponent either gets a second serve or you get a sideout depending on whether it was your opponents first or second serve and what rules you're playing by.


Retornar campos a partir de parametros

Question: Boa noite,
Preciso que o retorno de um SELECT seja dependente do parametro que for passado no SELECT
Exemplo
declare @variavel nvarchar(50)
Select
         campoa,
         campob,
         campoc,
         campod,
         campoe,
from tabela
eu preciso que se:
@variaval = campoa
retorne: select campoa, campob from tabela
se
@variavel = campob
retorne: select campob, campoc, campod from tabela
Como fazer essa lógica?
Comment: Isso se faz através da linguagem de programação que vai chamar o banco. Cada linguagem tem um jeito e cada banco tem um jeito. Qual é o seu banco e a linguagem que vc está utilizando ?
Comment: @NelsonTeixeira Bom dia...obrigado pela resposta Pela regra a solução deverá ser feita via banco de dados sql server
Answer: Acredito que seja isto o que precisa.
<code>DECLARE @Variavel AS VARCHAR(MAX); DECLARE @ComandoSQL AS VARCHAR(MAX);
SET @Variavel = 'campoa';

IF (@Variavel = 'campoa')
    BEGIN
        SET @ComandoSQL = 'SELECT campoa, campob, campoc, campod, campoe FROM Tabela'
    END
ELSE IF (@Variavel = 'campob')
    BEGIN
        SET @ComandoSQL = 'SELECT campob, campoc, campod FROM Tabela'
    END

/*Mostra o comando sql gerado*/
SELECT @ComandoSQL

/*Executa o comando sql gerado*/
EXEC (@ComandoSQL)
</code>

Retornar campos a partir de parametros