Optimal control problem with minimization of cost

Question: Consider the scalar system $\dot{x}=x+u$, given the constraint $u(t+T)=u(t)$. Find the control that drive $x(0)=1$ to $x(2T)=0$ and minimizes $$\int_0^{2T}u^2(t)\,\mathrm{d}t$$
Attempt: substituting $u(t)$ we get $$J=2\int_0^T (\dot{x}^2-2x\dot{x}+x^2 )dt$$
Now i can use Euler Lagrange's eq to find a differential equation of the form $$\ddot{x}=x \implies x(t)=c_1e^{t}+c_2e^{-t}$$
Now i can find $c_1$ and $c_2$ using Initial conditions, then find $x(t)$ and after that i can get the optimal control $u^{*}=\dot{x}-x$.
Is my attemp correct ? i'm unsure about using the constrain given, in the first step of the integral i took out the factor $2$ with incorporates the constrain, is this a valid method ?
Comment: The more grave error is that you did not consider the repeating condition in any way.
Comment: One could probably argue that the Euler-Lagrange equation is a local property, so that the general form of the solution remains, but with possibly different coefficients inside $(0,T)$ and $(T,2T)$. You only have to ensure that $$u(t)=-2c^1_2e^{-t}=u(T+t)=-2c^2_2e^{-T-t},$$ and then ensure continuity of $x$ at $t=T$ and also the boundary condition to get 4 equations for the 4 parameters on the two segments.
Comment: @LutzL yes i know something is wrong, how do it consider this ?
Answer: Reformulate the problem as a system over the interval $[0,T]$, so that $x_1(t)=x(t)$ and $x_2(t)=x(T+t)$ with the equations
$$
\dot x_1(t)=x_1(t)+u(t)\\
\dot x_2(t)=x_2(t)+u(t)
$$
with the boundary conditions now including the connection condition $x_1(T)=x_2(0)$ additional to $x_1(0)=1$,  $x_2(T)=0$.
Then establish the Lagrange functional with the usual Hamilton function
\begin{align}
L(x,u,\psi,λ)&=\lambda(x_2(0)-x_1(T))+\int_0^T\left[u^2+\sum_{k=1,2}\psi_k(\dot x_k-x_k-u)\right]dt
\\
&=λ(x_2(0)-x_1(T))+\int_0^T(H(x,u,ψ)+ψ_1\dot x_1+ψ_2\dot x_2)dt
\\
\text{where } H(x,u,ψ)&=u^2-ψ_1(x_1+u)-ψ_2(x_2+u).
\end{align}
The usual variational calculus gives
\begin{multline}
δL=δλ(x_2(0)-x_1(T))+λ(δx_2(0)-δx_1(T))+\sum_{k=1,2}[\psi_k(T)δx_k(T)-\psi_k(0)δx_k(0)\\
+\int_0^T\left[2uδu+\sum_{k=1,2}δ\psi_k(\dot x_k-x_k-u)-\sum_{k=1,2}\dot\psi_kδx_k+\sum_{k=1,2}\psi_k(-δx_k-δu)\right]dt
\end{multline}
Because of the fixed boundary conditions, $δx_1(0)=0=δx_2(T)$.
The equilibrium equations are thus
\begin{align}
\psi_1(T)&=λ\\
\psi_2(0)&=λ\\
2u(t)&=\psi_1(t)+\psi_2(t),&(0&=H_u)\\
\dot \psi_k&=-\psi_k&(\dot \psi&=H_x,~\dot x=-H_\psi)
\end{align}
giving $\psi_k(t)=\psi_k(0)e^{-t}$, in the connecting equation $\psi_2(0)=\psi_1(0)e^{-T}$, so that consequently $u(t)=\frac12e^{-t}(1+e^{-T})\psi_1(0)=Ae^{-t}$.
Inserting this control into the original equations we get
$$
e^{-t}x_k(t)-x_k(0)=\int_0^tAe^{-2s}ds=A\frac{1-e^{-2t}}2\\~\\
x_k(t)=x_k(0)e^t+A\sinh(t)
$$
The connecting equation is then
$$
x_1(0)e^T+A\sinh(T)=x_2(0)
$$
and inserting boundary conditions gives
$$
\left(e^T+A\sinh(T)\right)e^T+A\sinh(T)=0
\\
\implies A=-\frac{e^{2T}}{(1+e^T)\sinh(T)},~~ x_2(0)=\frac{e^T}{1+e^T}.
$$
Thus all the parts of the solution are computed. For $t\in[0,T]$ it is
\begin{align}
x(t)&=e^t-\frac{e^{2T}}{1+e^T}\frac{\sinh(t)}{\sinh(T)}\\
x(T+t)&=\frac{e^{T+t}}{1+e^T}-\frac{e^{2T}}{1+e^T}\frac{\sinh(t)}{\sinh(T)}
\end{align}
Answer: Here is a straightforward elementary approach:

The unique $x$-solutions to the initial value problem
$$\dot{x}-x~=~u, \qquad x(0)~=~1,\tag{1}$$
and the final value problem
$$\dot{x}-x~=~u, \qquad x(2T)~=~0,\tag{2}$$
are
$$ x(t) ~\stackrel{(1)}{=}~e^t \left(1 + \int_0^t \!ds ~e^{-s}u(s)\right),\tag{3} $$
and
$$ x(t)~\stackrel{(2)}{=}~-e^t  \int_t^{2T} \!ds ~e^{-s}u(s)~=~-e^t  \int_t^{2T} \!ds ~e^{-s}u(s\!-\!T),\tag{4}$$
respectively. In the last equality of eq. (4) we used that $u$ is $T$-periodic.
We demand that the two $x$-solutions (3) and (4) agree at $t=T$, which leads to a constraint
$$ 1 + \int_0^T \!ds ~e^{-s}u(s)
~\stackrel{(3)+(4)}{=}~-\int_T^{2T} \!ds ~e^{-s}u(s\!-\!T)~=~-e^{-T}\int_0^T \!dt ~e^{-t}u(t),\tag{5}$$
or equivalently
$$\chi~:=~\int_0^T \!dt ~e^{-t}u(t)+\frac{1}{1+e^{-T}}~\stackrel{(5)}{=}~0. \tag{6}$$
The constraint (6) is implemented via a Lagrange multiplier. We want to minimize the functional
$$ J[u,\lambda]~:=~\frac{1}{2}\int_0^T \!dt ~u(t)^2~+~\lambda\chi ~\stackrel{(6)}{=}~\int_0^T \!dt \left( \frac{u(t)^2}{2} +\lambda e^{-t}u(t)\right) + \frac{\lambda}{1+e^{-T}}. \tag{7}$$
The Euler-Lagrange (EL) equation for the control $u$ is
$$ u(t)~=~-\lambda e^{-t}, \qquad t~\in~ [0,T],\tag{8}$$
and hence by $T$-periodicity
$$ u(t)~=~u(t\!-\!T)~=~-\lambda e^{T-t}, \qquad t~\in~ ]T,2T].\tag{9}$$
Inserting the $u$-solution (8) into the constraint (6) we find
$$ \frac{1}{1+e^{-T}}~\stackrel{(6)+(8)}{=}~
\lambda\int_0^T \!dt ~e^{-2t}~=~\frac{\lambda}{2}(1-e^{-2T}),\tag{10}$$
so the Lagrange multiplier is
$$ \lambda~\stackrel{(10)}{=}~\frac{2}{(1+e^{-T})(1-e^{-2T})}.\tag{11} $$
The optimal $x$-solution becomes
$$ x(t)~\stackrel{(3)+(8)}{=}~e^{t}\left(1-\frac{\lambda}{2}(1- e^{-2t})\right), \qquad t~\in~ [0,T];\tag{12}$$
$$ x(t)~\stackrel{(4)+(8)}{=}~\frac{\lambda}{2}e^{T-t}(1- e^{-2t}), \qquad t~\in~ [T,2T].\tag{13}$$
Comment: Not necessary. The optimal control is already listed in eqs. (8)-(9).
Comment: in (4) why the minus appears ?
Comment: Because the independent variable $t$ is in the lower (rather than in the upper) integration limit of eq. (4).
Comment: And in (7) how did you found out the functional ?
Comment: I updated the answer.
Comment: thanks so the solution for $[0,2T] $ is the total of 12 and 13, and to find the control i need to find $u=\dot{x}-x$ ?


Float action button anchor with include layout

Question: do you know if it is possible to use the id views included in a layout as anchor of a FAB ? For example :
<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_anchor="@id/map"
    app:layout_anchorGravity="bottom|right|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_menu_add" />

"@id/map" is inside the inclued layout content_main.
With this code I currently get the follow error:

Error:(30, 28) No resource found that matches the given name (at
  'layout_anchor' with value '@id/map').

For information I'm use the include for trying to reduce my main layout size.
It seem that "@id/map" is not visible for the FAB anchor. But I perhaps doing something wrong.
Answer: I guess you are missing Tag Id android:id="@+id/map"
Open your @layout/content_main

Floating action buttons are used for a special type of promoted
  action. They are distinguished by a circled icon floating above the UI
  and have special motion behaviors related to morphing, launching, and
  the transferring anchor point.

Error:(30, 28) No resource found that matches the given name (at 'layout_anchor' with value '@id/map').

Comment: If that can help, I had the same problem again. Because I use `app:layout_anchor="@id/textView"` instead of `app:layout_anchor="@+id/textView"`. I think we cannot use `"@id/..."` with an included id.
Comment: I apologize for the late answer. You are right Amiya, it was a typo in the include file. Thank you for your help :)
Answer: I think plus"+" is missing in app:layout_anchor="@+id/map"
Answer: In some cases it's because the AppBarLayout is declared after the view calling it as anchor in the xml file.


Evaluate $\int_0^\infty e^{-x}\sin e^{-x}\cos e^{-x} \ln e^{-x}\;dx$

Question: How to evaluate the following integral?
$$\int_0^\infty e^{-x}\sin e^{-x}\cos e^{-x} \ln e^{-x}\;dx$$
Comment: @CameronWilliams you still have that $\ln e^{-x}$ term. Using IBP doesn't make it clean either.
Comment: @CameronWilliams Making the variable change wouldn't be advised. Then you would have $\ln u$
Comment: @VarunIyer Oh doh. You're right.
Comment: According to Wolfram Alpha, this gives a cosine integral so it seems like there is a typo of some sort.
Answer: Considering $$I=\int e^{-x}\sin (e^{-x})\cos( e^{-x}) \ln (e^{-x})\;dx$$the most natural change of variable seems to be $e^{-x}=t$. So $$I=-\int\log (t) \sin (t) \cos (t)\;dt=-\frac 12\int\log (t) \sin (2t) \;dt$$ Integrating by parts once to remove the logarithm then leads to $$I=\frac{1}{4} \log (t) \cos (2 t)-\frac{\text{Ci}(2 t)}{4}$$ and to the integral the result is $$\frac{1}{4} (\text{Ci}(2)-\gamma -\log (2))$$
Comment: @Integrator. It is amazing to notice that, very often, this happens to you and I : same answer, same time ! Cheers. Your turn now.
Answer: First substituting $z=e^{-x}$ and then integrating by parts, this integral may evaluated in terms of the cosine integral function, $\operatorname{Ci}{(x)}$:
$$\begin{align}
\mathcal{I}
&=\int_{0}^{\infty}e^{-x}\sin{\left(e^{-x}\right)}\cos{\left(e^{-x}\right)}\ln{\left(e^{-x}\right)}\,\mathrm{d}x\\
&=\int_{0}^{1}\sin{(z)}\cos{(z)}\ln{(z)}\,\mathrm{d}z\\
&=\left[\sin^2{(z)}\ln{(z)}\right]_{0}^{1}-\int_{0}^{1}\sin{(z)}\left(\frac{\sin{(z)}}{z}+\cos{(z)}\ln{(z)}\right)\,\mathrm{d}z\\
&=-\int_{0}^{1}\frac{\sin^2{(z)}}{z}\,\mathrm{d}z-\int_{0}^{1}\sin{(z)}\cos{(z)}\ln{(z)}\,\mathrm{d}z\\
&=-\int_{0}^{1}\frac{\sin^2{(z)}}{z}\,\mathrm{d}z-\mathcal{I}\\
\implies 2\mathcal{I}&=-\int_{0}^{1}\frac{\sin^2{(z)}}{z}\,\mathrm{d}z\\
\implies \mathcal{I}&=-\frac12\int_{0}^{1}\frac{\sin^2{(z)}}{z}\,\mathrm{d}z\\
&=-\frac14\int_{0}^{1}\frac{1-\cos{(2z)}}{z}\,\mathrm{d}z\\
&=-\frac14\int_{0}^{2}\frac{1-\cos{(t)}}{t}\,\mathrm{d}t\\
&=-\frac14\operatorname{Cin}{(2)}\\
&=-\frac14\left(\gamma+\ln{(2)}-\operatorname{Ci}{(2)}\right).\\
\end{align}$$

Note on Definitions:
A couple of different definitions of the cosine integral function, $\operatorname{Ci}{(x)}$, include either,
$$\operatorname{Ci}{(x)}:=-\int_{x}^{\infty}\frac{\cos{t}}{t}\,\mathrm{d}t,$$
or,
$$\operatorname{Ci}{(x)}:=\gamma+\ln{(x)}+\int_{0}^{x}\frac{\cos{t}-1}{t}\,\mathrm{d}t.$$
For convenience we may also define the related auxiliary function, $\operatorname{Cin}{(x)}$,
$$\operatorname{Cin}{(x)}:=\int_{0}^{x}\frac{1-\cos{t}}{t}\,\mathrm{d}t,$$
implying the relation,
$$\operatorname{Cin}{(x)}=\gamma+\ln{(x)}-\operatorname{Ci}{(x)}.$$
Comment: $\operatorname{Ci}, \operatorname{Cin}$... what kind of functions are these?
Comment: @Joe The function Ci is the cosine integral function. I've updated my response to include a note on the definitions. The link goes to the associated Wikipedia article.


What does combined block caching option 'DRUPAL_CACHE_PER_ROLE|DRUPAL_CACHE_PER_PAGE' do?

Question: I understand that certain block caching options can be combined. What does it mean if I set the caching option of a block defined in code to DRUPAL_CACHE_PER_ROLE|DRUPAL_CACHE_PER_PAGE?
I am confused by the OR bitwise operator. Does this mean that the block will not only be cached by page, but also by role? For example, if User role A visits the same page as User role B, they will each see different cached versions of the block despite being on the same page?
Answer: According to the documentation:

Page and user settings can be combined with a bitwise-binary or operator; for example, DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change depending on the user role or page it is on.

In other words: When the block is cached, information about the user role and page are stored with it. The cached version is served only in situations where both the current user role and the current page match those of the cached block.
A good example in Drupal 7 core is the Author Information block (see block info, block view). It must vary by page, because every page can have a different author, and it must vary by role, because not every role may have permissions to view the author information.


If $|f'(x)| \leq c|f(x)|$ for all $x \in (0,1)$ then $f(x)=0$

Question: Question:   Let $f:[0,1] \to \mathbb{R}$ be a real valued continuous function which is differentiable on $(0,1)$, and satisfies $f(0)=0$. Suppose there exists a $c \in (0,1)$ such that $|f'(x)| \leq c|f(x)|$ for all $x \in (0,1)$. Show that $f(x)=0$.
Solution attempt:
$f$ being continuous at $x=0$, for a given $\epsilon >0$ $\exists$ a $\delta>0$, such that $|f(x)|< \epsilon$ whenever $x \in [0, \delta) \cap [0,1]$.
Now, consider $|f'(h)|=|\lim_{k \to 0}\frac{f(h+k)-f(h)}{k} |\leq |cf(h)| \implies \lim_{ \ k \to 0} |f(2h)| \leq |f(h)|[1+ c|k|] $ Being continuous at $x=0$, $\lim_{h \to 0} f(h) = f(0) = 0 \implies f(2h) = 0$ [by applying $|f(2h)| \leq |f(h)|(c|k|+1) \ $].
In this manner, let us partition the interval $[0,1)$ into $n$ subintervals of length $h$ each. As the length $h \to 0$, $n \to \infty$, and recursively, we get $|f(rh)| \leq |f(h)|(c|k|+1)^r \ $. Hence, finally for all $r$, we get $f(rh)=0$. By continuity, we can safely say, for all $x$ in those respective subintervals, $f(x)=0$. Again, by continuity, we have $\lim_{ x \to 1} f(x) = 0$.
Hence, $f(x)=0$ for all $x$ in $[0,1]$.
Comment: Still makes no sense. $|f'(h)|=|\lim_{k\to 0} \frac {f(h+k)-f(k)} k|$. Don't mix variables.
Comment: The third line in your attempt does not make sense.
Comment: I am referring to $|f'(x)|=|\lim \frac {f(h+h)-f(h)} h|$
Comment: You cannot use the same variable in your limit $(h)$ and the value of $f'$, they have to be "independent" of one another
Comment: @KaviRamaMurthy which is?
Comment: Oh no!!!! I meant $f'(h)$
Comment: Can you please point out why?
Comment: I see my mistake now. Any other corrections?
Comment: @TheGreatDuck Did not quite understand your question!?
Comment: It is actually from an entrance exam. I am not sure about "mathematical contexts" though
Answer: Let $M$ be the sup norm of $f$. Let us prove by induction that $|f(x)| \leq \frac{c^nMx^n}{n!}$.
If $n=0$, this is obvious.
Let $n \geq 0$ be such that $|f(x)| \leq \frac{c^nMx^n}{n!}$ for each $x$.
Then $|f'(x)| \leq \frac{c^{n+1}Mx^n}{n!}$ for each $x$.
Since $f(0)=0$, integration yields the desired inequality.
Now,  the $RHS$ goes to $0$ as $n$ goes to $\infty$, thus $f=0$ (note that $c<1$ is unimportant).
Comment: To be brutally honest, I don't think so. It seems to me to be very deeply flawed owing to it not manipulating limits with the necessary rigor. However, I cannot prove that there is no proof that borrows some part of your ideas, so ... ;)
Comment: Can you please check out mine?! Correcting the mistakes will help me immensely.
Comment: Ok: what does the inequality just after the first $\Rightarrow$ mean?
Comment: I used the fact that $||a|-|b||≤|a-b|$ and $k$ approaches $0$
Comment: No, you did not. Because this inequality does not mean anything. $k$ is defined on the right hand side but not on the left hand side, for instance.
Comment: Why is that so?
Comment: What number is $\lim_{k \rightarrow 0}\,|f(2h)|$?
Comment: The value is independent of $k$; on the other side of inequality, I did not mention $k \to 0$
Comment: I left $k$ there. Does it count wrong?
Comment: I suggest that you rewrite carefully your proof by replacing all the limits by their rigorous definitions, with the proper quantification and dependencies between variables. If there is no flaw, it should work out very cleanly — else you have a problem.
Comment: For your previous comment which I had not seen: it is not a matter of counting wrong, it is a matter of having an undefined variable in an inequality.
Comment: Is my approach towards the solution at all viable?


Why cannot MLE be implemented for Gaussian mixture model directly?

Question: Consider the following density, the mixture of two Gaussian distributions,
\begin{align*}
p(x)= p(k=1) N(x|\mu_1,\sigma^2_1) + p(k=0) N(x|\mu_0,\sigma^2_0) ,
\end{align*}
where $p(k=1)+p(k=0)=\pi_1+\pi_0=1$ and $N(x|\mu,\sigma^2)$ is the density of Gaussian distribution with mean $\mu$ and variance $\sigma^2$.
Parameters of interests are $\pi_0$, $\mu_i$'s and $\sigma^2_i$'s.
This Q & A shows the MLE for the mixture of two Gaussian distributions when the latent variables $K_i$'s are observed.
In this question, suppose we only observe $X_i$'s, and the latent variables $K_i$'s are unobserved.
Classical methods for estimation of these $5$ unknown parameters are EM-algorithm and MCMC sampling, see Hastie et. al. (2009) for details.
Why cannot MLE be implemented for Gaussian mixture model directly?

(Some attempt)
The log-likelihood would be
\begin{align*}
\ln P(x|\theta) = \sum_{i=1}^n \bigg[ (1-k_i) (\ln \pi_0 + \ln N(x_i|\mu_0,\sigma_0^2))+k_i(\ln \pi_1 + \ln N(x_i|\mu_1,\sigma_1^2)) \bigg].
\end{align*}
Comment: There is no closed form solution for the MLE. This means that the loglikelihood needs to be maximised numerically. This is what EM in fact does. One can use alternative numerical approaches, but they are not necessarily better, and don't necessarily deserve the description "directly" either..
Comment: For simple problems, maximizing the full log-likelihood you give here numerically works fine. (So the short answer to "Why cannot ..." is "It can.")
Comment: The real problem is that the likelihood blows up whenever one of the $\mu_i$ coincides with a data value and the corresponding $\sigma_i$ shrinks to zero.  This gives multiple global maxima, all of which are usually considered unrealistic.
Comment: I agree with Ben on this. It is not the end of the world. Especially with a reasonably large sample and some regularisation, it is doable.
Answer: As @ChristianHenning has pointed out in the comments, the mixing of components makes likelihood analytically intractable. On the other hand, Bayesian methods are not applicable due to the combinatorial explosion of the terms in the expanded likelihood. See, e.g., the discussion and references in these notes. Furthermore, the multimodal nature of the likelihood makes it difficult to use direct numerical maximization or some simpler Monte Carlo algorithms, such as Gibbs sampling or Metropolis-Hastings.


Google Maps Using Fragments

Question: I'm using google maps in fragments(Navigation Drawer). When the application starts the first fragment is shown with google maps. I've initialized the google maps in onViewCreated method. First time it shows the google maps perfectly fine with my location but when I select another fragment and come back to this fragment it throws the null pointer exception.
Exception is thrown here in the code:
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

Method:
private void moveCamera(LatLng latLng, float zoom, String title) {
    Log.d(TAG, "moveCamera:  moving the camera to:   " + latLng.latitude + " lon " + latLng.longitude);

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}

OnViewCreated Method:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    getLocation();

    mapView =  view.findViewById(R.id.map);
    mapView.onCreate(savedInstanceState);
    mapView.onResume();
    mapView.getMapAsync(this);
}

OnMapReady method:
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMyLocationEnabled(true);
    init();
}

private void getLocation() {
    Log.d(TAG, "getDeviceLocation: getting the current device's location");
    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());

    try {
        if (mLocationGranted) {

            Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {

                    if (task.isSuccessful()) {
                        Log.d(TAG, "device location found");
                        currentLocation = (Location) task.getResult();
                        moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM, "My Location");
                    } else {
                        Log.d(TAG, "onComplete:  current location is null");
                        Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();
                        getLocationPermissions();

                    }
                }
            });
        }

    } catch (SecurityException e) {
        Log.e(TAG, "SecurityException :  " + e.getMessage());
    }

}

Error
Exception: java.lang.NullPointerException: Attempt to invoke virtual method
void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.map.CameraUpdate)
on a null object reference`

Comment: where are you calling the your method moveCamera()?
Comment: Inside the getLocation method
Comment: I've updated the code. Kindly take a look
Answer: You are getting a NullPointerException because your map is not ready when you are trying to move its camera.
You can try to do the following
@Override
public void onMapReady(GoogleMap googleMap) {

  mMap = googleMap;
  mMap.setMyLocationEnabled(true);
  init();

  getLocation();

}

by doing that, your code will just attempt to move the maps camera when the map is available or change your code logic and remove your moveCamere() from the getLocation() method and for example put it in onResume()

Google Maps Using Fragments


Babel 7 fails with single plugin saying "Duplicate plugin/preset detected."

Question: The plugin that fails is @babel/plugin-transform-regenerator (no marginal plugin, 1.6 milion downloads / week).
This is my entire .babelrc:
{
  "presets": [],
  "plugins": [
    "@babel/plugin-transform-regenerator"
  ]
}

When I try to transpile it with parcel using parcel build source/main/index.html --no-source-maps --out-dir build I get the following error:
/path/to/index.js: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.

plugins: [
  ['some-plugin', {}],
  ['some-plugin', {}, 'some unique name'],
]

at assertNoDuplicates (/.../node_modules/@babel/core/lib/config/config-descriptors.js:205:13)
at createDescriptors (/.../node_modules/@babel/core/lib/config/config-descriptors.js:114:3)
at createPluginDescriptors (/.../node_modules/@babel/core/lib/config/config-descriptors.js:105:10)
at alias (/.../node_modules/@babel/core/lib/config/config-descriptors.js:63:49)
at cachedFunction (/.../node_modules/@babel/core/lib/config/caching.js:33:19)
at plugins.plugins (/.../node_modules/@babel/core/lib/config/config-descriptors.js:28:77)
at mergeChainOpts (/.../node_modules/@babel/core/lib/config/config-chain.js:314:26)
at /.../node_modules/@babel/core/lib/config/config-chain.js:278:7
at buildRootChain (/.../node_modules/@babel/core/lib/config/config-chain.js:68:29)
at loadPrivatePartialConfig (/.../node_modules/@babel/core/lib/config/partial.js:85:55)

Here are my versions from package.json:
"@babel/core": "^7.1.2",
"@babel/plugin-transform-regenerator": "^7.0.0",

Any ideas?
Comment: I've never worked with any of this, but judging from the example given, you could try fixing it with `"plugins": ["@babel/plugin-transform-regenerator", {}]`. Though I highly doubt that will matter. A workaround might be to use `"plugins": ["@babel/plugin-transform-regenerator", {}, 'some-random-name']` so at least you're giving it a unique name.
Comment: From what I could find by doing a bit of research is that it might be possible that you have a couple of default plugins that are also used internally by this plugin. That causes the error mentioned.
Comment: @icecub That will probably work but it is really strange that something like this even happens... Where is the duplicated plugin comming from?
Comment: @icecub Please make it an answer so that I can accept it for everybody else on the web to have a reference.
Answer: This is a babel error basically saying that you have defined your plugin @babel/plugin-transform-regenerator twice - more or less indirectly.
Parcel Bundler transpiles your code by default with the Babel preset @babel/preset-env. These presets in general are just shareable list of plugins. As you can see here, preset-env already includes "@babel/plugin-transform-regenerator" in Babel 7.
Simple solution: just delete "@babel/plugin-transform-regenerator" from your plugins config in .babelrc.
PS: had a similar experience, after migrating from version 6 to 7. My old config looked like this (valid in Babel 6)
  "plugins": [
    "react-hot-loader/babel",
    "transform-object-rest-spread",
    "transform-class-properties",
    "transform-runtime",
    "transform-async-generator-functions",
    "transform-async-to-generator"
  ],
  "presets": ["env", "react"]

I had to remove plugins transform-object-rest-spread, transform-async-generator-functions and transform-async-to-generator, which - as said - are included in env (here explicitely specified).
Babel offers a fantastic upgrade tool called babel-upgrade (surprise, surprise), that did get the job done well to rename the plugins, but unfortunately it left my alone with these "duplicates".
Hope, that helps.
Answer: After doing some research, the most likely cause of the error mentioned is that you have one or more default plugins that are also used internally by this plugin.
The easiest way to solve the issue is to do what the error tells you: Add a unique name to the plugin like that:
"plugins": [
    ["@babel/plugin-transform-regenerator", {}, 'unique-name']
]

Answer: I faced the same problems today.
My way to solve this :
{
"presets": [
   "@babel/preset-env",
   "@babel/preset-react"
],
"plugins": [
    "transform-object-rest-spread",
    "transform-class-properties"
]
}

Answer: Just remove "@babel/plugin-transform-regenerator" from
"plugins": [
    "@babel/plugin-transform-regenerator"
]

Answer: I faced the same problem but with another plugin and I think they're both the same.
My plugin:
@babel/plugin-proposal-object-rest-spread

Finally I noticed that there is a plugin in both devDependencies in package.json and plugins in webpack.config.js. I got rid of the one in the webpack file and it worked well.
However your problem is with .babelrc and package.json. I think it'll fix if you do the same as me. You don't have to bring the same plugin in both file at the same time.


Which note is consonance and which is dissonance

Question: 1) I did some reading saying 2nd, 4th, 6th and 7th note are unstable note. where 7th note tends to move towards the tonic and it is the most unstable note. Is it true? When I play through the scale, i can hear that these notes tends toward something but I am not sure that I am hearing the right thing.
2) A chord or inteval written in Augmented and diminished are also unstable. Am I right ?
Comment: Downvoters should state the problem with the question, and provide suggestions on how to fix it.
Comment: Consonance and dissonance are much easier to understand if you play chords.  1 & 2 together, for example, is quite dissonant, and 1 & 5 together is very consonant.
Answer: The answers to both of these questions depends strongly on context. Obviously, any single note played in isolation won't sound functionally different from any other note played in isolation, so in order to give it functional meaning (as a 2nd or 5th or what have you) you need to play it in the context of a key.
Consider that we're in the key of C major. The tonic chord of that key is C-E-G. If you were to play that chord and sustain it with your left hand on a piano, and then improvise a melody on the other notes in the key of C major with your right hand (white keys), you would hear that it makes the most sense to come to a resting point in your melody on one of the same notes in the chord; namely, the root, 3rd, and 5th.
All of the other notes in the key (the 2nd, 4th, 6th, and 7th) will never resolved to in the context of "common practice" harmony. Each note has a different direction it tends to resolve. I am alluding to the practice of tension vs. resolution in common practice harmony--you build tension by using "unstable" notes and chords, and then resolve them in an artful way to a "stable" chord. The 7th, for example, likes to resolve up by a half step to the root. The 4th likes to resolve down by half step to the 3rd.
To address the 2nd part of your question, major and minor chords and intervals are the most stable, and something given the name augmented or diminished, as a result, implies an amount of instability in whatever context you're in. Usually, this also implies notes outside of those diatonic to the key (chromatic notes).
This answer is a pretty vast simplification over the complication and nuance that is involved in common practice harmony, but a full overview is too general for StackExchange. A good starting place is the Wikipedia article on Diatonic Function and related articles.
Comment: @Simon Beethoven's deafness has nothing to do with your ability to write melodic phrases. What is it you are actually trying to accomplish?
Comment: I wondering the Master Beethoven. He got deaf later in his life right. How does he able to compose a master piece that can avoid having funny section. I know it is a funny question. Because when i do a theory work that asking me to write a second or third phrase but i always ending up with strange melody that was not quite right.
Comment: Do you have any other link that is easy to understand? sorry I am a good musical person.
Answer: It depends on the style of music.  In modern jazz and blues, a dominant 7th chord can be an ending chord.  So can a major 7th chord like C - E - G - B.  Listen to the ending of "Le Boeuf sur le Toit" by Darius Milhaud.


$F$ fixed ultra filter $\Rightarrow$ $F=F_{\{x\}} = \{U \subset X | \{x\} \subset U \}$

Question: $F$ fixed ultra filter $\Rightarrow$ $F=F_{\{x\}} = \{U \subset X \mid \{x\} \subset U \}$
This is what I have come up with
Assume $F \not = F_{\{x\}} \Rightarrow \exists U \in F : \{x\} \not \in F$. Since $F$ is fixed $\exists y \in \cap_{f \in F} \ f : y \not = x$. I would like to claim that this contradicts the assumption that $F$ is ultra filter, can I do that?
A fixed filter is one that is not free, and a filter $F$ is free if $\cap_{f \in F} f = \emptyset$
Comment: ???? *By definition* a fixed (ultra)filter has the form $F_{\{x\}} = \{U \subset X \mid \{x\} \subset U \}$ Are you trying to prove that a fixed filter is an ultrafilter?
Comment: See my edit. @hardmath
Comment: I'm not quite sure, but it seems you are claiming that any ultrafilter is a *principal* ultrafilter. This is not generally true.
Comment: No, any **fixed** ultra filer. @hardmath
Comment: We defined a fixed filter to be a filter that is not free, and an ultra filter is a filter that is maximal. @Martín-BlasPérezPinilla
Comment: The only use of "fixed" ultrafilter I've seen makes it a synonym of principal ultrafilter.  See this [Wikipedia article](https://en.wikipedia.org/wiki/Ultrafilter).   Given that your definition is different (I don't know what makes a filter "not free"), you should give the details in the body of your Question.
Answer: A fixed ultrafilter has $\bigcap \mathcal{F} \neq \emptyset$. Let $a$ be a point in it.
Then $\mathcal{F} \cup \{a\}$ is a filter base (as it has the finite intersection property, because $a \in F$ for all members of $\mathcal{F}$).
So this generates a filter $\mathcal{F}'$ which then contains $\mathcal{F}$ so must equal $\mathcal{F}$ by maximality of $\mathcal{F}$.
So $\{a\} \in \mathcal{F}$. But then the enlargement axiom
tells us that $F_a \subseteq \mathcal{F}$. The reverse is true as all members of $\mathcal{F}$ contain $a$.
Comment: Enlargement axiom?
Comment: @Olba12 if a filter contains a set, it also contains all larger sets (supersets). There is also the finite intersection axiom, and not having $\emptyset$ in it, or equivalently $\mathcal{F} \neq \mathcal{P}(X)$. (being proper).
Comment: Ah yes, was not familiar with the name though.


How to update Microsoft Teams manifest of the bot for all users?

Question: I'm trying to allow the users that are already talking to the bot upload files (attaching the files to the bot).
I uploaded a manifest with "supportsFiles": true through "Upload Custom App".
But this only affects my conversation with the bot, the other users' manifest doesn't look like its updated because they can't see the attachment button.
Is there a way to update the bot's manifest for all the users in the organization?
This is not a published application, the users talk to the bot through the link from the registered bot in Azure Portal.
Any help is appreciate.
Thanks!
Answer: The Bots which are accessed via link won't update as there is no metadata associated with it. You need to create App Manifest for you Microsoft Teams.
Once you've created your app there are three options for distributing it.

Upload your app directly.
Publish your app to your organization's app catalog
Publish your app through AppSource

Please go through the options provided in the documentation and let us know if you need any help.
Comment: Thanks alot, I didn't know that there was no metadata associated and I thought that it was the same bot/manifest. Just confirmed that if it's an administrator that registers the app, it works for all the user.


How can I make Plupload in D7 start uploading automatically?

Question: I'm using the Plupload integration module and the problem is that once the users select the files, they think that they have already uploaded the files. No matter how obvious, bold and huge you make that "Start upload" button, most of them just ignore it. Plus it is not a good user experience.
What I need is for the "Start upload" button to disappear and the upload of the files into Plupload should begin automatically as soon as the files are selected. Would someone be kind enough to suggest how can this be done?
Answer: As given in the readme file of this module add following autoupload property to your form element as shown below.
<code>$form['my_element'] = array(
  '#type' => 'plupload',
  '#title' => t('Upload files'),
  '#description' => t('This multi-upload widget uses Plupload library.'),
  '#autoupload' => TRUE,
);
</code>
I have tried it and in works fine.


CSS Mobile-compatible Theme for Drupal?

Question: Are there any CSS Mobile-compatible Theme for Drupal?
Example of a CSS mobile-compatible site: http://framelessgrid.com/
Comment: Found the solution via `Kenn_VM` on IRC.

The keyword I need to search for in the Drupal themes repository is **responsive**
Answer: "Responsive", as mentioned in your comment, is indeed the buzzword. On a small scale, I have had success using Sky to create a mobile friendly site.
Comment: Thanks, but I am a little skeptical at those HTML5+CSS3 themes.. created a separate question for addressing this skepticism: [Should I steer clear of CSS3 and HTML5?](http://programmers.stackexchange.com/questions/128245/)

CSS Mobile-compatible Theme for Drupal?


What does the "bonus" tag over the score in NBA games means?

Question: Sometimes, while watching a NBA game, I see a "bonus" tag text over the telecast scoreboard.
What does it means? Which rule or set of rules influence this?
Comment: The *question* is the same. Maybe it needs a better answer, but that's not a reason for having a new question.
Comment: Sorry for the duplicate question, the title on the original question doesn't make it easier to find too.
Comment: the "duplicate" answer is related to college basketball only, not NBA.
Comment: That's true. Your question will help with that in the future.
Answer: The "bonus" tag occurs when one team accumulates a limited number of fouls.
Each subsequent foul results in free throws.
Please see a wikipedia article here for more details.


Listas ligadas - Adicionar ao final da lista

Question: Boas.
Estou com o seguinte problema, fiz um pequeno programa para testes, onde crio uma lista com os dados de um cliente, nome e número, mas estou com problemas em adicionar ao final da lista. Se tentar adicionar ao início, não tenho qualquer problema, mas quando tento adicionar ao final surge o erro se "segmentation fault", no fundo adiciona o primeiro e depois para.
Deixo de seguida o código:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct cliente
{
    char nome[40];
    int nr_cliente;
}cliente_t;

/*Criação do conceito de nó e respetivo método de remoção*/

typedef struct node
{
    cliente_t cliente;
    struct node* proximo; /*Apontador para o próximo nó*/
}node_c;

node_c* criar_no()
{
    node_c* node = NULL;
    node = (node_c*)malloc(sizeof(node_c));
    node->proximo = NULL;
    return node;
}

void remover_no(node_c* node)
{
    if (node)
    {
        free(node);
    }
}

/*Criação do conceito de lista e respetivo método de insersão,remoção e pesquisa*/

typedef struct list
{
    node_c* head; /*Apontador para a cabeça da lista*/
}list_c;

list_c* criar_lista()
{
    list_c* list;
    list = (list_c*)malloc(sizeof(list_c));
    list->head = NULL;
    return (list);
}

list_c* remover_lista(list_c* list)
{
    if (list->head == NULL)
    {
        free(list);
        list = NULL;
    }
    return (list); /*retorna nulo*/
}

void insere_lista_topo(list_c* list, node_c* node)
{
    if (list->head != NULL)
    {
        node->proximo = list->head;
    }
    list->head = node;
}

void insere_lista_fim(list_c* list, node_c* node)
{
    node_c* node_aux = list->head;

    if (node_aux == NULL)
    {
        insere_lista_topo(list, node);
    }
    else
    {
        while (node_aux)
        {
            node_aux = node_aux->proximo;
        }
        node_aux = node;
        node->proximo = NULL;
    }
}

node_c* pesquisar_lista(list_c* list, int nr_cliente)
{
    node_c* node = list->head;
    int aux = 0;

    while (node)
    {
        if (aux == nr_cliente)
        {
            break;
        }
        else
        {
            aux++;
            node = node->proximo;
        }
    }
    return (node);
}

int main()
{
    node_c* node;
    list_c* list;
    int i;

    list = criar_lista();

    for (i = 0; i < 5; i++)
    {
        node = criar_no();
        strcpy(node->cliente.nome, "Ze Manel");
        node->cliente.nr_cliente = i;
        node->proximo = NULL;
        insere_lista_fim(list, node);
    }

    for (i = 0; i < 5; i++)
    {
        node = pesquisar_lista(list, i);
        printf("Nome: %s\n", node->cliente.nome);
        printf("Nr Cliente: %d\n", node->cliente.nr_cliente);
    }
}

Comment: A lógica está errada. Só funciona para a lista vazia. Se a lista não está vazia precisa fazer com que o último aponte para o novo e o novo para NULL...
Comment: o ultimo node é NULL, fim da lista, percorrendo a lista  verifica se a ultima posição é **NULL** constatando que é verdadeira o proximo aponta para novo valor `proximo=NovoValor`.. ultima posição preenchida.
Answer: A lógica está errada. Assim só funciona para a lista vazia, o caso trivial. Se a lista não está vazia precisa fazer com que o último elemento aponte para o novo e o novo para NULL...
void insere_lista_fim(list_c* list, node_c* node)
{
    node_c* node_aux = list->head;

    if (node_aux == NULL) { insere_lista_topo(list, node); }
    else
    {
        while (node_aux) { node_aux = node_aux->proximo; }
        node_aux      = node;
        node->proximo = NULL;
    }
}

Não precisa de chaves num while() de 1 comando.
não precisa do else numa condição definitiva. Simplesmente retorne
talvez não devesse usar nomes tão grandes para um ponteiro auxiliar que só vai existir no loop

Estaria melhor com algo assim:
void insere_lista_fim(list_c* list, node_c* node)
{
    node_c* p = list->head;
    if (p == NULL)
    {
        insere_lista_topo(list, node);
        return;
    }
    while (p->proximo != NULL)  p = p->proximo;
    p->proximo      = node;
}

que funciona.
Em main isso também não está bom
    for (i = 0; i < 5; i++)
    {
        node = criar_no();
        strcpy(node->cliente.nome, "Ze Manel");
        node->cliente.nr_cliente = i;
        node->proximo            = NULL;
        insere_lista_fim(list, node);
    }

Nunca deixe uma variável com um nome ingênuo como i global em main ou qualquer função.
Se está gerando dados use algo auditável ao máximo. Usar o mesmo nome porque?

Prefira algo como
    for (int i = 1; i <= 5; i++)
    {
        node = criar_no();
        sprintf(node->cliente.nome, "Ze Mane %d", i);
        node->cliente.nr_cliente = i;
        node->proximo            = NULL;
        insere_lista_fim(list, node);
    }

E seu programa mostraria
Nome: Ze Mane 1
Nr Cliente: 1
Nome: Ze Mane 2
Nr Cliente: 2
Nome: Ze Mane 3
Nr Cliente: 3
Nome: Ze Mane 4
Nr Cliente: 4
Nome: Ze Mane 5
Nr Cliente: 5

Tem ainda muitos problemas no código.
Comment: Ah o SO-pt. Então minha resposta é inútil segundo ao menos 2 atentos leitores. Apesar de mostrar o que está errado. E explicar porque. E ter um exemplo em C de como poderia ser. E a saída do exemplo corrigido. Tenho mesmo que melhorar! :D


Pagination in Panelizer drupal

Question: I'm using panels and panelizer. I created a custom content in panelizer where I can upload a file. When I render the results, I have a lot of items. Now I want to paginate them.
How can I add the pagination in panelizer or use a view in panelizer?
Answer: Pagerer

Features:

multi-pane pager
Views pager plugin
control whether to display links to pages, to items, or to item ranges
direct input of the page to go to through an input widget
selection of the page to go to through a jQuery UI slider
selection of the page to go to through a client-side scrolling pager
links to progressively more distant pages (like +10, + 20, +100, +200)
adaptive logic links
specify text to be used to render page separators (like a vertical bar) and page breakers (like an ellipsis)
supports Views' AJAX enabled pager
Comment: And how does it answers the question? There is no mention of it working with panels or panelizer in piece you quoted. If you just *know* it works, write a paragraph or two about that.
Comment: multi-pane pager,Views pager plugin using this you do it

Pagination in Panelizer drupal


Display a certain page in a view

Question: Here is what I'm trying to do is display a certain page in a view instead of all of the basic pages.
How would I go about doing that?
Comment: Add contextual filter `Nid`. Select provide default value and then select fixed value and type in the node id #.
Answer: If you want to change what is shown on the site front page you can do that under Configure > System > Site information.
Enter node/[number] into the Default front page field (replace the [number] with the node ID of the content you want to appear on the front page).

If you want to change Content Views to show only a particular node add the Filter Content: Nid with the Operator set to Is equal to and enter your node ID number in the Value field.
This will show only the one node information on that Views.

Display a certain page in a view


What is meta name="omni_page"?

Question: What is <meta name="omni_page" />?  I only see it on Apple.com pages, and it doesn't look like anything I've seen in the standards.
Answer: I believe this is used by the Omniture web analytics software.  http://www.omniture.com/
Comment: Interesting, Abode acquired Omniture (http://www.omniture.com/en/company/adobe_faq) so Apple is feeding analytical data to Adobe.
Comment: Oddly, the Omniture site doesn't use the tags, but this guess would make the most sense.
Answer: The META tag and NAME attribute are part of the w3c spec, see: Specifying meta data.
It does seem a bit strange that the meta data only includes a name, though.
Comment: Actually it's different on each page, and they seem to include values.  The front page has  , /mac/ has  , etc.
Answer: From my search, I got this (for iPod Touch).
<meta name="omni_page" content="iPod touch - Index" />

"omni_page" basically suggest that the developer using a product from The Omni Group
Their website suggests,

The Omni Group is an elite team of
  special forces who develop
  productivity applications exclusively
  for Mac OS X and iPhone.  We're known
  for our awesome software,
  gold-standard customer support, and
  palpable geekery.

They also have a product called OmniAppKit which is an extension to Apple's AppKit.framework.
I think it's Omni Content generation which basically generates a meta tag for their pages for easy debugging purposes (or am I wrong?)
Comment: Could also be about Nuance's OmniPage OCR: http://www.nuance.com/imaging/products/omnipage.asp
Comment: You're the one assuming that the iPhone has something to do with it.
Comment: @Andrew Moore, my example has an example of the iPod Touch (and not iPhone) so I was wondering if the product works for iPod Touch (sorry, not iPhone).
Answer: Lower in the code, there's a line that points directly to Omniture.

What is meta name="omni_page"?


Incrementar valores em objetos

Question: let items = [
  { prod: '', qty: 50, vUnit: 5 },
  { prod: '', qty: 10, vUnit: 20 },
  { prod: '', qty: 5, vUnit: 10 },
];
let mail = [
  { name: 'Joãozinho', email: 'email@example.com', value: null },
  { name: 'Mariazinha', email: 'email@example.com', value: null },
  { name: 'Lindomar', email: 'email@example.com', value: null },
];
let addQty = () => {
  let total = items.reduce(function getTotal(total, item) {
    return total + item.qty * item.vUnit;
  }, 0);
  return total;
};
let mailDelivery = () => {
  mail.forEach(({ email, value }) => {
    console.log(
      email +
        ' deve pagar ' +
        Intl.NumberFormat('pt-br', {
          style: 'currency',
          currency: 'BRL',
        }).format(value / 100),
    );
  });
};
function sharedValue() {
  clients = mail.length;
  let total = addQty();
  let shared = total / clients;
  mail.map((x) => {
    x.value = parseInt(shared);
  });
  if (total === parseInt(shared) * clients) {
    return mailDelivery();
  } else {
    diff = total - parseInt(shared) * clients;
    //Aqui não faço ideia de como continuar

    return mailDelivery();
  }
}
sharedValue();

Tenho os dois objetos e tenho as seguintes situações:

calcular a soma dos valores, ou seja, multiplicar o preço de cada item por sua quantidade e somar todos os itens
Dividir o valor de forma igual entre a quantidade de e-mails

Só que entra o seguinte ponto:

Quando fizer a divisão, é importante que não falte nenhum centavo! Por exemplo, um valor total de R$ 1,00 para ser dividido entre 3 e-mails. Isso daria uma dízima infinita. No entanto, o correto aqui é que duas pessoas fiquem com o valor 0,33 e a terceira fique com 0,34.

Minha ideia foi, retornar a diferença entre o valor total e a soma dos valores divididos entre os clientes, porém, não faço a minima ideia de como poderia estar incrementando esse valor em "mail.value" e subtraindo da diferença obtida...
Comment: Não sei se isto responde à seu pergunta mas pode adicionar a diferença, por exemplo, ao último: `mail[mail.length - 1].value += diff;`.
Comment: Pensei em algo assim também meu mano, só que tipo, quando entra naquele ponto de "No entanto, o correto aqui é que duas pessoas fiquem com o valor 0,33 e a terceira fique com 0,34.", no código que montei a diff seria igual a 2, nisso teria que dividir igualitariamente esses 2 sendo 1 para o indice 0 e 1 para o indice 1 da array
Comment: Veja a minha resposta abaixo.
Answer: Pode fazer um pequeno loop e distribuir o valor de diff. Qualquer coisa como:
for (var i = 1; i <= diff; i++) {
  mail[mail.length - i].value ++;
}

Comment: MANO DO CÉU, salvou lindamente, fiquei pensando em mil modos mas era só ir no básico mesmo kkkkkkkkkk

Incrementar valores em objetos


The Calendar module doesn't recognize fields

Question: I created a content type "events", with a date field and other normal settings.
I am trying to use the Calendar module to create a calendar on my Drupal site, but I am facing an issue.
When I try to edit the basic calendar, and change its argument from date:node (node updated time), then in the list of date_fields it does not show the field that I had created above. It only shows the following fields:

Node: Last comment time
Node: Post date
Node: Updated date
User: Created date
User: Last access
User: Last login

I have tried this again and again by recreating my content type, or by disabling/enabling the Calendar module, but it does not seem to work. I am using Date 7.2.x and Calendar 7.2.x.
Comment: I guess you mean that Views doesn't list the field you created in the list of the view arguments. Drupal 7 fields are not CCK fields; Drupal 7 has its own field API, which doesn't require CCK at all. Also, what you call "cck" is a content type.
Comment: oh sorry..i meant content type...
Comment: There is nothing to be sorry. Using the wrong term confuses who reads the question, especially if the question is about Drupal 7, and you make references to CCK. Somebody could wonder if the question is really for Drupal 7, or for Drupal 6.
Answer: I installed Calendar 7.x-2.x-dev, Date 7.x-2.x-dev, and Views 7.x-3.x-dev; then I created a "Test" content type to which I added a date field ("Start date").
When I edited the Calendar view, and added a new argument for the view (view arguments are called "contextual filters," in Views 7.x-3.x-dev), I followed the following steps:

I filtered out the list of arguments to show only the ones defined from the Date module; between the two argument types, I selected "Date: Date (node)."
On the settings page that Views shows after I selected the argument type, I selected the date field I added to my content type.

If you select "Date: Date (users)," then you will see all the date fields that are associated with users, as in the following screenshot.

Still, the field I added to my content type is visible in the list of fields shown in the settings page for the view argument.
The issue you are seeing is probably caused by compatibily problems between Date, and Views. I would try using Views 7.x-3.x-dev.
Comment: i should upgrade my views module. that would help i guess.
Comment: suppose i do upgrade my views version.Then all the previous views that are present on the site would still be functional?
Comment: @ayush All your views would still be functional. As usual, the suggestion is to first test a new module version on a test site where you enabled the same modules that are enabled in the production site. If you don't see any issues in the test site, then you can be sure the module will not cause any problem on the other site.


UWP sending message to Windows Service using NamedPipes

Question: I'm trying to create a UWP app for our tools, one of its functionality is to manage tfs outside visual studio using tf.exe console commands and other things, i noticed that UWP is sandboxed and only has limited access outside its deployment folder so im planning to use a windows service to be the one who will be doing all the heavy work and using NamedPipes to communicate between UWP and Windows Service, been searching a bit already but until now im still not able to establish connection between this 2 app
I'm using console as a sample and starting it from UWP using FullTrustProcessLuncher
I uploaded a sample project in github
https://github.com/vgdagpin/UWP2WindowsService
Any help would be appreciated
Answer: I don't know much about named pipes so I can't tell if that is correct. But generally, UWP apps use APP services to communicate with desktop apps because the app service is native UWP.
I'd suggest you take a look at @Stefan Wick's Blog - UWP with Desktop Extension Part 1,2,3. You could search for them in your browser. These tutorials show the way how to package desktop apps with UWP apps using Windows Application Packaging Project and how to establish communication between the UWP app and the console app using App service which should be what exactly you want. After you launched the console app from the UWP app, you could let the console app call the windows service to do what you need.
Comment: @VincentDagpin Based on the document: [AppServiceConnectionStatus Enum](https://learn.microsoft.com/en-us/uwp/api/windows.applicationmodel.appservice.appserviceconnectionstatus?view=winrt-22000), `AppServiceUnavailable` means the app service and the version of the app are correct. Maybe you could try the sample code from the Blog first, then replace the desktop app with the console app you are using.
Comment: @VincentDagpin Do you mean even the sample form the blog does not work?
Comment: Thanks, yeah I tried AppServiceConnection now, since I used NetCore 5.0 I referenced nuget package Microsoft.Windows.CsWinRT, my new challenge now is I keep on getting AppServiceUnavailable
Comment: Already done that and no luck :), i updated my github repo with the recent example, will try again another later
Comment: I got it working now, I just need to separate my background task in separate project (Windows Runtime Component)

I updated github repo for reference


Prove that the set of all algebraic numbers is countable.

Question: I'm a student in Korea.
If I make a mistake in grammar, please indicate.
Recently, I'm studying the book 'Principles of Mathematical Analysis'
So, I tried to solve the exercise #2 in chapter 2.
'A complex number $z$ is said to be algebraic if there are integer $a_0, \dots, a_n$ ,not all zero, such that  $a_0 z^n + a_1 z^{n-1} + \dots + a_n =0$ '
The hint is 'For every positive integer $N$ there are only finitely many equation with $n+|a_0|+...+|a_n|=N$'
Of course, I have searched this exercise on this site. But there were different methods.
I want to prove this exercise by using the hint. please help me.
Comment: Countable union of countable sets is countable
Comment: If you show the hint is true, then the set of all such polynomials $S_N$ is finite, and each polynomial having at most $n$ roots. The number of roots contributed cannot exceed $n|S_N|$. Then the countable union of finite sets is countable.
Comment: Dupe http://math.stackexchange.com/questions/50655/proving-the-countability-of-algebraic-numbers
Comment: the general intuition is that any set of elements which can all be  finitely described is countable. For algebraic numbers you can always describe any of them as "the nth root of this equation", for instance with lexicographic order on coordinates.
Answer: For every nonnegative integer $N$, define the set of polynomials
$$P_N:=\{(a_nz^n+\dots+a_1z+a_0) \,\mid\, n+|a_0|+\dots+|a_n|=N\}\,.$$
The hint says that $P_N$ is finite.
Now, each polynomial has finite number of roots (counting with multiplicity, a polynomial $f$ has exactly $\deg(f)$ roots in $\Bbb C$).
Let $R_N$ be the set of all roots of polynomials in $P_N$:
$$R_N:=\{\alpha\in\Bbb C\,\mid\,\exists f\in P_N\,:\,f(\alpha)=0\}\,.$$
So, $R_N$ is still finite.
Finally $\{$algebraic numbers$\}\ =\ \bigcup_{N\ge 0}R_N$.
Comment: What is the importance of fixing $a+|a_0|+\cdots+|a_n|=N$?
Answer: We define a height $h$ of a polynomial $a_0+a_1x+\cdots a_nx^n\in\mathbb{Z}[x]$ as $h=n+\sum_{i=0}^n|a_i|$.
Clearly for a fixed $h$ there are only finitely many choices for $n$ and $a_i$ and so there are only finitely many polynomials of fixed height.
Now we make a list of all the algebraic numbers in the following way: Consider any height $h\in\mathbb{N}$ and for all the finitely many polynomials of this height(here we use the hint), write down all the finitely many roots of these polynomials in the list. Keep repeating for all possible heights. It is clear that no algebraic number will be missed out in this list. This proves that the algebraic numbers are countable.


Error 1385 when executing RUNAS on Windows Enterprise 7

Question: I am having trouble installing an application on a Windows 7 Enterprise computer. The installer creates a user under which a service process will run. However I get the code error 1385 all over my logs (installer and installed service). I managed to isolate the problem in such environment. I can reproduce it easily doing:
runas /env /user:thehostname\thejustcreatedusername

then the thejustcreatedusername password is asked, and as result I get:
Erreur de RUNAS : Impossible d'exécuter - notepad
1385 - Échec d'ouverture de session : l'utilisateur ne bénéficie pas du type d'ouverture de session demandé sur cet ordinateur.

I think it corresponds to the English version: Logon failure: the user has not been granted the requested logon type at this computer.
In the internet I found that I should grant the user the access this computer from network right. I did it following the steps at https://technet.microsoft.com/en-us/library/dd277404.aspx, through the Local Security Policy tool, but no success (still same 1385 error). I also added my user to the Users group that has that right already granted but no success. However if I add that user to the Administrators group, the RUNAS command works and I see a notepad being launched.
What setting should I change in such user to run that impersonation command successfully?
Answer: Indeed Jon, granting that right and also Allow log on locally did the trick.
There is an explanation on the reason why the installer worked on some environments and failed in some other ones. It worked correctly on environments whose Users group had been granted these rights (which is by default I think), and hence the new user inherited such permissions, leading to a non failure situation.
However in the non-working environment, the Users group had not been granted such right, and hence the newly created user did not inherit, and hence the 1385 error in both installation and during runtime.
Thanks!
Answer: You probably need logon as a service right.


Assign Public IP (not Elastic IP) after instance launched

Question: When I launch instance in AWS console I can set "Auto-assign Public IP" to true and newly created instance will be assigned with public IP address from pool.
Now assume I have launched instance with this setting set to false and want to assign public IP to this instance. The same public IP as in first case, not Elastic IP.
PS I know I can launch new instance and shut down old one. I'm particularly interested in assigning to one already running.
Answer: The instance that you launched without a public IP will stay without one as it is only assignable when you launch the instance.  Even having a subnet with auto assign public IP switched on will not assign a public IP to your instance if, when you launched the instance you chose not to have a public IP.
The only way I know is to select assign a public IP before launching the instance or having the subnet set up to auto assign public IPs which will do that only when you launch a new instance.
So to summarize:
It is not possible to assign a public IP after launching that instance unless you use EIPs.
Comment: Sorry for being emotional, Amazon sucks indeed with all these things you can't change afterwards. It's plain everywhere -- can't rename, can't remove, can't assign. Do they use their own system, anyway? :)
Comment: Now it is possible with AWS new dashboard. Nischal S answer works for me
Answer: To correct it afterwards, spin down your original server, spin up a new with auto assign public IP enabled and the existing volumes attached.
You can then discard the original instance.
Comment: "Launch more like this" eases duplication.
Comment: Thanks for the "launch more like this tip"! Note that it doesn't retain root volume sizes, though, so you'll have to set those again.
Comment: detach the original volume from the original instance and attach it to the newly-provisioned instance (detaching and deleting the volume you provisioned with it, I'd recommend the low default 8GB gp2 drive they suggest at the time of this writing).
Answer: If you are using ELB and Autoscaling, creating instance on fly and to stress test the instance is difficult. One solution during this scenario:
Select EC2 instance> Actions>Networking> Manage Ip Addresses.
Then use option "To add or edit an IPv4 public IP Allocate an Elastic IP to this instance or network interface".

Create an elastic IP
Navigate to Elastic IP address link> click Associate IP
Select the instance to associate IP and save.

Now you will have EC2 instance with public IP without restarting/deleting EC2 instance.
Comment: EIPs are only free while your instance is running.  If your instance is in the stopped state, they cost about the same hourly as running a tiny instance.
Comment: This works as long as you have available elastic IPs for the region (only 5 are typically available).
Comment: This is a soft limitation so it is possible to request additional elastic IPs for your account
Answer: Assuming your instance is running in a VPC you can create an Elastic Network Interfaces (ENI) that has a public IP assigned to it then associate that ENI with your instance without needs to create a new one.
Comment: But not as the primary interface.
Comment: Just tried your suggestion with no luck. When I create new ENI in the web console it doesn't have an option to enable "Public IP". The defaults from the VPC subnet are ignored as well. Any ideas?
Comment: If all you want to do is assign an public IP to the server you could use an EIP.  Create one through the GUI and then assign it to the server.  I may have misunderstood the original requirements with my original response.
Comment: Yes, I know that I can use EIP. But as I stated in question, I'm particularly interested in possibility to assign dynamic public IP. The same as I get, when check Auto-assign Public IP when launch new instance.
Answer: This was not possible back in 2016 but now of course AWS allows it:

Go to EC2 view from your console and click on Elastic IPs

Click associate ElasticIP

Find the EC2 instance that you would like
Comment: the title: Assign Public IP (not Elastic IP)
Answer: To assign a public IP to instance at run time:

Click on instance and select Networking-->Manage IP Addresses from action dropdown
Select Allocate elastic from "To add or edit an IPv4 public IP Allocate an Elastic IP to this instance or network interface." line then it will create a public IP for you
A window will appear asking to assign IP created in step 3 to instance and to private IP. Provide the required value.
Now try to ssh via putty. It worked for me. Hope it will help. Best of luck.
Comment: This doesn't answer the question, the OP specifically asked about assigning a NON-elastic public IP.
Comment: I know this is not the answer to the question, but it helps others "like me" to search for a solution on google. Thanks
Comment: @AndresFelipe I'm searching for a solution for the original question on google and your "not the answer" doesn't help me.


Degeneracy and Uniqueness in General LP

Question: This is about problem 4.12 from Bertsimas & Tsitsiklis's Introduction to Linear Optimization à la page 190. The problem is repeated below (bold is from errata).

Consider a general linear programming problem and suppose that we have a non-degenerate basic feasible solution to the primal in which all free variables are nonzero. Show that the complementary slackness conditions lead to a system of equations for the dual vector that has a unique solution.

From my understanding, a general LP primal-dual pair is as follows.
\begin{equation*}
   \begin{array}{cc}
    \begin{array}{rll}
     \text{minimize} & \textbf{c}^\top\textbf{x}&\\
     \text{subject to} & \textbf{a}_i^\top\textbf{x}\geqslant b_i,&i\in M_1\\
           & \textbf{a}_i^\top\textbf{x}\leqslant b_i,&i\in M_2\\
           & \textbf{a}_i^\top\textbf{x}= b_i,&i\in M_3\\
           & x_j\geqslant 0,&j\in N_1\\
           & x_j\leqslant 0,&j\in N_2\\
           & x_j~\text{free},&j\in N_3\\
    \end{array}
    &
    \begin{array}{rll}
     \text{maximize} & \textbf{p}^\top\textbf{b}\\
     \text{subject to} & p_i\geqslant 0,&i\in M_1\\
           & p_i\leqslant 0,&i\in M_2\\
           & p_i~\text{free},&i\in M_3\\
           & \textbf{p}^\top\textbf{A}_j\leqslant c_j,&j\in N_1\\
           & \textbf{p}^\top\textbf{A}_j\geqslant c_j,&j\in N_2\\
           & \textbf{p}^\top\textbf{A}_j= c_j,&j\in N_3\\
    \end{array}
    \\
   \end{array}
  \end{equation*}
A basic feasible solution $\mathbf{x}^*$ would imply that at such a point, there are exactly $n$ linearly independent active constraints. This does not say that $|M_3|=n$. There could be non-free variables that are $0$. However, this UCBerkeley solution claims so and the professor marked it correct. Could anyone explain why $|M_3|=n$ and why there cannot be any $x_i=0$ in this case?
Comment: I think the linked solution is wrong. Consider the LP in normal form $Ax=b, x\geq 0$ where $|M_3|<n$ (the usual case). In this setting BFS's can exist. (Also, since there a no free variables none of them are 0.)
Comment: @ericf both the linked solution and your comment are wrong (your comment is wrong because a bfs requires $n$ equality constraints (in normal form), with $n$ the dimension of $x$). Just put the problem in the question in normal form and re-read the given solution.
Comment: I'm not sure I completely understand your question, but in the solution that you linked the key step is the use of the complementary slackness conditions in the paragraph following the one you quoted which guarantee uniqueness.
Comment: @ericf, thanks for the quick response. Here is my clarification. The problem, as I understand it, wants us to show that there are $n$ linearly independent equations $c_j=\mathbf{p}'\mathbf{A}_j$ so that you can solve for a unique $\mathbf{p}$. Since this term only appears in the complementary slackness condition for the variables $x_j$, we have to show that all the $x_j$ are nonzero. This in turn replies on the claim that none of the "$n$ linearly independent active constraints" satisfied by the basic feasible solution is a sign constraint. The solution did so with $|M_3|=n$. Is that true?
Comment: I still think my answer is correct but perhaps I missing something. Either way the following link provides a nice clean discussion of the topic
Comment: Oops, here's the link https://www.google.com/url?sa=t&source=web&rct=j&url=http://www.wisdom.weizmann.ac.il/~robi/teaching/2012a-AdvancedAlgorithms/Lecture1.pdf&ved=2ahUKEwjHiI382I3eAhX7HzQIHVWUBfYQFjAAegQIABAB&usg=AOvVaw1Thw9yiZE1pQLgMwzSzMzw
Answer: The solution that you have linked is wrong. Notice that the book you are using explicitly gives a definition of what a general optimization problem looks like on page 42:
\begin{equation*}
\begin{array}{ll}
  \text{minimize}   \quad & \mathbf{c}^{\prime}\mathbf{x}\\
  \text{subject to} \quad & \mathbf{A}\mathbf{x} \geq \mathbf{b}
\end{array}
\end{equation*}
To answer your second question, we have $x_i \neq 0$ for all indices of $x$ (and not only for some subset of $\{1,\ldots,n\}$).
You can find a correct solution to this exercise here.

Degeneracy and Uniqueness in General LP


How do I move an element diagonally and after another animation in jQuery?

Question: I have an HTML/CSS element:

 BOX

#box {
      width: 100px;
      height: 200px;
      background-color: skyblue;
      position: absolute;
      left: 0px;
      top: 200px;
      text-align: center;
      font-family: Times New Roman;
}

I need it to move from its position in the middle of the page diagonally down and to the left (to the left corner). I've tried this:
$(function() {
            $("button").click(function() {
                $("#box").animate({
                    left: $(window).width() - 200
                    bottom: $(window).width() - 200
                }
        });
    });

How do I do this with jQuery and have it done after it's been on the page a few seconds (for a different animation to occur first)?
Comment: Better to use `top` instead of `bottom`.
Answer: Consider the following.

$(function() {
  $("button").click(function() {
    $("#box").animate({
      left: $(window).width() - 100,
      top: $(window).height() - 200
    });
  });
});
#box {
  width: 100px;
  height: 200px;
  background-color: skyblue;
  position: absolute;
  left: 0px;
  top: 40px;
  text-align: center;
  font-family: Times New Roman;
}

BOX

<button>Go</button>

You were using width property for both. You must use width and height. Also it's better to use top versus bottom in this case. You can use bottom, yet I would suggest something like:
bottom: $("#box").height()

In this way, the property of the top will be N Pixels from the "Bottom".
See More: https://www.w3schools.com/cssref/pr_pos_bottom.asp


Erro em sistema depois que subiu para servidor

Question: O sistema foi desenvolvido em php utilizando o framework codeigniter 3.
Funciona muito bem no localhost.
Subi para o servidor e começou a dar problemas. Verifiquei o php instalado e está na versão 5.6
Erros que acontecem:

Message: Object of class CI_DB_mysqli_result could not be converted to int
Filename: models/Usuarios_model.php
Line Number: 12
Message: Cannot modify header information - headers already sent by (output started at /home/user145/public_html/sistema/system/core/Exceptions.php:271)
Filename: helpers/url_helper.php
Line Number: 564

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Usuarios_model extends CI_Model {

public function login($username, $password) {
    $this->db->where("username", $username);
    $this->db->where("password", $password);

    $resultados = $this->db->get("usuarios");

    if ($resultados > 0) { ----------------------> LINHA 12
        return $resultados->row();
    }
    else {
        return false;
    }
}}

Quando volto em alguma página acontece este erro:

Severity: Warning
Message: unlink(/tmp/ci_session9c9ddb88511925d48aa2df5fd44857177296879f):   Operation not permitted
Filename: drivers/Session_files_driver.php
Line Number: 384
Backtrace:
File: >/home/user145/public_html/sistema/application/controllers/Dashboard.php
  Line: 7
  Function: __construct
File: /home/user145/public_html/sistema/index.php
  Line: 315
  Function: require_once

Após subir ao servidor, algumas páginas não estão sendo encontradas quando tento acessar.
Comment: @user102074 é dificil dizer se realmente no `localhost` está funcionando corretamente, porque, não temos como testar, agora eu indiquei o código errado que você está fazendo, porque, ali não retorna um inteiro, ali pode retornar `null` ou um `objeto` por isso eu disse tire `>0`! então você está programando errado, não me leve tão pouco mau ... é um indicação que falta estudar mais um pouquinho.
Comment: @user102074 ai é outro contexto, com certeza o teu código tem outros problemas!
Comment: Coloque o local do erro, os códigos referentes!
Comment: primeiro erro alguma $query tua que esta retornando uma int que não pode ser resolvido.

O segundo, essa exception é a codificação que tem que ser utf-8, mas tudo isso pode ser expeculação já que não contem um exemplo minimo verificavel, post seu codigo
Comment: ok, vou editar a pergunta
Comment: `if ($resultados) { .....` já assim resolve!
Comment: Agradeço. mas isso não é normal... no localhost fucniona e subo no servidor, não funciona
Comment: O erro foi corrigido, mas porque agora não funciona meu ajax? não encontra nenhuma página? é como se os links estivessem obsoletos
Comment: as minhs views não estão sendo encotnradas
Comment: @user102074 estranho mesmo, então, tem mais problemas de codificação.
Comment: `Operation not permitted` Provavelmente o seu `PHP` não tem permissão para escrita/remoção desse arquivo de sessão. Cheque as permissões. Há algum erro quando você tenta acessar suas `views`? Você está utilizando as mesmas configs (Apache/Nginx, PHP etc) do localhost no servidor??
Comment: Quando eu tento acessar as views, ocorre o erro 404 no network do navegador. As views estão no servidor.
Answer: Como os comentários apontaram acima, talvez falta um pouco de experiência na programação. Na linha 12 você esta verificando se a consulta retornou algum dado. Para fazer isso não é necessário fazer ´$resultados > 0`, visto que, em php, tudo é considerado verdadeiro, exceto

0 (zero numério)
"0" (zero string)
false
"" (string vazia)
null
array() (array vazio)

Caso queira estudar um pouco mais sobre isso sugiro a própria documentação do PHP
Logo, para fazer essa comparação basta fazer
if ($resultados)

Revise todo o seu código para verificar se isso não está acontecendo em outros lugares.
Comment: eu agradeço a ajuda. mas o problema agora é outro
Comment: eu postei os outros erros que acontecem. Minhas views não estão sendo encontradas. estou usando ` base_url()` nos links e alterei o arquivo `config.php`.
Comment: que valor vc colocar pra sua url base?
Comment: eu coloco o link onde está o sistema exemplo: `http://meusite.com.br/sistema/`... assim desse jeito
Comment: no seu servidor, você colocou seu sistema todo dentro de uma pasta chamado sistema? pq caso contrário não tem necessidade dessa parte. Seria muito mais fácil achar os erro se vc postasse o link do seu site. Isso é possível?
Comment: isso, dentro de uma pasta.. pq isso é uma má pratica? eu nao posso colocar na raiz... na raiz tem um site.
Comment: Pode ser assim, sem problemas. Tente ver o que está acontecendo na aba network do seu navegador
Comment: o fato de estar numa pasta, impede que minhas views sejam encontradas?
Comment: Não. Eu já subi sistemas que estavam em subpastas do sistema e tudo funcionou normalmente. Sem mais informações (código) não vai ter como te ajudar a achar o problema.
Comment: Quando eu tento acessar as views, ocorre o erro 404 no network do navegador. As views estão no servidor.


Why does autocorrelation function for trend in data decrease with increasing lag?

Question: Forecasting: Principles and Practice, 3rd edition by Hyndman and Athanasopoulos states in section 2.8, Autocorrelation that, for trend in data the autocorrelation function has positive values that slowly decrease as lag increases.
The definition for autocorrelation function for lag $k$ is defined here as -
$r_k=\frac{\sum_{t=k+1}^{T}{(y_t-\overline y)(y_{t-k}-\overline y)}}{\sum_{t=1}^T (y_t-\overline y)^2}$, where $T$ is the length of the time-series.
Can anyone give a rigorous proof and intuitive sense as to why it might be so, indifferent of the type of trend that the series might have?
P.S.: I am new to time-series; however, comfortable with maths.
Answer: I had the same doubt as you since I was introduced to time series analysis by the same book. Although it is useful to have an autocorrelation coefficient defined in that way, it may be a good idea to give some clarification in the book itself.
So, yes, as you said, the autocorrelation function decreases over the lag axis due to the fact that the global sample variance in the denominator remains the same and that - given a trended series - the actual sample variances of both the series used for the autocorrelation decrease w.r.t. the original one, since a bigger and bigger chunk of the variability at the extreme points of the series is not considered.
My idea is that this is useful mainly to distinguish a trended series from one that hovers around a constant value: without this artificial behaviour of the autocorrelation calculation we would not be able to distinguish the two in the ACF, since they would both have a constant ACF of about 1. This is not the case with the formulation using global sample variance instead of the actual sample variances of the lagged and cut versions.
Obviously, a non-linear trend induces a decreasing ACF either way.
Answer: Here is the full quote from the section you reference (bold added):

When data have a trend, the autocorrelations for small lags tend to be large and positive because observations nearby in time are also nearby in value. So the ACF of a trended time series tends to have positive values that slowly decrease as the lags increase.

Surely that gives the intuition. As the lags increase, the values are further apart in both time and value due to the trend.
Comment: The OP is asking for a rigorous proof and an intuition. You have provided the latter here, but not the former. Would you be willing to update your answer?
Comment: Asymptotically, yes. But not for finite samples. Using R, try `acf(1:n)` for different values of `n` to demonstrate.
Comment: @RobHyndman will that be the case for a timeseries that is simply a straight line? Will the  auto-correlations then, not be 1 for any lag, allowed by the length of the series? Although this is an extreme case, it is simple enough to use as a mental model while considering trends.
Comment: @RobHyndman I did with Python
`a = pd.Series(np.arange(30)); pd.Series([a.autocorr(lag=i) for i in range(25)])`
and all came out to be 1. However, I agree with the point that for finite linear series a shifted version will have a lower length and the corresponding term in numerator $y_{t-k}-\overline{y}$ gets affected while the denominator does not because it still uses the variance of the original series. However, should we not consider the denominator to be the $\sqrt{\text{var(original)var(shifted)}}$? I think this is why pandas results give 1.


Why not report the mean of a bootstrap distribution?

Question: When one bootstraps a parameter to get the standard error we get a distribution of the parameter. Why don't we use the mean of that distribution as a result or estimate for the parameter we are trying to get? Shouldn't the distribution approximate the real one? Therefore we would get a good estimate of the "real" value?  Yet we report the original parameter we got from  our sample. Why is that?
Thanks
Answer: Because the bootstrapped statistic is one further abstraction away from your population parameter. You have your population parameter, your sample statistic, and only on the third layer you have the bootstrap. The bootstrapped mean value is not a better estimator for your population parameter. It's merely an estimate of an estimate.
As $n \rightarrow \infty$ the bootstrap distribution containing all possible bootstrapped combinations centers around the sample statistic much like the sample statistic centers around the population parameter under the same conditions. This paper here sums these things up quite nicely and it's one of the easiest I could find. For more detailed proofs follow the papers they're referencing. Noteworthy examples are Efron (1979) and Singh (1981)
The bootstrapped distribution of $\theta_B - \hat\theta$ follows the distribution of $\hat \theta - \theta$ which makes it useful in the estimation of the standard error of a sample estimate, in the construction of confidence intervals, and in the estimation of a parameter's bias. It does not make it a better estimator for the population's parameter. It merely offers a sometimes better alternative to the usual parametric distribution for the statistic's distribution.
Answer: There is at least one case where people do use the mean of the bootstrap distribution: bagging (short for bootstrap aggregating).
The basic idea is that if your estimator is very sensitive to perturbations in the data (i.e., the estimator has high variance and low bias), then you can average over lots of bootstrap samples to reduce the amount of overfitting particular examples.
The page I linked to points out that this introduces some bias into your estimate, which is why the sample mean will often make more sense than averaging your bootstrap samples.  But if you have something like a decision tree or a nearest neighbor classifier that can change radically in response to small changes in the data, then this bias might not be as big a concern as overfitting.
Comment: I'm not sure I understand your question. I didn't actually *use* the phrase "bias of a parameter." I'm also not entirely sure what you mean by $y$ versus $\theta$ in this context.
Comment: I normally see bagging used to reduce the variance of one's estimates for the response (i.e. its sensitivity to fluctuations in the data). The most commonly bagged models (e.g. trees) typically don't have well-defined parameters that would be easily compared across bootstrap samples.
Comment: Thanks, that's exactly what I thought as well. To me bagging does not seem to make much sense for anything other than the estimate of a response, so it is limited in that sense.
Answer: It is worth noting that the difference between the mean of bootstrapped samples $\theta_B$ and the sample estimate $\hat{\theta}$ can sometimes be used as an estimate of the bias of $\hat{\theta}$ in estimating the true parameter $\theta$.
Answer: One simple answer, because it's biased.
A simple example, estimate the upper bound of a $\text{Uniform}(0, \theta)$ random variable. Here, I take 1,000 bootstrap samples of a $n=10$ random sample, and calculate the MLE for each BS subsample and average them together. The relative bias is 5%!
<code>set.seed(123)
out <- replicate(1000, {
  n <- 10
  u <- runif(n, 0, 3)
  mle <- max(u)*(n+1)/n

  bsm <- mean(replicate(1000, {
    max(sample(u, replace=T))*(n+1)/n
  }))
  c(mle, bsm)
})

b <- hist(out[1, ], col=c1 <- rgb(0.5, 0.5, 0.5, 0.5), breaks=pretty(out, 20), xlab='Estimate')
hist(out[2, ], breaks = b$breaks, col=c2 <- rgb(0.5, 0.5, 0, 0.50), add=T)
</code>


Greek modes, minor and major scales

Question: By definition, a major scale is:

W W H W W W H

similarly, a minor scale is:

W H W W H W W

Now, the standard notion of Greek modes begins with: a major scale, and the construction of the modes with the steps and whole steps of the major scale, like:

Choose the C key and build its major scale:

W W H W W W H = C D E F G A B C
This is the famous Ionian mode.

Now, choose the next note of the scale as key: D.

Then, note that we can construct a new scale pattern just seeing the steps and whole steps between the notes (which will ends in D):
W H W W W H W = D E F G A B C D
This is the famous Dorian mode.

Now, the whole thing began with a major scale as fundamental pattern. Therefore, my question is:
What if we start with a minor scale; it will be called "minor Greek modes"?
Comment: To expand on @phoog's comment: The seven modes built on some rotation of WWHWWWH are most unambiguously described as the [diatonic modes](https://en.wikipedia.org/wiki/Diatonic_scale#Modes).
Comment: Those modes have Greek names, but they are not Greek modes.
Comment: As others note, the Greek modes are totally different from the medieval European ("church") modes with pseudo-Greek names attached to them. But in the 16th-17th centuries, people did start thinking of the eight or twelve church modes as being primarily "major" or "minor" based on the size of the third above the final, and they were adding so many chromatic alterations that the other distinctions started to blur. This is where major and minor keys came from, oversimplifying somewhat. Keep in mind also that the church modes start on D, so it's not accurate to say they start from the major scale.
Answer:
What if we start with a minor scale; it will be called "minor greek modes"?

Well no, because the minor scale is already a mode of the major scale; it is the Aeolian mode.  You could define any of the modes as the "home mode," but the set of other modes derived by starting on each of the different scale degrees would be the same.
On the background information, I feel compelled to note that the Ionian and Aeolian modes that we recognize today were only established in the sixteenth century.  Before that, there were only the Dorian, Phrygian, Lydian, and Mixolydian authentic modes (and their plagal counterparts, the Hypodorian, Hypophrygian, Hypolydian, and Hypomixolydian, which had the same final pitch but different range and dominant).
These modes, in turn, were not the same as their ancient Greek namesakes, because they arose in the middle ages as the result of some misinterpretation of ancient Greek sources.  For this reason, they're more accurately called "church modes" or "medieval modes" than "Greek modes," but since modern modal music usually has little to do with medieval music, it's probably best just to call them "modes."
Answer: It's logical that all modes of the major scale follow that same sequence, but starting at different points along it. Seen better as circular rather than linear. Thus Ionian (parent, major) is TTSTTTS, Dorian moves one along, TSTTTST, and so on. Taking us to Aeolian, which is only another start point round the sequence.
Starting from there, it makes no sense to continue the sequence with the next note, etc., and call them modes of the minor! They're still the same!
The main fact of minor modes is their 3rd note. If that produces an interval of m3, then it's a minor mode. If it produces M3, it's a major mode. (Both against their root notes, I should say) This really has not much to do with the parent scale.
So, minor modes are Aeolian, Dorian and Phrygian, and major modes Ionian, Lydian, and  Mixolydian. Leaving Locrian as a fairly unusable (!) minor also.
There are also modes of the melodic and harmonic minors, again spawned from the parent scales. Those will have different intervals from what you have stated, and are modes from or of those other minors, but not necessarily major or minor modes in their own right. That's dictated again by m3/M3.
Answer: First of all. The definition of major and minor scales is not correct. Major scale is every scale with the major third. Minor scale is every scale with minor third. Therefore Ionian, lydian and mixolydian modes are considered major, whereas dorian, phrygian, aeolian (and locrian, which is not present in the old music) is considered minor.
The modes are older than the concept of major and minor. The old music did not use all twelve semitones. There used to be six modes in which the music was written. Later, people realised that the most beatiful for them were Ionian and Aeolian modes. Since these were almost only two used modes in Baroque and Classical era, Ionian scale is called the major scale and aeolian (and later harmonic and melodic scale) were called minor.
Therefore as an answer, we can call the Greek modes major or minor, as I wrote in the first paragraph. We can start wherever we want. The only thing that matters is the third.
Comment: "Major scale is every scale with the major third. Minor scale is every scale with minor third": this is going to be controversial.  It's true in some contexts, and it's certainly consistent with Bach's title page for the Well-tempered Clavier, but most modern theory teachers would give a negative mark if someone responded to an exercise asking for a major scale by writing a Lydian or Mixolydian scale.
Comment: @Tim perhaps, but it might be useful to quote Bach's aforementioned title page: _The Well-Tempered Clavier, or Preludes and Fugues through all the Tones and Semitones, Concerning both the major third or Ut Re Mi and the minor third or Re Mi Fa._  Whether we take replace the word "scale" with "key" in the first paragraph, it's equally correct (in the baroque sense) or incorrect (in the modern theory class sense).  Related to this, "mode" can refer either to scale or to key.
Comment: @phoog - I guess, like so many others, Vit is conflating scale and key...

Greek modes, minor and major scales


Can I connect an iPhone to a windows 10 machine to see my work in Flutter?

Question: I want to see my work without using a simulator from Android Studio. Currently I have an Android Phone and it works when I connect my phone with Windows 10.
Can I do the same with an iPhone?
Comment: You will need a mac or hackintosh
Answer: Flutter relies on Xcode and the iOS SDK to perform the underlying compilation and publishing of iOS apps. Unfortunately, it's not possible to do iOS development on Windows, a Mac is required.
Some googling reveals there are several online services, such as MacInCloud and MacStadium that provide a means to pay for a remotely accessible VM in the cloud if you'd prefer not to purchase a Mac, though not having used any, I can't personally vouch for any of them.


Jittering lines when scrolling a TMX map in cocos2d-x

Question: I feel like I'm missing some fundamental concept as to why I am getting flickering when moving a tile map around.
I create a layer. In it, I add a TMXTiledMap.
<code>_tileMap = TMXTiledMap::create("TMX/32Map.tmx");
_tileMap->setScale(1.f);
_floorLayer = _tileMap->getLayer("Floor");
this->addChild(_tileMap);
for(const auto& l : _tileMap->getChildren()) {
    static_cast<SpriteBatchNode*>(l)->getTexture()->setAliasTexParameters();
}
this->scheduleUpdate();
</code>
In the update I move the layer.
<code>Vec2 newPos = this->getPosition();
newPos.x = (newPos.x - 1);
newPos.y = (newPos.y - 1);
this->setPosition(newPos);
</code>
I realize I'm not moving it by dt. If I move it by dt I get an overall jumpiness to the whole layer. I understand this is due to how it renders partial pixels. But if I move it by one pixel like above, I get this # looking set of lines on the screen about 64 pixels or so on top and bottom and about 224 pixels from the left and right
That is when the window is 1024x768. If I make a 320x240 window, I don't see the lines and if I make it 640x480 I only see them on the left and right sides right near the edge of the screen.
Ultimately I'd just like to smoothly scroll a tile map around. Any help would be super appreciated, because I just can't seem to get started on this project.
Comment: Same problem. Do you solve that ? Maybe move map only by certain distance, or move only by even numbers.
Comment: I am currently using TexturePacker to add buffers around the tiles. I'm not sure this is 100% "solved" because I have been staring at it so long that everything looks weird to me, but as I delve further into the project I'll be able to tell if this really is what I needed or not.
Answer: For me working solution was to change CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL in ccConfig.h from 1 to 0. Find ccConfig.h in cocos/base/.
Comment: This only made things look gross on my end.


How to combine various measures into a single measure

Question: I have several measures:

Profit and loss (PNL).
Win to loss ratio (W2L).
Avg gain to drawdown ratio (AG2AD).
Max gain to maximum drawdown ratio (MG2MD).
Number of consecutive gains to consecutive losses ratio (NCG2NCL).

If there were only 3 measures (A, B, C), then I could represent the "total" measure as a magnitude of a 3D vector:
R = SQRT(A^2 + B^2 + C^2)
If I want to combine those 5 measures into a single value, would it make sense to represent them as the magnitude of a 5D vector? Is there a way to put more "weight" on certain measures, such as the PNL? Is there a better way to combine them?
Update:
I'm trying to write a function (in C#) that takes in 5 measures and represents them in a linear manner so I can collapse the multidimensional values into a single linear value. The point of this is that it will allow me to only use one variable (save memory) and it will provide a fast method of comparison between two sets of measures. Almost like building a hash value, but each hash can be used for comparison (i.e. >, <, ==).
The statistical significance of the values is the same as the order they're listed: PNL is the most significant while NCG2NCL is the least significant.
Comment: @Lirik: Like I said, there are all sorts of ways.  It's not possible to recommend a *good* or *meaningful* purely one from a programming perspective; you need to understand the problem domain (i.e. finance) to make a sensible decision.
Comment: Umm, isn't this an entirely domain-specific problem?  You can combine a set of numbers in an infinite number of ways; I'm not sure what this has to do with programming or algorithms...
Comment: @Jared, so many stack exchanges :)...
Comment: @Lirik - Yes, no kidding. My own thinking is, you'll need to find out what the statistical significance of each measure you're wanting to determine (weighting, for instance), and what it means in combination, and then maybe validate your math, before turning it into a algorithm. So it's putting the whip in front of the cart in front of the horse to work on the algorithm first.
Comment: I don't think the question could is as relevant as should you.
Comment: @Oli, I'm trying to program it :), so that's why I think there must be some sort of algorithm or method to represent a "multidimensional vector" with a linear value (i.e. magnitude). I need to be able to compare the "magnitudes of two vectors" in a meaningful way, so there must be some widely accepted ways to do that.
Comment: And this probably belongs on http://math.stackexchange.com/ or http://stats.stackexchange.com/
Comment: If you just want to compare the values, there is no need to do a SQRT.
Comment: @Jared, the statistical significance is the same as the order I listed the measures in: PNL has the highest statistical value, while NCG2NCL has the lowest statistical value. Like Nikita said: the magnitude of (9,0,0) is 9 and magnitude of (3,3,3) is 5.196, but simply adding the values would make the vectors look equivalent.
Comment: If you had training data you could train an SVM and let it figure out which measures are most important.  In that case your question could go on one of the machine-learning-oriented stack exchange type sites :)
Comment: @Hightechrider, thanks! 1-up for referring me to a "more appropriate" stack exchange site :). Anyway, I might just throw a bunch of values in Excel and see how they get distributed when I apply the suggested solutions... if I have any problems, I'll just go to the Excel-oriented stack exchange :).
Answer: If I want to combine those 5 measures into a single value, would it make sense to represent them as the magnitude of a 5D vector?
Absolutely, if result suits you.
Is there a way to put more "weight" on certain measures, such as the PNL?
You can introduce constant weights
SQRT(wa*A^2 + wb*B^2 + wb*C^2)

Is there a better way to combine them?
That depends on your requirements. In particular, there's nothing wrong with using simple sum |A| + |B| + |C|, that would favour 'average' properties better. I.e., with your formula (0, 0, 9) gives much better total than (3, 3, 3), while with the simple sum they would be equivalent.
Generally speaking Oli is right: you'll have to make the decision yourself, no algorithm book can evaluate the requirements for you.
Comment: thanks! I don't know if I didn't explain my problem sufficiently well, but you're definitely supporting my hypothesis: the magnitude formula gives a much better total than just adding the numbers. I was trying to think of a better total, i.e. something like a hash number, are hash numbers ever used to give a sort order for the thing they're representing?
Comment: @Lirik Hash values are distributed 'randomly'. E.g., for a vector `(0, 0, 1)` you could have hash `10000` and for vector `(100, 100, 100)` hash `3`. Does that suit you? If yes, go ahead :)
Comment: @Lirik "Better" in what sense? There's no general "better", but there might be "better" for your particular requirements.
Comment: by better I mean that the vectors are always represented by a single value that properly reflects the significance of the measures (where PNL has the highest significance and NCG2NCL has the lowest). So far I think that the vector magnitude with weights attached to each value will be sufficient... I don't plan on using a hash value, but I was just brainstorming.
Answer: Combining measures into a single value is risky at best.  However you do it you loose information.  If I have 3 oranges, an apple and a couple of slices of bread I can combine them in various ways:

Sum (3 + 1 + 2 ) = 6
Weighted sum ( .5 * 3 + 2 * 1 + 1.5 * 2) = 6.5
SQRT( 3 ^ 2 + 1 ^ 2 + 2 ^ 2) = SQRT ( 15 ) ~= 3.8
SQRT( 3 ^ 2 + 2 * 1 ^ 2 + 2 ^ 2) = SQRT (16) = 4
and on and on.

Whichever result I get is less meaningful than the first. Through in a steak and a glass of water and the value becomes even less meaningful.  The result is always some measure of serving of food.
You need to figure out how to convert your various values into values with equivelent scales (linear or log) and equivalent value (1 X ~= 1 Y  ~= 1Z).  At that point a simple sum or product may be sufficient.  In your case, it appears you are trying to combine various measure of financial return.  Some of the measures you are using are not highly comparable.
Comment: thanks, so far it seems like the weighted vector magnitude provides the most "resolution." For my purposes, its results seem to "better" distinguish the vectors.
Answer: I would suggest implementing this using principal component analysis. That will give you the weights you need for your coefficients.  You can either do this via a stat package or use a packaged C# function.
-Ralph Winters
Answer: As others have noted, there are an infinite number of ways of combining values. You've tagged the question machine-learning and artificial-intelligence, which suggests you might want to find the optimum way of combining them? Eg. come up with a "goodness" metric, and try to model this from the others. Then there are a range of machine learning algorithms - eg. a Bayesian Model would be a good start: Fast, generally performs well if not necessarily the best.


Relationship Question

Question: Let $\ S\ $ be a non-empty Set, and suppose s$\ \in S $.
Assuming $\ S\ $ is finite, what can we deduce about the relationship between  $\ |\mathcal P(S\ \setminus \{s\} )| $ and $\ | \mathcal P(S)|?$
May I know if the question is looking for $\ |\mathcal P(S\ \setminus \{s\} )| =$ $\ | \mathcal P(S)| \over  | \mathcal P(\{s\})| $ ?
Anyone care to elaborate? Thanks.
Comment: What is $\mathcal{P}$?
Comment: $\ \mathcal P(S) $ is powerset of S
Answer: Let $$P_1 = \{ A \subset S \mid s \in A\}$$ and $$P_2 = \{ A \subset S \mid s \notin A \}.$$ Then $\mathcal{P}(S) = P_1 \uplus P_2$ and $\mathcal{P}(S\setminus\{s\}) = P_2$. However, $|P_1| = |P_2|$ by bijection $f : \mathcal{P}(S) \to \mathcal{P}(S)$ (observe that $f$ is its own inverse, that is $f \circ f = \mathrm{id}_{\mathcal{P}(S)}$):
$$f(A) = \begin{cases} A \cup \{s\} & \text{ for } s \notin A \\
A \setminus \{s\} & \text{ for } s \in A \end{cases}$$
So $|\mathcal{P}(S)| = |P_1| + |P_2| = 2 |P_2| = 2|\mathcal{P}(S \setminus\{s\})|$.
I hope this helps ;-)
Comment: Thanks. So how did you derive $\ |\mathcal{P}(S)| = |P_1| + |P_2| = 2 |P_2| = 2|\mathcal{P}(S \setminus\{s\})| \;and \;|P_1| = |P_2| $?
Comment: @Ray.R.Chua I've taken care of a big majority of details, why don't you work out the rest yourself?
Comment: I think I get it. $\ |P_1| = |P_2| $ because f is 1-1 and onto. Thanks again!
Answer: $|\mathcal P(S \setminus \{s\} )| =\frac { | \mathcal P(S)|}{2}$

Relationship Question