Mostrar dados na tela de acordo com o ID clicado

Question: Olá, estou com um pequeno problema aqui talvez fácil de resolver, porém não estou conseguindo. Tenho uma primeira tela (alunos.php) onde terá vários termos de pesquisa, e um deles será por horário de estudo, onde vão me trazer alguns resultados do banco de dados. Até aqui tudo funcionando perfeitamente. Segue o print da tela da pesquisa.

Segue o código para que esta pesquisa funcione:
<?php
                                                    if($startaction == 5){
                                                            if($acao == "search_time") {
                                                                    if(empty($_POST['select_time'])) {
                                                                        echo'';
                                                                    } else {
                                                                    //pegar nome via post
                                                                    $searched_time = $_POST['select_time'];
                                                                    $result = mysql_query("SELECT * FROM alunos WHERE Dia_Horario LIKE '%".$searched_time."%' " );
                                                        $check_time = mysql_num_rows($result);
                                                                        if($check_time >= 1){
                                                                             while($ln = mysql_fetch_array($result)) {
                                                                                $radio = $ln['ID'];
                                                                                $id = $ln['ID'];
                                                                                $full_name = $ln['Nome_completo'];
                                                                                $hora_estudo = $ln['Dia_Horario'];

                                                        ?>

                                     <a data-toggle="modal" data-target="#dialog01" href="#<?php echo $radio; ?>"> Clicar Aqui

                                            <?php echo $id; ?>

                                        <a href='http://www.dpaulatreinamentos.com/system/teste03/views/pages/aluno.php?id_aluno=<?php echo $id; ?>' class='nomecompleto' title='".$full_name."'>
                                            <?php echo $full_name ?>

                                        <?php echo $hora_estudo; ?>

                            <?php

                                                                } } else {
                                                                    echo'';

                                                                }
                                                                }
                                                            }

                                                            }

                                ?>

Depois que clicamos no nome do aluno, é carregado uma nova pagina, nesta pagina terá os dados completos do aluno porém com campos para edição onde eu poderei trabalhar somente com este aluno, cadastrar novas aulas, mudar dados mas somente deste aluno, já está puxando o ID no link e carregando a nova pagina já com o ID na URL, porém os dados não aparecem, segue print da segunda tela.

Segue parte do código que eu coloquei:
 <?php

    $searched_time = $_POST['select_time'];

                               $pegaid = $_GET["ID"];
                                                                    $result = mysql_query("SELECT * FROM alunos WHERE ID = '$pegaid'" );
                                                        $check_time = mysql_num_rows($result);
                                                                        if($check_time >= 1){
                                                                             while($ln = mysql_fetch_array($result)) {
                                                                                $radio = $ln['ID'];
                                                                                $id = $ln['ID'];
                                                                                $full_name = $ln['Nome_completo'];
                                                                                $hora_estudo = $ln['Dia_Horario'];

       echo $id;

  ?>
   <form>
     <?php echo $pegaid; ?>
     <input type="text" class="txt-medium bradius" value="<?php echo $full_name; ?>"/>
     <input type="submit" value="Atualizar" class="sb-search-medium" />
  </form>

Será que teria alguém para me ajudar? Se sim, agradecerei muito.
Answer: primeiro aconselho que trabalhe no mysqli depois você pode selecionar apenas  tabela que é
SELECT * FROM alunos

depois você da um
<? php while($ln = mysqli_fetch_assoc($result)){ ?>

depois lista cada um que que vai só exibir e ou que vai editar
<div id="<?php echo $ln['id']; ?>">

<?php echo $ln['Nome_completo']; ?>

<?php echo $ln['Dia_Horario']; ?>

e não esqueçe de fecha a while
<?php } ?>

claro que pra atualizar algumas funções do banco você vai precisar usar o update.
Comment: Não é isso que preciso, mais valeu a ajuda
Answer: Não está a funcionar pois no teu print o nome da variavel é (id_aluno), contudo no teu script tu estás a tentar resgatar (ID).
Então não é isso: $pegaid = $_GET["ID"];
E sim isso: $pegaid = $_GET["id_aluno"];
Deve ser esse o motivo, sem aluno não há retorno não é mesmo?


Pass arguments to the entity_browser iframe url (modal)

Question: I have a form I have a field of type Date Range, I also have another field of type entity_browser(modal) with a selection view widget.
The normal behavior when I click the Button of the entity browser field, is the opening of the modal, if we inspect the code it can be seen similar to this:
<form
   data-entity-browser-uuid="a9b7680318c9f1a1aca1abc308d8c6d0ac880b4a"
   data-drupal-selector="entity-browser-event-browser-form"
   action="/entity-browser/modal/event_browser?uuid=a9b7680318c9f1a1aca1abc308d8c6d0ac880b4a&original_path=/node/add/activity"
   method="post"
   id="entity-browser-event-browser-form">....
</form>

What I'm trying to do, is that as the dates are selected, pass these values as arguments to the iframe url something like this:
<form
   action="/entity-browser/modal/event_browser?uuid=a9b7680318c9f1a1aca1abc308d8c6d0ac880b4&aoriginal_path=/node/add/activity&start=12-02-2022&end=14-02-2022"
....
</form>

Then from the view take these values and filter the contents.
What i have so far
Reviewing the code of the entity_browser module, I see that the Modal class (Drupal\entity_browser\Plugin\EntityBrowser\Display\Modal), as part of the process hook, this dispatch an event to which one can subscribe.
In fact, i can add parameters to the query argument in this subscription, i have harcoded the values as a test, but they do not render when I refresh the form where I create the content that contains the entity_browser type field.
Example:
public function onAlterEntityBrowserDisplayData(AlterEntityBrowserDisplayData $event) {
    if ($event->getBrowserID() === "event_browser") {
       $data = $event->getData();
     if (isset($data["query_parameters"]["query"])) {
        $data["query_parameters"]["query"]['start'] = '12-02-2022';
        $data["query_parameters"]["query"]['end'] = '14-02-2022';
        $event->setData($data);
      }
    }

  }

If I could get this to work, then I'd have to figure out some way with ajax to keep changing these values as the values in the date field change.
I don't know if this is the best way to do it, I don't know what you think.
Update
The subscription to the event is working, that is, when rendering the content form, the new parameters are added to the iframe url.
The only thing that I would be missing is the update of the parameters via ajax when the values of the date field change.
I can add an ajax callback to the date field that listen when the value changes, I see there is an input field of type hidden where it seems to have the values that entity_browser will use. The problem is that it doesn't have an id to replace the values with.
Example:
<input
   data-drupal-selector="edit-field-event-entity-browser-entity-browser-path"
   type="hidden"
   name="field_evento[entity_browser][entity_browser][path]"
   value="/entity-browser/modal/event_browser?uuid=1d0cbf414d0af02542405648750ccf4d157438fb&original_path=/node/add/activity&start=12-02-2022&end=14-02-2022"
>

The problem is that it doesn't have an id to replace the values with.
What can be done in these cases?
Answer:
I would suggest creating a custom Entity Reference widget, that extends the one that you are trying to alter.
Then use Drupal form states to make your entity reference field conditional, and display it only if the date range is selected.
Add JS code that updates the values submitted (add the selected dates) when the entity browser open button is pressed.
in hook_form_entity_browser_media_entity_browser_modal_form_alter or hook_inline_entity_form_entity_form_alter or hook_field_widget_WIDGET_TYPE_form_alter do the filtration job.


How to make an image fit a custom 256dp Big Picture Notification in Android?

Question: I'm trying to fit (center and inside) 2 kind of images obtained from web services in a Big Picture styled Notification. One kind is 97px*150px sized and the other 300px*100px.
As I checked the image must fit 256dp tall max height to fit on Jelly Bean's Big Picture notification visual area, so I expected that I can call the matrix scales availables on ImageView (fitXT, centerInside, etc) but i'm surprised that no scaling method behavior is available to configure and the bitmap is always center-cropped wich by the way is worst default matrix behavior I would selected for default because images always are cutted in some way. A center inside behavior for default it would be better, I think.
So, this leaves me room for this posibilities:

Pre-scale images using some sort of pixels to dp method. This method must also has to respect aspect ratio. After that use that new picture against Notification Builder, wich (I expect) will respect the iomages because no out of bounds behavior will happen.
Create my own RemoteView to use ImageView and gain access to scale matrix behaviors.
File a new feature request to Google :)
File a bug request to Google :)

Which option do you think or know as the best?
Is there any other option that am I could be missing?
EDIT: I've tested several methods to matrix scale the images with success but the center-crop is always there by default to break and cut my images making it imposible to use.
I will give a try now to RemoteView method.
I also filed the issue 58318 for this, trying to make life easier for future devs trying to accomplish this task: https://code.google.com/p/android/issues/detail?id=58318
Answer: The only solution is to create my own RemoteView as follows:
First, a custom layout:
<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/status_bar_latest_event_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:drawable/list_selector_background">

<ImageView
        android:id="@+id/big_icon"
        android:layout_width="34dp"
        android:layout_height="34dp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:scaleType="fitCenter"
        />

<TextView
        android:id="@+id/title"
        android:text="sometitlestringfromresources"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_alignBottom="@+id/big_icon"
        android:layout_toRightOf="@+id/big_icon"
        android:layout_marginLeft="15dp"/>

<ImageView
        android:id="@+id/big_picture"
        android:layout_width="match_parent"
        android:layout_height="192dp"
        android:layout_marginTop="64dp"
        android:scaleType="fitCenter" //This scale will show your picture without crop
        />
</code>

And the RemoteView implementation:
<code>  if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            RemoteViews views;
            views = new RemoteViews(getPackageName(), R.layout.custom_notification);
            views.setImageViewBitmap(R.id.big_picture, bitmap);
            views.setImageViewBitmap(R.id.big_icon, BitmapFactory.decodeResource(getResources(), R.drawable.your_24x24dp_brand_icon));
            views.setTextViewText(R.id.title, message);
            myNotification.bigContentView = views;
        }

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(randomInt, myNotification);
</code>
Where myNotification is your notification builder and randomInt is my own implementation to no overlap notifications (check if this is not your need to replace notifications or generate several).
<code>  Random randomGenerator = new Random();
  int randomInt = randomGenerator.nextInt(100);
</code>
And that's it. Maybe is a little dirty but it works. I'll leave the bug open to Google and if I receive some response i'll update this.


Need help converting pseudo-code to c#

Question: I've been working on building an icosphere, and am almost done with it.
Right now what I am trying to do is make it so that any triangles not facing the camera aren't added to the draw list, because I'm dealing with a lot of triangles, and am filling up the vertex buffer.  I've managed to make it so the triangles facing the initial camera position are hidden (see attached images), but the hidden triangles do no update as I move the camera around.
Here are the two images showing this:
http://i41.photobucket.com/albums/e262/cstgirllover/Cho/IcosphereCulledFront.png
http://i41.photobucket.com/albums/e262/cstgirllover/Cho/IcosphereCulledSide.png
I've been using (pseudo)code from this site to help me get this far:
http://decadeengine.blogspot.com/2011/03/remove-back-facing-patches-before.html
but I cannot seem to find any corresponding code for this:
p_pGraphics->get_Matrix(eModelView)

That is from the last segment of code on the page, which fixes the problem I'm having.
My surrounding code looks like this:
public float isFacing(Vector3 pos1, Vector3 pos2, Vector3 pos3, Camera dotCamera)
    {
        Vector3 temp1 = CalculateNormal(pos1, pos2, pos3);

        float dotp = Vector3.Dot(temp1, dotCamera.GetDirection * _________);
        return dotp;

    }

The equivalent code need to go in after "dotCamera.GetDirection * "
Answer: I think this code snippet will depend on which 3d engine you are using.
effectively what it's doing to to try and get a matrix representing the current rotation/position of the view.
if you are targetting XNA you might find this of help Rotation&Transaltion:
Comment: Well, the issue is that I don't know what that bit of code is actually pointing to in his project, so I don't know ho to equate it to my project.  And I'm using XNA
Answer: That's not pseudo code.  There isn't enough information to give a solid answer but have you tried this?
float dotp = Vector3.Dot(temp1, dotCamera.GetDirection * p_pGraphics.get_Matrix(eModelView));

Comment: Neither p_pGraphics or eModelView are declared in my program, so that doesn't work, and I don't know what they are referencing, so I can think up an equivalent in my code.

Need help converting pseudo-code to c#


Distribute n integers into m (non distinct) bins without creating consecutive triples

Question: I have $[n] := \{0, 1, \cdots, n-1\}$ integers and $m$ bins (we don't distinguish bins). How many possible ways to distribute $m$ integers from $[n]$ into $m$ bins are there such that the distributions have no consecutive triple?
In other words, how many subsets of size $m$ are there in $[n]$ which don't contain 3 consecutive integers ($6, 4, 5$ is a consecutive triple but $1, 2, 4$ isn't)?
Some subsets for $m=7$ and $n = 20$:

{0, 1, 3, 4, 6, 7, 9} has no consecutive triple
{1, 3, 6, 18, 19, 10, 2} has a consecutive triple (1, 2, 3)
{10, 15, 18, 19, 0, 5, 8} has no consecutive triple
Answer: Let $A(n,m)$ be the number of ways to choose $m$ integers from $[n]$ without a consecutive triple. Clearly $A(n,m) = \binom{n}{m}$ when $m < 3$, and $A(n,m) = 0$ when $m > \left\lceil\frac23 n\right\rceil$.
For larger $m$ it might be easier to invert the question. How many subsets $S$ of size $m$ are there which do have 3 consecutive integers?
Suppose that the lexicographically first consecutive triple is $k,k+1,k+2$.
Case $k = 0$: any selection of $m-3$ elements from the remaining $n-3$ works, so we have $\binom{n-3}{m-3}$ subsets.
Case $0 < k \le n - 3$: clearly $k-1$ is not in $S$. Suppose that $i$ elements from $[k-1]$ are in $S$: they don't contain a triple, so there are $A(k-1,i)$ ways to choose them. The remaining $m-i-3$ elements of $S$ are chosen freely from the remaining $n-k-3$ elements of $[n]$.
Putting those together, $$\binom{n}{m} - A(n,m) = \binom{n-3}{m-3} + \sum_{k=1}^{n-3} \sum_{i=0}^{\left\lceil\frac{2(k-1)}{3}\right\rceil} A(k-1,i) \binom{n-k-3}{m-i-3}$$
This allows closed forms for small $m$. E.g. $$\begin{eqnarray}
A(n,3) & = & \binom{n}{4} - \binom{n-3}{1} - \sum_{k=1}^{n-3} A(k-1,0) \binom{n-k-3}{0} \\
& = & \binom{n}{3} - n + 2 \\
A(n,4) & = & \binom{n}{4} - \binom{n-3}{1} - \sum_{k=1}^{n-3} A(k-1,0) \binom{n-k-3}{1} + A(k-1,1) \binom{n-k-3}{0}\\
& = & \binom{n}{4} - (n-3) - \sum_{k=1}^{n-3} n-4\\
& = & \binom{n}{4} - (n-3)^2
\end{eqnarray}$$
etc. I wouldn't be especially optimistic about finding a closed form for general $m$, but I haven't really tried.


How to solve the conflict between reset.css/normalize.css and the 'initial' CSS prop value?

Question: There is a new value in CSS3 called 'initial', it will reset the prop's value to the browser's default.
The spec here: https://developer.mozilla.org/en-US/docs/Web/CSS/initial
But in most times, a website/webpage often have a reset.css or normalize.css file apply to the site/page.
So in most cases, I want the prop which set to 'initial' to be the reset.css or normalize.css's value but not the browser's default, how to solve the conflict between those two?
Comment: Why not just use the same value as in the `reset.css` then? It's a constant, so there are no issues with changing it. Can you show a specific example where you have a problem with this?
Comment: most times the developer can not remember the value in the reset.css, is it?
Answer:
There is a new value in CSS3 called 'initial', it will reset the prop's value to the browser's default.

That's where most people are mistaken (even I got it wrong once). The initial value is not the same thing as the browser's default value.
A browser default is set by the browser in its default stylesheet.
The initial value of a property is the default that is stated in the spec. The initial value is usually the same regardless of what element you apply the property to; it's the browser that decides whether it should apply a different value to different elements by default.
For example, the initial value of display is inline — many HTML elements default to display: block, but setting display: initial will turn them into inline elements, not block elements.
Even the document you link to itself links to another document defining the term "initial value":

The initial value given in the summary of the definition of each CSS property has different meaning for inherited and non-inherited properties.

With all that said, there is currently no way using CSS to reset a property to either a browser's default or an arbitrary level in the cascade (e.g. normalize.css or a reset stylesheet).
Comment: This is a great answer and should be accepted. There is now a postcss plugin you can use to leverage some aspects of `initial` https://github.com/maximkoretskiy/postcss-initial


Graph out of incidence matrix Matlab

Question: What I need is exactly contrary of ;
I = incidence(G).

Here I have already an incidence matrix I, is there any way to get G, which is a graph including Nodes and Edges?
Comment: In principle it should be as I can see so far. You could look for a way to get the adjacency matrix from the incidence matrix. What have you tried so far? Edit: or "collect" source and target node for each edge.
Comment: No, I wanted to know if there is a direct way, like a matlab method.
Answer: I did not find a Matlab method but the following method I developed is quite straight forward:
% Define your test graph
s = [1 1 1 2 3 3];
t = [2 3 4 3 4 5];
G = graph(s,t);
I = incidence(G);

% Find the source nodes from incidence matrix
[s2,~] = find( I == -1 )

% Find the target nodes from incidence matrix
[t2,~] = find( I == 1 )

% Generate graph from source and target nodes
G2 = graph( s2, t2 );
figure;
subplot(211);
plot( G );
subplot(212);
plot( G2 );

% Check
I2 = incidence(G2);

assert( isequal(I, I2), 'Did not generate same incidence matrices' );

So all the work is done with find and the info:

I = incidence(G) returns the sparse incidence matrix for graph G. If s
  and t are the node IDs of the source and target nodes of the jth edge
  in G, then I(s,j) = -1 and I(t,j) = 1. That is, each column of I
  indicates the source and target nodes for a single edge in G.
Comment: It returns the exact thing I want, than you for your kind help.
Comment: @HamidrezaMirtaheri: nice to hear. Would be great if you voted up my answer then and accept it, see http://stackoverflow.com/help/someone-answers

Graph out of incidence matrix Matlab


rank position based on field value

Question: I would like to display the rank position of a node based on a field value.
Let's say that in field_A there is the node's quantity of "points" and in field_B the node's category.
Then, I would like to display that the current node is 5th out of 15 in its category for example.
thanks for your help.
Comment: How do you want to handle ties?
Comment: I don't know yet. Any idea?
Comment: https://en.wikipedia.org/wiki/Ranking
Comment: can you write code, or do you need to do this as a view?
Comment: Whatever, view or code in a field (computed field) will be fine
Comment: If you want us to help you, you'll have to be a bit more specific about what you want. You can find different ways of handling ties in my wikipedia link above.
Comment: I'm not sure to understand what you mean by handling ties. I have 2 fields in the node. Points and category. When  a node is displayed, I would like to display the position of the node out of the quantity of node in its category based on the number of points.
Comment: see wikipedia link
Comment: Thanks for the link Ollie.  Standard competition ranking ("1224" ranking). Is it what you wanted to know?
Answer: seems you need to create a "taxonomy view" (category) then create a listing and sort them by the "points" field value.
Comment: Thanks a lot. But I need to show only the current node position.  With this method it displays all nodes
Comment: If you want to create a (table)list like:
1.node x
2.node y
3,node z

U can use the display field :global counter.

Jus showing one node can be done by filter or using a contextual filter.
Comment: The problem is that when U use a filter and so display 1 result,  the global counter will be always 1. It doesn't keep the rank that was before filtering.

rank position based on field value


Doubt about the definition of totally bounded metric space.

Question: Let $(S, \rho)$ be a metric space. Using my professor's definition, it's totally bounded if for any $\epsilon >0$, we can find $(X_{j})_{j=1}^{J}$ such that $J < \infty$, diam$(X_{j}) < \epsilon$ for any $j$ and $S = X_{1} \cup ... \cup X_{j}$. I'm ok with that.
The problem is that in the next line he says that we can consider every $X_{j}$ as a closed ball, without any loss of generality.
I'm trying to convince myself of that. In the first moment, I thought that we could take the closure of each $X_{j}$, something that would keep the diameter and would close the sets. However, a point $x \notin S$ in the boundary of $X_{j}$ would be included in the reunion, which would brake the decomposition since we wouldn't have an equality between sets anymore.
So, how to see this? Thanks a lot in advance!!
Answer: You can pick a point $x_j\in X_j$. Then $X_j\subseteq B(x_j,\epsilon)$. Note that the ball of radius $\epsilon$ has diameter at most $2\epsilon$, by the triangle inequality. Thus, if you can cover the set with finitely many sets of diameter at most $\epsilon$, then you can cover it with balls of diameter at most $2\epsilon$.
Comment: Thanks a lot! Ok, so I could take the diameter of any $X_{j}$ to be $\epsilon /2$ and have the result, right?
Comment: Hold on, but there might be other elements in these balls that are not in $S$, so how would I keep the equality between $S$ and the reunion of these balls?
Comment: @RaulGuarini The point here is that you may replace $S=X_1\cup\cdots\cup X_j$ by $S\subset X_1'\cup\cdots\cup X_j'$ as an equivalent definition of totally boundedness. To see the equivalence, just take $X_i=X_i'\cap S$.
Comment: @shrinklemma so let's see if I got it. If you have totally boundedness, you can always use closed balls of radius $\epsilon$ as pre-kidney just showed (name them $X_{j}^{'}$ for each $j$) and have $S \subset X_{1}^{'} \cup ... \cup X_{j}^{'}$. If this can be done, so if we let $X_{j} = X_{j}^{'} \cap S$, we are back where we started and every $X_{j}$ will be closed in $S$. Is this sound? Thanks again!
Comment: Ignore my previous comment. I thought $S$ was a subset of a larger metric space rather than the metric space itself. Since $S$ is already the whole space and $S$ is covered by the closed balls, $S$ is equal to the union of these balls.
Comment: In summary, don't think of $S=\bigcup X_i$ as an equality, but rather as a set containment $S\subseteq \bigcup X_i$ (the two are equivalent). The idea is we are covering the set with finitely many small sets.
Comment: Alright so, many thanks again!!
Answer: (i). If $S$ satisfies the open-ball condition, we can satisfy the closed-ball condition by using $(\bar X_j)_{j=1}^J$ because diam $(\bar X_j)=$diam $(X_j).$
(ii). If $S$ satisfies the closed-ball condition,  then for $\epsilon >0$ let $S=\cup_{i=1}^J T_j$ with finite $J,$
 where each $T_j=Cl(B_{\rho}(p_j,r_j))$ is a closed ball with diam $(T_j)\leq 2r_j<\epsilon /2 .$
Then $X_j=B_{\rho}(p_j,2r_j)$ is an open ball with diam $(X_j)\leq 4r_j<\epsilon,$ and $X_j\supset T_j.$ And  $S\supset \cup_{j=1}^jS_j\supset \cup_{j=1}^jT_j=S.$ So $S$ satifies the open-ball condition.


Is there a name for this property of a function?

Question: I want to know if there is a name for this property:
for given positive numbers $a,b$, we have an inequality $|f(x)-f(y)|<b$ whenever $|x-y|<a$.
Warning:
It looks like Lipshitz continuity, but this property does not imply the continuity; for example, EVERY bounded function with bound $M$ satisfies it when we set $a$ and $b$ such that $a>0$ and $b>2M$.
Note that this property depends on the choice of $a$ and $b$.
Maybe the existence of these constants is important.
Where did I see this?:
I just saw this in several exam problems. I thought it might be useful in numerical analysis, because making $b$ small means that this function can be considered to be a Lipschitz continuous function with small errors. So I guessed it should have a name.
If anyone knows any concept similar to this, please tell me. Thanks.
Comment: It sounds like you are either talking about Lipschitz continuity $$ |f(x)-f(y)|\leq (b/a)|x-y|$$ so that $(b/a)$ is the Lipschitz parameter, or uniform continuity (where we fix $b$ and then choose $a$).
Comment: nope. this condition does guarantee any kinds of continuity.
Comment: I don't understand: are you trying to come up with a name for this, or did you see this somewhere and forget its name?
Comment: I have never seen the name of this. But I guessed that it would be useful somewhere, in spite of discontinuity, because it provides with a powerful estimate of the function. I just encountered it when I was solving a final exam problem.
Comment: But this is not a useful definition of continuity. If I fix $b$ at 2, and $a$ at 1, then this says that the floor function is continuous.
Comment: I know. I thought if it is used, maybe it will be in numerical analysis. If b is sufficiently small, we might make a good approximation.
Comment: @Matt I could definitely see uses for it. Let's say you designed an algorithm that takes a real number $x$ and produces another real number $f(x)$. Suppose $\varepsilon > 0$ is the machine epsilon for whatever machine you're coding it for, and there was some $a$ such that $|x - y| < a \implies |f(x) - f(y)| < \varepsilon$. If you wanted to $f(x_0)$ where $x_0$ is not necessarily rational, you just need to compute $f(x)$ where $x$ is a decimal approximation within $a$ of $x_0$, and $f(x)$ will be indistinguishable from $f(x_0)$. Seems potentially handy.
Comment: I saw this three or four times in exam-oriented problems, so I just thought it sould have a name.
Comment: I'm pretty sure Michael is correct and you mean Lipschitz Continuity only, I've seen it in various numerical Analysis courses as well
Comment: @TheoBendit Thank you. My first ally!
Comment: @Anvit Nope. This definition definitely admits step functions as  "continuous functions".
Comment: @user680089 are you talking about your definition or Lipschitz definition? because step function is continuous in both
Comment: @Anvit I know that Lipschitz continuity with constant 1 is used to verify the existence of fixed point in numerical analysis. But I'm asking totally different concept
Comment: @Anvit of course my definition. Lipschitz continuous function is continuous, but mine is never continuous at all. Please see quotation marks on "continuity".
Comment: I think my question was very confusingly written.. sorry for you
Comment: @user680089 : Not only are there quotation marks around "continuity," there are also quotation marks around "fixed." To understand the question, one must interpret both sets of quotation marks. It sounded like you were trying to remember a certain type of continuity, for which Lipschitz or uniform seemed like closest matches.  Apparently that is not what you meant. Now you are saying quotations on "continuous" means "not really continuous" and so one expects quotations on "fixed" to mean "not really fixed."
Comment: ok alright I'll edit.
Comment: @Michael Thank you for pointing out the problem. But I am very disappointed to downvoters so let me tell you what I'd like. Remeber some people understood and upvoted the question before edit. I know I'm also at fault, but I hope you guys not to justify your misunderstanding. Actually it should have been clear if you gave a more attention.
Comment: @user680089 : I never downvoted it, but now I have upvoted it.
Comment: @Michael I am ashamed... I got upset and lost rationality temporarily. I will be careful at asking questions. Thanks
Answer: Not all properties are required to have names, we can just make up a  name like $P(a,b)$. However, your property is similar to the concept of a "leaky bucket constrained" arrival process used in queueing theory.

Definition 1:
Given positive real numbers $a,b$, a function $f:\mathbb{R}\rightarrow\mathbb{R}$ has property P(a,b) if $|f(x)-f(y)|\leq b$ whenever $|x-y|\leq a$.
Definition 2:
A function $f:\mathbb{R}\rightarrow\mathbb{R}$ is leaky bucket constrained with rate parameter $\lambda \geq 0$ and burst parameter $\sigma \geq 0$ (written $f(t) \sim leaky(\lambda, \sigma)$) if
$$ |f(x)-f(y)|\leq \lambda |x-y| + \sigma \quad \forall x, y \in \mathbb{R}$$

From these two definitions we can prove the following:

$f(t) \sim leaky(\lambda, \sigma) \implies$ $f(t)$ has property $P(a,\lambda a+\sigma)$ for every $a\geq 0$.

If $f(t)$ has property $P(a,b)$ for some positive numbers $a,b$ then $f(t) \sim leaky(b/a, b)$.

Definition 2 is usually applied to nondecreasing functions that represent arrival functions, such as functions $N(t)$ that represent the number of jobs that arrive to a queue during a time interval $[0,t]$. Such $N(t)$ functions jump discontinuously when a new arrival occurs. If $N(t) \sim leaky(\lambda, \sigma)$ then any interval of size $T$ has at most $\lambda T + \sigma$ arrivals, and the long term arrival rate satisfies
$$\limsup_{t\rightarrow\infty} \frac{N(t)}{t} \leq \lambda$$ Such processes are useful because, assuming each job has a fixed size, the worst-case size of the queue can be deterministically bounded (in terms of $\sigma$) whenever the service time of each job is a constant $1/\mu$ that satisfies $\mu\geq \lambda$.
Comment: Note: The deterministic queue bound that holds for $leaky(\lambda,\sigma)$ processes whenever $\lambda \leq \mu$ is very strong and cannot be obtained  in queues with Poisson arrivals, such as M/M/1 or M/D/1.  Indeed M/M/1 or M/D/1 queues  cannot be deterministically bounded and they require $\lambda < \mu$ even to ensure the _average_ queue size is bounded, which is more stringent than $\lambda \leq \mu$.


android activity can't recover

Question: When I click my app's icon on the desktop,the splashactivity will first run, then it start the loginactivity before it finished. I click the loginbutton to login.then I came to the mainactivity.Then I click the HomeKey to goto the Android Home. At this time ,I click the app's icon again, the splashactivity start firstly. Why the mainactivity can't be recover? Othewirse,when I click the HomeKey at loginactivity ,the app can skip the splashactivity and recover the loginactivity.Thanks.
Comment: you need to go to login activity after the splash every time you launch the app?
Comment: No, I need the app go back to the state what before the HomeKey be Clicked .Thank you .
Comment: Make the ``LoginActivity`` your main activity, and only show the ``SplashActivity`` when you want to (i.e., once a day).  Ideally, you would want to show a splash screen while the program is loading in the background - although the common practice now adays is more about advertising the App than anything else.
Comment: Thank you.But after I make the **LoginActivity** as main activity,I also can't recove the **MainActivity** when I Click the HomeKey at the **MainActivity** and click the app's icon latter. I think if the MainActivity can't be keeped when it running background. How can I keep it aways running ?
Comment: @mrres1 Please post you comment as an answer and iterate over it further is the question can be worked with accordingly.
Answer: Thats very unusual, when a home key is pressed, an app is usually restored in the state it was left. At least thats what i have seen with all apps i have on my phone. What you could do is control your app flow using onPause() and onStop() as they get called when HomeKey is pressed.
Comment: Yes, I override the OnPause() method,but just like this ** protected void OnPause(){ super.OnPause(); BaseActivity.isMainPageRunnint = false; } ** I do the same at other Activity but this question never happened.
Comment: If you are running on ICS and above, did you check if u have ticked Settings -> Developer Options -> Dont keep Activities? The fact that the splash screen starts is because you activity is getting killed and there no recovery state for it, hence android starts it all over again
Comment: Thank you! I checked and the checkbox is not choiced. The other acitvity can recover just the **MainActivity** can't.
Comment: Thanks again,this happened because I make the **MainActivity** singleInstance .
Comment: Welcome, kindly accept the answer as right one, this might help others facing the same problem. Thanks!
Answer: If you create your LoginActivity as the launch activity, then you can display SplashActivity only when you want to display it.  My recommendation was being once a day.
In the onStart of your LoginActivity:
@Override
protected void onStart()
{
    /*
        get last stored time & date of onStart using SharedPreferences
        get the current time & date

        if (current day != stored day)
            store date and time
            startActivity(SplashActvity)
    */
}

android activity can't recover


Is this a valid Markov Chain Monte Carlo sampler

Question: Let's consider a sampling algorithm which is sampling from the posterior  distribution $P(X)$ of a random variable $X$. At a given iteration $t+1$ it proposes a new value $(X_{t+1})$ for $X$ using a symmetric proposal distribution $Q(X_{t+1}|X_t)$ around the old value $X_t$. Due to the symmetry of the proposal distribution, the standard Metropolis Hastings (MH) acceptance rate is as follows: accept $X_{t+1}$ with probability $\alpha=\min(1,P(X_{t+1})/P(X_t))$. Somewhere, I saw a slightly different acceptance rate, it says:

if $P(X_{t+1})>P(X_t)$ accept $X_{t+1}$ (This part is same as the MH algorithm)
else sample from the distribution $P=[P(X_t); P(X_{t+1})]/(P(X_t)+P(X_{t+1}))]$ (In this case the sampler will choose $X_{t+1}$ or $X_t$ depending on their posterior probabilities)

I was wondering whether the later is a valid MCMC sampler.
Comment: Why can't you try to prove that the distribution $P$ is stationary with this transition?
Comment: Would you mind to cite the source of the second approach?
Answer: This alternative version sounds like Barker's (1965) and Hastings' (1970) versions when the acceptance probability is
$$\alpha(x,x^\prime) = s(x,x^\prime) \left(1+\dfrac{p(x) q(x^\prime|x)}{p(x^\prime) q(x|x^\prime)}\right)^{-1}$$with $s(x,y)$ is a symmetric function keeping the above between 0 and 1
except that there should be no sure acceptance first, i.e., when $p(x^\prime)>p(x)$.
For instance, here is an illustration of why the proposal in the question does not work:

This histogram represents the result of 10⁵ simulations, against the intended standard Normal target, using another standard Normal random walk as proposal.
While, if I remove the first step in the "alternative" algorithm, Barker's formula leads to the proper fit:


what is the query of sql database connection

Question: I want to connect my C# project with SQL database.
which query I have to follow??
using(SqlConnection connection = new SqlConnection(connectionString)) {
    connection.Open();
}

i use this, it is not working
Comment: Figure out your connection string. See http://www.connectionstrings.com/
Comment: define "it is not working". What happens?
Comment: what does not work exactly?
Comment: There is nothing here that we can help you with. And by the way, where is the query? I don't see any
Answer: Try this
namespace Town
{
    class clsconnection
    {
        string connection = @"Data Source=server name;Initial Catalog=databasename;Integrated Security=True";

        public SqlConnection getconnection()
        {
            SqlConnection sql = new SqlConnection(connection);
            sql.Open();
            return sql;
        }
    }
}

Comment: thanx, it is working,
i have connect my form with database sucessfully


Loading images using picasso on a slow connection

Question: I am using Picasso to load images for a listview.
The problem is internet connection is slow.
How can I change load timeout time in Picasso?
My code is :
Picasso.with(context)
.load(MainActivity.WEBSITE + book_item.Image)
.resize(final_thumb_width, final_thumb_height)
.into(new PicassoTarget(book_item,item.img, item.title));

Comment: post some code please.
Comment: @hanaa I don't think code is necessary here.
Comment: Set Connection Time out for HttpUrlConnection
Comment: @PiYusHGuPtA But how I change HttpUrlConnection of Picasso?
Answer: You could possibly try something like this in your MainActivity's onCreate (or whereever you want to create the Picasso Builder
    Picasso picasso;
    OkHttpClient okHttpClient;

    okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);

    picasso = new Picasso.Builder(this)
            .downloader(new OkHttpDownloader(okHttpClient))
            .build();

That should give Picasso a timeout of ten seconds. Configure it to your needs.
Full Disclosure: I don't use a timeout. I just noticed this in the API. This may be completely wrong lol.
Comment: Since Picasso 2.5.0 OkHttpDownloader class has been changed, assuming you are using OkHttp3 (and so picasso2-okhttp3-downloader), so you have to do something like this:
Answer: You have two options:

Subclass a Downloader class. Check this for reference implementation
Preconfigure OkHttpClient with timeouts and pass it to Picasso
Comment: given link is dead.


Commerce- How can I modify order details with hook_commerce_paypal_wps_order_form_data_alter()?

Question: I want to modify the information Commerce sends to PayPal so that the order description on PayPal describes the product, not the order (users on my site can only order one of two products, so I think that is more useful).
This is what I want to change:

These strings are in the Commerce Website Payments Standard submodule. I am using the hook_commerce_paypal_wps_order_form_data_alter() function as suggested in the answer to this question.
However, in the API, there is no example for this function (I also looked at the Commerce Examples module but didn't find anything), and I'm a bit lost about how to handle it.
The string I want to override is defined in commerce_paypal_wps_order_form() in this section:
    // Define a single item in the cart representing the whole order
    'amount_1' => commerce_paypal_price_amount(commerce_currency_convert($amount, $order_currency_code, $currency_code), $currency_code),
    'item_name_1' => t('Order @order_number at @store', array('@order_number' => $order->order_number, '@store' => variable_get('site_name', url('<front>', array('absolute' => TRUE))))),
    'on0_1' => t('Product count'),
    'os0_1' => commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()),
  );

I want to change item_name_1 to t('My string') and remove on0_1 and os0_1.
I tried this:
function MYMODULE_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $data['item_name_1'] = t('My string');
  unset($data['on0_1']);
  unset($data['os0_1']);
}

But nothing is changed, even after clearing the caches.  I'm having a really hard time debugging this because it is called immediately before the redirect to PayPal, so even if I use dpm() I'm not able to see it.
Comment: use [dd()](https://api.drupal.org/api/devel/devel.module/function/dd/7) instead of dpm.
Comment: @loolooyyyy Thanks, actually my error turned out to result from failing to clear the caches.  (Two versions of Drush, and it was reading from the wrong .drushrc.  D'oh!)  Since your answer is a good general tip, feel free to add and I will accept.
Comment: I'll add this as an answer. Thanks, that's kind of you but I don't think it's worth 100 points :D
Answer: When you can not see the HTML output of debugging tools such as dpm(), you should use the utility function dd() instead. The logging data will be stored in a file called drupal_debug.txt which you can inspect later.


First difference stationary process

Question: I have a question regarding an I(1) process.
Suppose we have the following equation:
$$
Y_0 = \alpha_1Y_{-1}+\alpha_2Y_{-2}+\alpha_3Y_{-3}+...+\alpha_4Y_{-4}
$$
$$
with \sum\limits_{i=1}^4 \alpha_{i} = 1
$$
How can I prove mathematically that Y is already an I(1) process, given that the sum of the lagged coefficients are equal to one?
Thanks in advance!
Comment: One equation does not prove anything about the properties of the _process_.
Answer: As @Dilip says, your notation is wrong, it should be general as follows, having $t$ in it, together with its ch. eqn:
$$Y_t=\sum_{i=1}^4\alpha_iY_{t-i}\rightarrow 1=\sum_{i=1}^4\alpha_iL^i$$
If the ch. eqn. has $(1-L)^d$ as a factor, than it is $I(d)$. Checking if at least we have $(1-L)$ in its factorization is easy, because if it is, $L=1$ should be a root of the characteristic equation. Substituting into the above equation yieds:
$$1=\sum_{i=1}^4\alpha_i$$
which is already true. So, $L=1$ is a root of the characteristic equation, and $Y_t$ is at least $I(1)$. We can't say anything about larger orders.

First difference stationary process


deserializing the content of a json array in a class shows null values using gson

Question: I am trying to deserialize the content of a json array with name topics.
after deserialing into the pojo, the topics array keeps printing null even though everything seems fine
//entry model
public class MainRequest {

    private  String bookId;
    private List<topics> topics; //called as a list based on the json structure

    }

//topics model
public class topics {
    private String DESCRIPTION;
    private String INDEX;
}

the two models is executed in a controller this way
@PostMapping(path = "/do-library-request", consumes = "application/json")
    public ResponseEntity<?> process(@RequestBody List<MainRequest> mainRequest,
                                                 HttpServletRequest request
    ) {

        Gson gsons = new Gson();

        logger.log(Level.INFO, "Request: {0}", gsons.toJson(mainRequest));

        //out from logger
        {"bookId":"155","topics":[{},{}]} // topics are null and this is the problem

        .......

how can I print the value of the topics is the challenge
[{

       "bookId":"155",

       "topics":[

          {

             "DESCRIPTION":"Little Beginnings",

             "INDEX":"3455"

          },

          {

             "DESCRIPTION":"Nostalgic moments",

             "INDEX":"1234567"

          }

       ],

Comment: Take care of java naming conventions. Class names should start with upper case character and variable names should start with lover case properties
Comment: done as advised and the issue still persists....
Comment: Do you have getter , setter and noargs constructors?
Comment: I have created a smal test program and it works fine `String mainRequest = "[{\r\n" + "\r\n" + "       \"bookId\":\"155\",       \r\n" + "\r\n"+ "       \"topics\":[\r\n" + "\r\n" + "          {\r\n" + "\r\n"+ "             \"DESCRIPTION\":\"Little Beginnings\",\r\n" + "\r\n"+ "             \"INDEX\":\"3455\"\r\n" + "\r\n" + "},\r\n" + "\r\n" + "{\r\n"+ "\r\n" + "             \"DESCRIPTION\":\"Nostalgic moments\",\r\n" + "\r\n"+ "\"INDEX\":\"1234567\"\r\n" + "\r\n" + "}\r\n" + "\r\n" + "]}]"; Gson gsons = new Gson();

  System.out.println(gsons.fromJson(mainRequest, List.class));

 }`
Comment: prints out `[{bookId=155, topics=[{DESCRIPTION=Little Beginnings, INDEX=3455}, {DESCRIPTION=Nostalgic moments, INDEX=1234567}]}]`
Comment: I am using lombok, I will remove it and add the getter and setter manually
Comment: You do not need it. I am also added lombok annotations
Comment: I would try to change name of property `DESCRIPTION` to `description` and add the `@SerializedName` or `JsonProperty` annotation (depends on if you are using gson or jackson in spring boot
Comment: I am using gson, please u can post as answer for better readability
Comment: No because i do not know if it solves your problem
Comment: because u can see that me controller takes this -
@RequestBody List mainRequest,
Comment: more reason why I needed u to post an actual answer
Comment: I have done it.
Comment: still same issuee bro
Answer: Change the variable names of class topic to lower case and add the SerializedName annotation
@Data
public class topics {
    @SerializedName("DESCRIPTION")
    private String description;
    @SerializedName("INDEX")
    private String index;
}

This should solve your problem.
BTW: especialy at this point it is important to follow the java naming convetions


Changing QueryInterface from stdcall to register

Question: We are using Delphi 10.3.2. with OSX64 support. We are developing a project on OSX64 that uses GCC compiled dylib. Dylib libraries on OSX64 by default are not stdcall or cdecl so we have to remove on all functions those directives. We have a problem with QueryInterface that we have to change from stdcall to nothing.
We tried creating our own class of MyIINterface and TMYInterfacedObject but it cannot compile since it returns error

E2211 Declaration of 'QueryInterface' differs from declaration in interface 'MyIInterface'
  mycom.pas(10): Related member: function QueryInterface(const TGUID; out): HRESULT;

How is this possible? Also if we rename QueryInterface to QueryInterface2 in MyIINterface it still requires QueryInterface.
  type

  MyIInterface = interface
    ['{00000000-0000-0000-C000-000000000046}']
    function QueryInterface(const IID: TGUID; out Obj): HResult;
    function _AddRef: Integer;
    function _Release: Integer;
  end;

  MyIUnknown = IInterface;

  TMyInterfacedObject = class(TObject, MyIInterface)
  protected

    function QueryInterface(const IID: TGUID; out Obj): HResult;

Comment: Calling conventions like `stdcall` and `cdecl` only apply to 32bit compilations, they are ignored on 64bit compilations. 64bit compilers automatically use the proper 64bit calling convention for the system being compiled for. So you don't need to remove the calling conventions from code declarations. Whatever problem you are experiencing is related to something else.
Answer: The OSX64 compiler ignores calling convention declarations and uses the platform calling convention for all functions.
The change you are proposing has no effect on any generated code on this platform. However, this change will break your code if you ever come to compile on a platform where the calling convention does matter. You should therefore not make any such change as you propose.
Whatever your problem is, this is not the solution.


Is it ok to select models using MASE and present the metric to client area as MAPE?

Question: My question follow this one.
Metrics such as MASE and MSE have better properties than MAPE.
However, MAPE has an excellent appeal for business areas, because it is easy to interpret and it is compared to the real data.
Where I work, they use cMAPE to select the models and it is calculated as:
$$\text{cMAPE} = \frac{|\text{y}_\text{true} - \text{y}_\text{pred}|}{\max(\text{y}_\text{true}, \text{y}_\text{pred})}$$
It was made like this in order to prevent the occurrence of 0's in y_true. However, clearly, the problem with this metric is that: higher y_pred tends to produce smaller cMAPE.
So, I was thinking of using MASE or MSE to select the models, but show the final result as cMAPE because anyone can understand easily.
Is it valid? Or will it create another problem?
Comment: It might, in that someone else might come along and say "I can do better than (he) did!", and prove it by taking your model, optimizing it with respect to cMAPE, and presenting the results, which, naturally, will have a lower cMAPE than yours.
Answer: You can certainly do this. (You can do a lot of things.)
Here is the thing to keep in mind: if you want to minimize the cMAPE (maybe your bonus depends on getting a cMAPE below a certain number?), you will almost certainly want to give a forecast that is different than if you want to minimize the MSE or the MAE. (The MSE-minimizing forecast is usually also different from the MAE-minimizing one.)
For instance, assume the true demand is Poisson distributed with parameter 0.5. What is the "best" forecast? If by "best" you mean that the expected MSE is minimized, you want to forecast the expected demand, 0.5. If you want to minimize the expected MAE, you want to forecast median demand, which is 0. If you want to minimize the expected cMAPE, you want to forecast 1.

Thus, you can certainly optimize your models so their point forecasts minimizes the MAE or MSE. How do you go from a model to a point forecast? Per above, you need to decide which functional of the predictive density you want to extract. And you can then report cMAPE. However, if you are tasked to reduce the cMAPE, one lever is to extract a different functional than the one you used in minimizing the MSE or MAE.
Taking a step back, I would very much recommend that you tailor your error measure to the functional you want to elicit - not the other way around, as above. How useful in a business sense is it to elicit a point forecast of 1 for a Poisson density with expectation of 0.5? I have never seen a business process that would be optimally controlled through MAPE-optimal forecasts, and I strongly suspect that the cMAPE is no better. Conversely, there are processes that are optimally controlled by unbiased expectation forecasts (which are elicited using the MSE), and others that require quantile forecasts (which you elicit using a pinball loss). For instance, if you want to set safety amounts, you need a quantile forecast for that.
You may be interested in What are the shortcomings of the Mean Absolute Percentage Error (MAPE)? and this paper.
R code for the plot above:
sims <- rpois(10000,0.5)
candidates <- seq(min(sims),max(sims),by=0.01)

mses <- sapply(candidates,function(xx)mean((sims-xx)^2))
maes <- sapply(candidates,function(xx)mean(abs(sims-xx)))
cmapes <- sapply(candidates,function(xx)mean(abs(sims-xx)/pmax(sims,xx)))

opar <- par(mfrow=c(1,3),las=1)
    plot(candidates,mses,type="l",ylab="",main="Expected MSE")
    plot(candidates,maes,type="l",ylab="",main="Expected MAE")
    plot(candidates,cmapes,type="l",ylab="",main="Expected cMAPE")
par(opar)

Comment: ... Re "functional": the paper will make it clearer. I took that term from Gneiting. It's essentially a "one-number summary of a predictive density". The key observation is that there is *always* a predictive density involved, although it may only be implicit. Using MSE as a training loss will elicit the expectation; using the MAE will elicit the median; both are *functionals* of the predictive density. Once you have a predictive density - like the Poisson example above - you can summarize it into a single number in various ways, and which one is best depends on your error measure.
Comment: Thank you so much for the answer! You mention MAE instead of MASE, because the inner part is the same: absolute differenceS?. The same happens to MAPE and cMAPE.
What do you mean by "Per above, you need to decide which functional of the predictive density you want to extract"? You mean, the metric error? and "I would very much recommend that you tailor your error measure to the functional you want to elicit - not the other way around, as above."? I didn't understand the 'functional' term. I will read the paper tonight!
Comment: Yes, MASE is just a scaled MAE. For cMAPE, it depends on how you sum: $\frac{\sum|y_i-\hat{y}_i|}{\sum \text{max}\{y_i,\hat{y}_i\}}$ is a different thing (closer to wMAPE) than $\sum\frac{|y_i-\hat{y}_i|}{\text{max}\{y_i,\hat{y}_i\}}$ (closer to MAPE); which one do you use? ...
Comment: I use the first one. Actually, the function in python is defined as `mape = np.mean(np.abs(y_true - y_pred)/np.maximum(y_true, y_pred))`
Comment: Finally, my recommendation is to first ask whether you want a conditional expectation, or a conditional quantile (at what level?), or a conditional median, and afterwards choosing an error measure that will reward you for finding that functional. Want the conditional expectation? Use MSE. Want a quantile? Use a pinball loss.
Comment: Hm. But with your Python code, you use the second possibility, not the first one, since the `np.mean` is outside the fraction. And then this is not just a scaling of the MAE, just as the MAPE isn't.
Comment: Thank you for the great answer! From my business point of view, I always prefer to use conditional expectation. However, it is hard to present an `MSE` because they always want mape (they don't know that they are calculating it, but they are).
But I see your point. If I select a model based on `MSE` and present it on `MAPE`, the math will not agree. What do you do in those cases? Do you convince the audience to use a less interpretable metric?
Comment: That is indeed a hard problem. On the one hand, [I try to educate people on the pitfalls in forecast accuracy measurement](https://dfep.netlify.app/sec-quality). On the other hand, [we](https://help.sap.com/docs/CARAB/e95c8443f589486bbfec99331049704a/cd577eea46a04c84afa86340ae052d49.html) aim for expectation forecasts (plus a variance forecast and a distributional assumption for safety amount setting). We again try to educate our users, but if we don't seem to get through to them, we do sometimes post-process our forecasts to yield better MAEs by reducing them by a few percent.
Comment: In general, my strategy is to demonstrate to clients that I know what I am doing, and that I indeed try to help them through better forecasting. Once we have built up enough trust, they will listen with more openness when I explain to them that things are not simple, and that being careful about MAPE is not about fooling them, but about helping them to see the issues.
Comment: Nice!! What is "we do sometimes post-process our forecasts"?
Comment: ... "by reducing them by a few percent". We sometimes do this when the client insists on evaluating using MAE/MASE/wMAPE. All of these are scalar multiples of the MAE, so they are minimized in expectation by the conditional median. Since we usually deal with slow moving products, often intermittent ones, the conditional median is usually lower than the conditional expectation, so we reduce our expectation forecasts a bit to get lower MAEs, because the post-processed forecasts are closer to the median. (I emphasize that the business value is driven by the high quantile forecasts, anyway.)
Comment: Ok! But how do you do that ? Do you select the model that produces the smallest MAE? Or do you first select a model based on MSE and then do sth else to give smaller MAE?
Comment: Actually, we don't do model selection at all. We have one model, fit that (regularizing to address the overparameterization), then output its expectation forecast. And then we possibly tweak that. I have been lobbying to also output the conditional median and explaining to customers what the difference is, but haven't quite gotten the resources to do so yet.
Comment: I didn't understand your last comment. And also, I found very interesting the approach "forecast and assess full predictive densities" that you showed in [here](https://forecasters.org/wp-content/uploads/gravity_forms/7-621289a708af3e7af65a7cd487aee6eb/2015/07/Kolassa_Stephan_ISF2015.pdf). Is there anywhere in the web that has a detailed discussion on this topic? Because it was not clear to me how to implement it..
Comment: If you could explain which part of my last comment was confusing, I'll gladly try to explain. About assessing full predictive densities, [take a look at this](https://forecasting-encyclopedia.com/theory.html#evaluating_probabilistic_forecasts) and the papers by Gneiting and colleagues. The tool of choice usually is a *proper scoring rule*, [here is our tag wiki](https://stats.stackexchange.com/tags/scoring-rules/info).


How to make field on account only editable by admin?

Question: How can I make it so that a certain field on the user profile/account is only editable by an admin?  I added the "file" field to accounts, but I want admin's to be the only ones to be able to populate the field.  I dont think there are permissions for this.
Answer: You can use the Field Permissions module to set permissions for a single field.

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Features:

Enable field permissions on any entity, not just nodes.
Role-based field permissions allowing different viewing patterned based on what access the user has.
Author-level permissions allow viewing and editing of fields based on who the entity owner is.
Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


SQL Query matching two fields

Question: I currently have a table called cc_site, in this table I store the results of pings from different ip addresses.
The table has four fields:

auto increment ID field
date (which includes time)
IP address
status (used to determine if the ping was successful or not).

I'm trying to create a query which will give me the latest result based off the date field for an individual ip address. The code I'm currently using is below but it doesn't work unless the IP I'm using in the query is the latest entry in the table.
$query = "SELECT *
          FROM cc_site
          WHERE ip='$host'
          AND Date IN (
              SELECT max(date)
              FROM cc_site
          )";

I knew the query is incorrect however I have not been able to find code that would perform the query I need.
Any help would be great.
Answer: No need of that sub-query. Use can use ORDER and LIMIT instead -
SELECT * FROM cc_site WHERE ip='$host' ORDER BY `date` DESC LIMIT 1

This will sort the records in descending order according to date and return the record with highest record.
Answer: select * from cc_site
where ip='$host' and date in(select max(date) from cc_site where ip='$host');

I think this might give you the answer

SQL Query matching two fields


Mutable default argument for a Python namedtuple

Question: I came across a neat way of having namedtuples use default arguments from here.
from collections import namedtuple
Node = namedtuple('Node', 'val left right')
Node.__new__.__defaults__ = (None, None, None)
Node()

Node(val=None, left=None, right=None)

What would you do if you would want the default value for 'right' to be a empty list? As you may know, using a mutable default argument such as a list is a no no.
Is there a simple way to implement this?
Comment: Why are you asking for something which you yourself say is a no-no?
Comment: @John Zwinck: Can we modify __new__() so that it will change a 'None' into a new [] like we do with user defined classes?
Answer: You can't do that that way, because the values in __defaults__ are the actual default values.  That is, if you wrote a function that did had someargument=None, and then checked inside the function body with someargument = [] if someargument is None else someargument or the like, the corresponding __defaults__ entry would still be None.  In other words, you can do that with a function because in a function you can write code to do whatever you want, but you can't write custom code inside a namedtuple.
But if you want default values, just make a function that has that logic and then creates the right namedtuple:
def makeNode(val=None, left=None, right=None):
    if right is None:
        val = []
    return Node(val, left, right)

Comment: the downside of this solution is one has to know- or to remember- to actually use the factory function rather than the `Node` class. this kind of design choice isn't always obvoius.
Answer: The way given in the accepted answer works great. The only downside I see is that one has to both know (in the case of some other user) and remember to use the factory function instead of the named tuple class- both when creating the object, and when doing things like this:
isinstance(node, Node) #  success
isinstance(node, makeNode) #  misery

A way around this problem might be to do something like what is shown below.
NodeBase = nt('NodeBase', 'val left right')
NodeBase.__new__.__defaults__ = (None, None, None)

class Node(NodeBase):
    '''A namedtuple defined as:

    Node(val, left, right)

    with default values of (None, None, [])'''
    __slots__ = ()
    def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls, *args, **kwargs)
            if obj.right is None:
                obj = obj._replace(right = [])
            return obj

Answer: Since this question has been asked, the dataclasses module has been proposed and accepted into Python.  This module has a lot of overlapping use cases with namedtuples but with some more flexibility and power.  In particular, you can specify a factory function for when you want to specify a default for a mutable field.
from typing import List
from dataclasses import dataclass, field

@dataclass
class Node:
    val: str
    left: List["Node"] = field(default_factory=list)
    right: List["Node"] = field(default_factory=list)

In a data class you specify the types of the various fields, so in this case I had to fill in a few blanks and assume that val would be a string and that left and right would both be lists of other Node objects.
Since right and left are the left hand side of an assignment in the class definition, they are optional arguments when we initialize a Node object.  Further, we could supply a default value, but instead we supplied a default factory, which is a function that is called with 0 arguments whenever we initialize a Node object without specifying those fields.
For example:
node_1 = Node('foo')
# Node(val='foo', left=[], right=[])

node_2 = Node('bar', left=[node_1])
# Node(val='bar', left=[Node(val='foo', left=[], right=[])], right=[])

node_3 = Node('baz')
# Node(val='baz', left=[], right=[])

node_4 = Node('quux', left=[node_2], right=[node_3])
# Node(val='quux', left=[Node(val='bar', left=[Node(val='foo', left=[], right=[])], right=[])], right=[Node(val='baz', left=[], right=[])])

Personally I find myself reaching for dataclasses over namedtuples for any application where I need more than just the thinnest container for data.
Answer: Just small change in implementation from Rick Teachey, the default value can be set outside class:
NodeBase = namedtuple('NodeBase', 'val left right')

class Node(NodeBase):
    __slots__ = ()
    def __new__(cls, *, right=[], **kwargs):
        obj = super().__new__(cls, right=right, **kwargs)
        return obj

#IMPLEMENTATION
kw = {'val': 1, 'left':12}

m  = Node(**kw)
# outputs Node(val=1, left=12, right=[])

Comment: With this code `Node(val=1, left=12, right=1)` produces `Node(val=1, left=12, right=[])`


Integer value comparison

Question: I'm a newbie Java coder and I just read a variable of an integer class can be described three different ways in the API.  I have the following code:
if (count.compareTo(0)) {
            System.out.println(out_table);
            count++;
    }

This is inside a loop and just outputs out_table.
My goal is to figure out how to see if the value in integer count > 0.
I realize the count.compare(0) is the correct way? or is it count.equals(0)?
I know the count == 0 is incorrect. Is this right? Is there a value comparison operator  where its just count=0?
Answer: To figure out if an Integer is greater than 0, you can:

check if compareTo(O) returns a positive number:
if (count.compareTo(0) > 0)
     ...

But that looks pretty silly, doesn't it? Better just...
use autoboxing1:
if (count > 0)
    ....

This is equivalent to:
if (count.intValue() > 0)
    ...

It is important to note that "==" is evaluated like this, with the Integer operand unboxed rather than the int operand boxed. Otherwise, count == 0 would return false when count was initialized as new Integer(0) (because "==" tests for reference equality).

1Technically, the first example uses autoboxing (before Java 1.5 you couldn't pass an int to compareTo) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.
Comment: +1: Regarding the `==` comparison, one should be very cautious when comparing *two* *boxed* numbers (but not one boxed and one primitive number), because, as mmyers mentioned, `==` tests for reference equality, not equality of the wrapped values.
Comment: The former example is using autoboxing; the latter autounboxing.
Answer: Integers are autounboxed, so you can just do
if (count > 0) {
    ....
}

Comment: Ummm. Not really. ... In other comparisons this is not always the case. What if you are comparing two Integers and using '=='? Then the instances are compared, but sometimes the JVM doesn't cache them so it reports identical values as different. See http://stackoverflow.com/questions/10002037/comparing-integer-values-in-java-strange-behavior .
Comment: @ingyhere Integer is autounboxed when comparing with int.
Comment: @Alex78191: In the case of one boxed and one primitive comparison in this example it works, and the left-most value unboxes. This is not guaranteed for comparisons of two Integer objects, at least not in 2013 nor in all JVM implementations. That was the point, if I recall. Anyway, there's little cost to using `if (count.intValue() > 0) { ... }` as a practice except it may be beneficial to _limit_ autounboxing in loops.
Answer: It's better to avoid unnecessary autoboxing for 2 reasons.
For one thing, it's a bit slower than int < int, as you're (sometimes) creating an extra object;
void doSomethingWith(Integer integerObject){ ...
  int i = 1000;
  doSomethingWith(i);//gets compiled into doSomethingWith(Integer.valueOf(i));

The bigger issue is that hidden autoboxing can hide exceptions:
void doSomethingWith (Integer count){
  if (count>0)  // gets compiled into count.intValue()>0

Calling this method with null will throw a NullPointerException.
The split between primitives and wrapper objects in java was always described as a kludge for speed. Autoboxing almost hides this, but not quite - it's cleaner just to keep track of the type. So if you've got an Integer object, you can just call compare() or intValue(), and if you've got the primitive just check the value directly.
Comment: +1 For mentioning the negative sides of autounboxing. The performance difference can be huge, especially when auto(un)boxing in loops.
Answer: You can also use equals:
 Integer a = 0;

 if (a.equals(0)) {
     // a == 0
 }

which is equivalent to:
 if (a.intValue() == 0) {
     // a == 0
 }

and also:
 if (a == 0) {

 }

(the Java compiler automatically adds intValue())
Note that autoboxing/autounboxing can introduce a significant overhead (especially inside loops).
Answer: Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.
Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:
if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.
If you're having trouble understanding this, check out the link above, or imagine it's doing this:
if (count.intValue() > 0) { }

Comment: up vote for informative links.

Keep in mind that `count` has to be non-null. The Exception produced at runtime auto-unboxing a null value is confusing.
Answer: One more thing to watch out for is if the second value was another Integer object instead of a literal '0', the '==' operator compares the object pointers and will not auto-unbox.
ie:
Integer a = new Integer(0);
Integer b = new Integer(0);
int c = 0;

boolean isSame_EqOperator = (a==b); //false!
boolean isSame_EqMethod = (a.equals(b)); //true
boolean isSame_EqAutoUnbox = ((a==c) && (a.equals(c)); //also true, because of auto-unbox

//Note: for initializing a and b, the Integer constructor
// is called explicitly to avoid integer object caching
// for the purpose of the example.
// Calling it explicitly ensures each integer is created
// as a separate object as intended.
// Edited in response to comment by @nolith

Comment: You must instantiate `a` and `b` with `New Integer(0)` otherwise `isSame_EqOperator` will be `true`
Comment: Goodpoint @nolith, though this is due to caching of integers in Java, explained well in the accepted answer to http://stackoverflow.com/questions/3131136/integers-caching-in-java. I will change my answer to use your suggested edit with a comment describing why to explicitly use the constructor.
Answer: well i might be late on this but i would like to share something:
Given the input:
    System.out.println(isGreaterThanZero(-1));
public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

Returns false
public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

Returns true
So i think in yourcase 'compareTo' will be more accurate.

Integer value comparison


cannot run a simple java class

Question: I created a simple java class:
package com.name;

public class Main {
    public static void main (String [] args) {
        System.out.println("I have made it");
    }
}

and save it in Main.java
Then I did java Main.java, and I can see the Main.class
I tried to run it as:
java Main

java com.name.Main

but I kept getting:
Error: Could not find or load main class Main

My java -version output is:
java version "1.8.0_191"
Java(TM) SE Runtime Environment (build 1.8.0_191-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)

and my $JAVA_HOME environment variable is:
/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home

Answer: Your class is in the com.name package, so the class loader expects to find it in a com/name subdirectory:
mkdir -p com/name
mv Main.class com/name
java com.name.Main

Comment: The question and response don't mention the compilation step. It might be worthwhile to include that, since it's how the class file was created in the top directory to begin with. Set the classpath right and compile + execute from the root directory, not the subdirectory.

cannot run a simple java class


Empty Object Repository List in RAD Studio 10.3

Question: I've installed new version of RAD Studio 10.3 a couple days ago on my system Windows 10 Pro 64bit. It required to login with admin rights, i did it.
Then I started RAD Studio from non-administrative account, and when IDE started, I clicked "File - New", and all default items from object repository were lost.
There was no items like "Console application", or "Windows Application". Only folder "Other - Unit Test", with three items: "Code Template", "Project Group", "Text File".
Then I restarted RAD Studio from an administrative account. All items were in list: Console Application, Windows Application, FireMonkey Application.
Then I restarted again from non-administrative account. And no items again.
I searched in web for that problem, it seems it doesn't load items from object repository, when logged in from non-administrative account. But what is the reason? I gave full read/write access in every folder of "Environment Variables" for all user.
Comment: The problem was not in the fact that RAD studio failed to load objects from Object repository but instead the fact that it didn't load your licence properly. You RAD studio checks your licence and then only valid objects based on your licence. So by using Licence manager you might have solved this without messing in registry.
Answer: The problem solved.
I've executed regedit.exe, and deleted branch HKEY_CURRENT_USER\Software\Embarcadero\BDS\20.0
I could rename it, but I had no important settings saved, so I deleted it.
And then I've restarted RAD Studio from non-administrative account. Regedit branch was recreated, and everything became fine. Standart project items appeared.
I think that issue was because of first launch of RAD Studio was by admin account. And it created some wrong paths (which exactly, I didn't find).
Now everything is okay.


Conditional expectation, pinching

Question: Let $\mathfrak{C}$ be a unital $*$-subalgebra of the full matrix algebra $M_n(\mathbb{C}).$
   Let $\mathbb{E}_\mathfrak{C}$ be the orthogonal projection from  $M_n(\mathbb{C}),$ endowed with the
 Hilbert-Schmidt inner product $\langle A,B \rangle = {\rm Tr} \: B^*A$, onto the $*$-subalgebra $\mathfrak{C}.$
   Then it seems to me that the inequality
          $${\rm Tr } \: |\mathbb{E}_\mathfrak{C}(A)|^p \leq {\rm Tr} \: |A|^p$$ holds,
   for every $1 \leq p  < \infty,$ where $|X|=(X^*X)^{1/2}$ denote the absolute value of $X$. I guess this must be written somewhere in literature. Please, could you give me a reference for the result?
Answer: I will prove the case when $p=2$. I hope it will be helpful for you.
Note that $E_\mathfrak{C}$ is a completely positive, unital, trace-preserving map. Using the Schwarz type inequality, we have
\begin{eqnarray}
E_\mathfrak{C}(A)^*E_\mathfrak{C}(A)\leq E_\mathfrak{C}(A^*A).
\end{eqnarray}
Since $\textrm{Tr}E_\mathfrak{C}(A^*A)=\textrm{Tr}A^*A$, we have the desired inequality.
Comment: Thanks! The proof is more or less clear but it would be simpler if I could give a reference.

Conditional expectation, pinching


Extrair atributos de um XML em uma mensagem SOAP

Question: Estou construindo um WebService que retorna status de um objeto, para tanto recebo os dados do objeto para pesquisar na base via mensagem SOAP:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:agr="http://site.temp.br/">
   <soapenv:Header/>
   <soapenv:Body>
      <agr:getObjeto_V1>
         <arg0>
            <TipoObjeto>C</TipoObjeto>
            <CodigoObjeto>999999</CodigoObjeto>
            <Valor>9999999999999</Valor>
            <NomeObjeto>xxxxxxxxxxxx</NomeObjeto>
         </arg0>
      </agr:getObjeto_V1>
   </soapenv:Body>
</soapenv:Envelope>

Esse é a mensagem soap enviada para o webservice, no service eu pego essa mensagem tranquilamente, mas, estou apanhando um pouco para pegar os valores dos nós que estão dentro do nó arg0, estou tentando assim:
        XmlDocument xml = new XmlDocument();
        xml.LoadXml(xmlSoapRequest.InnerXml);

        XmlNodeList xnList = xml.SelectNodes("/Envelope/Body/getObjeto_V1/arg0");
        foreach (XmlNode xn in xnList)
        {
            char TipoObjeto = (char)xn["TipoObjeto"].InnerText[0];
            string CodigoObjeto = xn["CodigoObjeto"].InnerText;
            string valor = xn["Valor"].InnerText;
            string NomeObjeto = xn["NomeObjeto"].InnerText;
        }

Como eu posso fazer isso? Se tiver uma outra forma em que eu não precise selecionar os atributos manualmente, mas, fazer a conversão diretamente para uma classe, eu também aceito.
Comment: Não seria uma opção trabalhar com serialização e deserialização do teu Xml https://pt.stackoverflow.com/a/44245/5846 https://pt.stackoverflow.com/q/13087/5846
Answer: Neste seu caso, eu sugiro que você utilize o LINQ para selecionar os nós que deseja. Uma vez que, não é muito trabalhoso manipular XML com ele.
Veja como obter os valores com o LINQ através deste seu XML, segue o código:
var xml = @"
    <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:agr=""http://site.temp.br/"">
       <soapenv:Header/>
       <soapenv:Body>
        <agr:getObjeto_V1>
            <arg0>
               <TipoObjeto>C</TipoObjeto>
               <CodigoObjeto>999999</CodigoObjeto>
               <Valor>9999999999999</Valor>
               <NomeObjeto>xxxxxxxxxxxx</NomeObjeto>
            </arg0>
         </agr:getObjeto_V1>
       </soapenv:Body>
     </soapenv:Envelope>
";

var objs = (
            from p in XElement.Parse(xml).Descendants("arg0")
            select new
            {
                TipoObjeto = (string) p.Element("TipoObjeto"),
                CodigoObjeto = (string) p.Element("CodigoObjeto"),
                Valor = (string) p.Element("Valor"),
                NomeObjeto = (string) p.Element("NomeObjeto")
            }
          ).ToList();

objs.ForEach(x =>
{
    WriteLine($"Tipo objeto: {x.TipoObjeto}");
    WriteLine($"Codigo objeto: {x.CodigoObjeto}");
    WriteLine($"Valor: {x.Valor}");
    WriteLine($"Nome objeto: {x.NomeObjeto}");
});

Saída:

Tipo objeto: C
  Codigo objeto: 999999
  Valor: 9999999999999
  Nome objeto: xxxxxxxxxxxx

Usei o método Descendants para retornar os elementos descendentes do elemento especificado, que é o elemento arg0, e transformei eles e uma lista que contém uma coleção de objetos de tipo anônimo.
Veja o programa funcionando no .NET Fiddle.
Comment: Eu acabei resolvendo de outra forma, mas, vou testar a sua e te digo depois.


Apache Solr own grouping in autocomplete

Question: The apache solr autocomplete module don't work for me.
I try to achive a relative complex autocomplete,
my target is to achive this on the autocomplete:
Search for "searchword":
-Facet for type/bundle
-Facets based on the results
Show all results for "searchword"
As example:
Search for "test":
Download (176)
Systems (100)
News (20)
Services (5)
Systems
System 1
System n
Services
Service 1
Service n
Show all results for "test"
Any suggestions how I could get this?
Edit: I use apache solr search for this so no search api hook here
(miss some functions in the search api based)
Answer: You can try to write your own query according to results you want to get.
below link may help you in this.
https://www.drupal.org/node/2203775
Comment: already thought about a own module, but no search api in this system (see edit).
Comment: well, you can write your own custom module. That module will alter the query which is working for default autocomplete feature. To add more filter you can use the below code:try {
        $solr = apachesolr_get_solr();
        $params = array(
      'rows' => $count_limit,
      'sort' => 'created desc',
      'qt' => 'standard',
   'wt' => 'standard',
        );                                                                        } catch (Exception $e) {
        watchdog('module name', 'apachesolr: ' . nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
        return NULL;
    }
Comment: Also you can use:$response = $solr->search($query, $params);  //dpm($response); to perform the search.Also there is a function that can be used is :$query->add_filter();
Answer: Found the Module Search Autocomplete will work on this base.
So I just need to add a top Layer for the facet and group the results.


The locus of points $z$ which satisfy $|z - k^2c| = k|z - c|$, for $k \neq 1$, is a circle

Question: Use algebra to prove that the locus of points z which satisfy $|z - k^2c| = k|z - c|$, for $k \neq 1$ and $c = a + bi$ any fixed complex number, is a circle centre $O$.
Give the radius of the circle in terms of $k$ and $|c|$.
I squared both sides and got this:
 $$(k^2−1)x^2+(k^2−1)y^2+(a^2+b^2-k^2a^2-k^2b^2)k^2=0$$
I might have gone wrong somewhere though.
Edit. Never mind, I didn't go wrong.
$$(k^2-1)x^2+(k^2-1)y^2-(k^2-1)k^2a^2-(k^2-1)k^2b^2=0$$
$$x^2+y^2=k^2(a^2+b^2)$$
$$r^2=k^2(a^2+b^2)$$
$$r=k|c|$$
Comment: First, as a general rule, don't substitute in for $z$ or $c$ until you have to, your calculations will be simpler.  Second, use the fact that if $w$ iw a complex number, $|w|^2=w\cdot \overline{w}$.  That will square it properly.
Answer: Here are the steps
$$ \left|z - k^2c\right| = k\left|z - c\right| $$
$$ \left|z - k^2c\right|^2 = k^2\left|z - c\right|^2 $$
$$ \left(z - k^2c\right)\left(\overline{z - k^2c}\right) = k^2(z - c)\left(\overline{z-c}\right) $$
$$ \left(z - k^2c\right)\left(\overline{z} - k^2\overline{c}\right) = k^2(z - c)\left(\overline{z}-\overline{c}\right) $$
$$ \left|z\right|^2 - k^2\overline{c}z-k^2c\overline{z}+k^4\left|c\right|^2= k^2\left(\left|z\right|^2-\overline{c}z-c\overline{z} + \left|c\right|^2\right) $$
$$ \left|z\right|^2 - k^2\overline{c}z-k^2c\overline{z}+k^4\left|c\right|^2= k^2\left|z\right|^2-k^2\overline{c}z-k^2c\overline{z} + k^2\left|c\right|^2 $$
$$ \left|z\right|^2 -k^2c\overline{z}+k^4\left|c\right|^2= k^2\left|z\right|^2-k^2c\overline{z} + k^2\left|c\right|^2 $$
$$ \left|z\right|^2 +k^4\left|c\right|^2= k^2\left|z\right|^2 + k^2\left|c\right|^2 $$
$$ \left|z\right|^2 -k^2\left|z\right|^2= k^2\left|c\right|^2 -k^4\left|c\right|^2$$
$$ \left|z\right|^2\left(1 -k^2\right)= k^2\left|c\right|^2\left(1 -k^2\right)$$
$$ \left|z\right|^2= k^2\left|c\right|^2$$
$$ \left|z\right|= k\left|c\right|$$
Comment: The second line does not follow from the first line: for a complex number, $|w|^2=w\cdot \overline w$, not $|w|^2=w^2.
Comment: @Aaron, please see my edit. Thank you.
Comment: Yes, everything looks correct now.
Answer: Hint: If you square both sides, and expand out (initially writing things in terms of your variables and their complex conjugates), you will get a lot of useful cancellation.
Here is the beginning of such a calculation, to help you out.
Squaring the left hand side yields:
$$(z-k^2c)(\overline{z}-k^2\overline{c})=|z|^2+k^4|c|^2-k^2(z\overline{c}+\overline{z}c).$$
Similarly, squaring the right hand side yields:
$$k^2(|z|^2+|c|^2-(z\overline{c}+\overline{z}c)).$$
Setting the two sides equal and rearranging, we have
$$(k^2-1)|z|^2=(k^4-k^2)|c|^2.$$
Answer: instead of squaring let me see if conjugates help.
$\begin{eqnarray}
0 = |z - k^2c|^2 -k^2 |z -c|^2 &=& (z - k^2 c)(\bar z - k^2 \bar c) -k^2(z-c)(\bar z - \bar c) \\
&=& z \bar z - k^2 c \bar z - k^2\bar c z + k^4 c \bar c -k^2(z \bar z - c \bar z -z  \bar c + c \bar c)  )\\
&=&(1-k^2)z \bar z - k^2(1-k^2)c\bar c \\
&=&(1-k^2)(|z|^2 - k^2|c|^2)
\end{eqnarray}$
$ \mbox{ if } k^2 \neq 1, \mbox{ then } |z|^2 = k^2|c|^2$


ERROR - SSH operator error: timed out in Airflow while connecting with ec2 instance

Question: I am getting a timeout error while trying to connect with ec2 instance.
I can connect to the machine through ssh command:

ssh -i keypair.pem myuser@ec2IPaddress

My connection file has the following things:

conn Id: ssh_custom
  Conn Type: SSH
  Host: ec2IPaddress
  Username: myuser
  Port: 8888
  Extra: {"key_file":"/home/ubuntu/keypair.pem", "no_host_key_check": "false", "allow_host_key_change": "true", "timeout": "45"}

My dag file looks like:
from airflow import DAG
import datetime as dt
from airflow.operators.bash_operator import BashOperator
from airflow.contrib.hooks.ssh_hook import SSHHook
from airflow.contrib.operators.ssh_operator import SSHOperator

sshHook = SSHHook(ssh_conn_id='ssh_custom')

default_args = {
    'owner': 'arpita',
    'start_date': dt.datetime(2019, 11, 20),
    'retries': 1,
    'retry_delay': dt.timedelta(minutes=5),
    'depends_on_past': False,
    'email': ['email@example.com'],
    'email_on_failure': True,
    'email_on_retry': True,
}

with DAG('sample',
         default_args=default_args,
         schedule_interval='30 * * * *',
         ) as dag:
     task1 = SSHOperator(task_id="task1",
                         command='echo $HOSTNAME',
                         ssh_hook=sshHook)

task1

Getting the error:
ERROR - SSH operator error: timed out
Traceback (most recent call last):
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/contrib/operators/ssh_operator.py", line 101, in execute
    with self.ssh_hook.get_conn() as ssh_client:
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/contrib/hooks/ssh_hook.py", line 180, in get_conn
    sock=self.host_proxy)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/paramiko/client.py", line 349, in connect
    retry_on_signal(lambda: sock.connect(addr))
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/paramiko/util.py", line 280, in retry_on_signal
    return function()
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/paramiko/client.py", line 349, in <lambda>
    retry_on_signal(lambda: sock.connect(addr))
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/models/taskinstance.py", line 926, in _run_raw_task
    result = task_copy.execute(context=context)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/contrib/operators/ssh_operator.py", line 173, in execute
    raise AirflowException("SSH operator error: {0}".format(str(e)))
airflow.exceptions.AirflowException: SSH operator error: timed out
[2019-11-26 15:23:20,254] {taskinstance.py:1080} INFO - All retries failed; marking task as FAILED
[2019-11-26 15:23:20,284] {logging_mixin.py:95} INFO - [[34m2019-11-26 15:23:20,284[0m] {[34mconfiguration.py:[0m299} WARNING[0m - section/key [[1msmtp[0m/[1msmtp_user[0m] not found in config[0m
[2019-11-26 15:23:20,284] {taskinstance.py:1086} ERROR - Failed to send email to: ['firstname.lastname@example.com']
[2019-11-26 15:23:20,285] {taskinstance.py:1087} ERROR - [Errno 111] Connection refused
Traceback (most recent call last):
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/contrib/operators/ssh_operator.py", line 101, in execute
    with self.ssh_hook.get_conn() as ssh_client:
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/contrib/hooks/ssh_hook.py", line 180, in get_conn
    sock=self.host_proxy)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/paramiko/client.py", line 349, in connect
    retry_on_signal(lambda: sock.connect(addr))
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/paramiko/util.py", line 280, in retry_on_signal
    return function()
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/paramiko/client.py", line 349, in <lambda>
    retry_on_signal(lambda: sock.connect(addr))
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/models/taskinstance.py", line 926, in _run_raw_task
    result = task_copy.execute(context=context)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/contrib/operators/ssh_operator.py", line 173, in execute
    raise AirflowException("SSH operator error: {0}".format(str(e)))
airflow.exceptions.AirflowException: SSH operator error: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/models/taskinstance.py", line 1084, in handle_failure
    self.email_alert(error)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/models/taskinstance.py", line 1307, in email_alert
    send_email(self.task.email, subject, html_content)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/utils/email.py", line 55, in send_email
    mime_subtype=mime_subtype, mime_charset=mime_charset, **kwargs)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/utils/email.py", line 101, in send_email_smtp
    send_MIME_email(smtp_mail_from, recipients, msg, dryrun)
  File "/home/ubuntu/airflow/.venv/lib/python3.5/site-packages/airflow/utils/email.py", line 121, in send_MIME_email
    s = smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) if SMTP_SSL else smtplib.SMTP(SMTP_HOST, SMTP_PORT)
  File "/usr/lib/python3.5/smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.5/smtplib.py", line 335, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.5/smtplib.py", line 306, in _get_socket
    self.source_address)
  File "/usr/lib/python3.5/socket.py", line 711, in create_connection
    raise err
  File "/usr/lib/python3.5/socket.py", line 702, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

Comment: Are you sure you set up your SSH keys correctly? Also, double check to make sure your instance doesn't have any firewall rules that conflict
Answer: The problem is solved, actually, the port number 8888 was incorrect. It worked with port number 22.
Comment: I am trying to set connection from airflow to my aws ec2 linux server using ssh connection option. Normally I am able to ssh to that ec2 instance but I try Airflow ssh connection test I get [Errno 2] No such file or directory: '/Users/archanakarpe/Downloads/20-march.pem'
Comment: Path and permission works when I directly ssh to that ec2 instance. So as cloudwalker.io/2019/09/01/airflow-connections/… airflow-connections document is saying Note: There are a couple of catches before you jump ahead Make sure you are able to access your Linux box from airflow server before jumping head. Install the following python library and its dependencies ssh_tunnel So could someone help me how to set this ssh_tunnel in this case or is something else I am doing wrong? Please guide me


How to show the Contribution of Independent variables in terms of percentage in Multiple regression?

Question: I would like to show the independent variables (IV) contribution in percentage. For example,
Regression equation is HeatFlux = 389 + 2.12 East + 5.32 South - 24.1 North
R-Sq = 87.4%   R-Sq(adj) = 85.9%

Here, how would I say East is contributing X% and South is contributing y%? Is there any method to show this?
Answer: You can use standardized coefficients (although beware that their interpretation is controversial). In SPSS you can choose to have this produced in the output. In R you can use the lm.beta() function in the 'QuantPsych' package:
http://www.inside-r.org/packages/cran/QuantPsyc/docs/lm.beta
The standardized coefficients can give you an indication of the relative contribution that the variable is making in predicting your IV. Higher values indicate higher contributions...These can then be translated into a percentage of contribution (if your standardized coefficients are B1, B2, B3, B4, then the percentage of contribution for B1 would be: B1/(B1+B2+B3+B4) - but this is not a typical thing to report and could be very misleading).
Comment: You probably want to look at the coefficient of partial determination. This will give you the percentage change in the sum of squares of errors when for each IV...For instance, have a look at Applied Linear Statistical Models (2005 edition) by M.H. Kutner, C.J. Nachtsheim, J. Neter, and W. Li SEction 7.4 (p. 268ff)
Comment: Thanks for this. Can we say this with R-squared? Like, with all these 3 IVs the R^2 is 85.9%. Let's say we are removing one of them and there will be a change in the R^2. Can we consider this change in terms of percentage? I seek experts' views on this.


Prove that a manifold is not orientable

Question: I have found a proposition who says: A manifold M is not orientable if it contains a Moebius band. How can I prove this?
Comment: Open is impossible if ${\rm dim M}>2$.
Comment: Interesting question: the converse implication!
Comment: @Martín-BlasPérezPinilla interesting remark! Is it true?
Comment: More hypothesis required. Can you check the the exact wording?
Comment: If a Manifold isn't orientable then it contains an open subset diffeomorphic to the Moebius band.. Is this the right claim?
Comment: a submanifold?why open is impossible?
Comment: ?!?! I misread you and understood open subset of $M$.
Comment: Definitely true for surfaces. Maybe true for embedded submanifolds (http://en.wikipedia.org/wiki/Submanifold#Embedded_submanifolds). I think that the oriented atlas of $M$ restricted to the submanifold works.
Comment: Update: Klein bottle can be embedded in ${\bf R}^4$.
Answer: If $M$ were orientable, the Moebius band will inherit the orientation of $M$.
Comment: Martin thanks for your answer. If i want to prove that the Moebius band isn't orientable, without using the vector normal, only with the definition of oriented atlas, what i might to do? I've seen there is a similar post but it don't answered completely this question. Thanks.
Comment: Thank you for your comment!
Comment: See http://math.stackexchange.com/questions/15602/why-is-the-mobius-strip-not-orientable. And maybe *Differential Forms and Applications* (do Carmo) has *another* argument that I can't remember.
Comment: I think we can´t use this argument because the mobius strip is not open. We have: If M is a orientable manifold, then every open subset of M is a orientable manifold.
Answer: The claim is incorrect.  Euclidean space $M=\mathbb{R}^3$ contains the Mobius band but $M$ is orientable.
Comment: Is a submanifold?
Comment: The usual picture of the Mobius band in Euclidean space represents it as a submanifold. A parametrisation can be found in most elementary differential geometry textbooks.  Of course if $M$ is 2-dimensional the claim is true.
Comment: This is the exercice: I have the Moebius band M, the quotient of the square $[0,1]x\times [0,1]$ with the projection map $\pi \colon [0,1]\times [0,1]\to M$. After prove that the Moebius band isn't orientable conseider $M^°=\pi([0,1]\times (0,1)$. Show that $M^°$ and every manifold which contains an open set diffeomorphic to $M^°$ is not orientable.
Comment: So @user72694 the claim is true only in 2-dimensional manifolds? How we can generalize it for prove that a manifold isn't orientable? thanks
Comment: @user72694 the Moebius band is contained in ${\Bbb R}^3$ like ${\Bbb R}^2$ in ${\Bbb R}^3$? There are several definitions of submanifolds with adjectives. In any case, you are right, the simple condition of subset isn't enough. More is required.
Comment: @Martín-BlasPérezPinilla however, what is the right claim? what hyp. needs?
Comment: @user72694, please, can you check if my comment about embedded submanifolds makes sense?
Answer: We have:
1) The mobius strip is not orientable.
2) let $f:M\rightarrow$ N  be is a diffeo. M is orientable iff N is orientable.
3) Every open subset of a orientable manifold is a orientable manifold.
Let M be the mobius strip, U subset of N and $f:U\rightarrow$ M diffeomorphism.
Suppose that N is orientable. Then by 3) we have U is a orientable manifold.
Since $f:U \rightarrow$ M is a diffeo by 2)  M is orientable. Contradition.

Prove that a manifold is not orientable