Xamrin forms carousel view missing reference

Question: I am using carousel view in xamarin forms to navigate through pages. After adding packages to my project's xamarin forms folder, I got an error "Cannot load file or assemble xamarin.forms.carouselview or one of its dependencies" I tried loading the assembly in appdelegate.cs. Now am getting a build error "Reference to type xamarin.forms.IItemViewController claims it is defined assembly xamarin.forms.core, version=184.108.40.206, culture=neutral, publickeytoken=null, but could be found" this error is pointing to the code of appdelegate that i have written.
I will be grateful if i get any suggetions
PS: this works perfect in a sample app. i am getting such error only when i am integrating this in my official project.
Comment: Did you install the NuGet package on both your shared code project as well as the platform project?
Comment: yes i have added..
Answer: Xamarin Forms CarouselView has a dependency of Xamarin.Forms (>= 184.108.40.206-pre3)
You must upgrade to at least that version or higher. Your Xamarin.Forms.Core dll should then be version=2.0.0 instead of v1.5.0.
Comment: I think you should double-check on all projects, Adam seems to be right. If you look closely to the error that you got, you notice that there is a version number 188.8.131.52 in there.
Comment: Xamarin.forms version that am using is 22.214.171.124... this version is higher than 188.8.131.52-pre3..


SVM formula variations

Question: I was reading about SVM in Wikipedia and saw that the formula was written like this (with minus):
$$
\vec{w} \cdot \vec{x} - b = 0
$$
While other sources have it like this (with plus):
$$
\boldsymbol {w}^\text{T} \boldsymbol x + b = 0
$$
What are the differences in their meaning and which one should be used?
In essence I want to refer to the SVM formula and I don't know which one is the correct one.
Comment: Wikipedia is not an authoritative source. Personally, I'd use the second one, because that's the one I've seen in books, but it doesn't really matter, because the formulas are essentially identical.
Comment: What interpretation does the 'minus' give to it compared to the 'plus'?
Answer: Neither is more correct than the other, and you aren't going to get radically different interpretations from a sign change (as $b$ from one formulation can have the exact same interpretation as $-b$ in the other). Choices like this are usually made on the basis of what makes the formulas easier to write or look more aesthetically appealing, not interpretation.
Writing $w \cdot x - b = 0 \iff w \cdot x = b$ is (aesthetically) nice if you want to think of the hyperplane as a level curve of the function $f(x) = w \cdot x$ that corresponds to the value $b$. But you can just as easily interpret $w \cdot x + b = 0$ as the level curve corresponding to $-b$, so there is no difference in interpretation.
It's worth pointing out that Vapnik (one of the inventors of SVMs) uses $w \cdot x + b = 0$ in the Theory of Statistical Learning, so perhaps that's the "canonical" choice.

SVM formula variations


How to show that $\int_R f(z)dz=0?$

Question: Let $f$ be holomorphic in a neighbourhood of a closed rectangle $R$ except for finitely many points $z_0, z_1, \cdots, z_n \in int(R)$ and suppose that $$lim_{z\to z_j}(z-z_j)f(z)=0$$
Then how to show that $\int_{\delta R} f(z)dz=0?$
I am not able to think how to approach this question. Any help will be appreciated.
Answer: Take $\epsilon$ so small that $B(z_j,\delta) \subset int(R)$ for $j=1,2,……,n$.Then by Cauchy integral formula on multiple connected domain,we have
$$\int_{R}f(z)dz = \int_{\partial B(z_1,\delta)}f(z)dz + …… + \int_{\partial B(z_n,\delta)}f(z)dz$$
Next we prove that $\int_{\partial B(z_j,\delta)}f(z)dz=0$ for $j=1,2,……,n$.
Since $\lim_{z \to z_j}(z-z_j)f(z)=0$,then for any $\epsilon \gt 0$,there exists $r \lt 0$ such that $|z-z_j|\lt r$ implies $|(z-z_j)f(z)| \lt \epsilon$.Choose $\delta \lt r$ that $$|\int_{\partial B(z_j,\delta)}f(z)dz| = |\int_{\partial B(z_j,\delta)} \frac{(z-z_j)f(z)}{z-z_j}dz| = |\int_{0}^{2\pi} \frac{\delta e^{i\theta}f(z_j+\delta e^{i\theta})}{\delta e^{i\theta}}i\delta e^{i\theta}d\theta| \le \int_{0}^{2\pi}\epsilon d\theta =2\pi \epsilon$$
Hence $\int_{\partial B(z_j,\delta)}f(z)dz=0$.
Consequently $\int_{R}f(z)dz=0$
Answer: All singularities are of order $1$, i.e.
$$Res_{z=z_j}(f):=\lim_{z\to z_j}(z-z_j)f(z).$$
Since $$\int_R f(z)dz=2\pi i\sum_{j=0}^nRes_{z=z_j}(f),$$
you obviously have the result.
Answer: It suffices you prove this when there is exactly one such singularity and it is the origin. Note that if we take a ball $B$ in the interior of $R$, by Cauchy's theorem we can eliminate the integral along the boundary of $R\smallsetminus B$, and it remains to show that $$\int_{\partial B} f(z)dz=0$$
By hypothesis, given $\varepsilon >0$ we can choose $\delta >0$ so that $|f(z)z|<\varepsilon$ whenever $|z|<\delta$. Now take $B$ of radius $<\delta$, and note that the integral above is $$\int_{\partial B}zf(z)z^{-1}dz$$
By our estimation this is at most $$\varepsilon \int_{\partial B} \left|\frac{dz}z\right|=2\pi \varepsilon$$
in absolute value. Since $\varepsilon >0$ was arbitrary, we can conclude.

How to show that $\int_R f(z)dz=0?$


Can I create nested list in SlateJs?

Question: I need to create nested list objects like :
1. Abc
2. def
    a. abc
        i. lmn
        ii. opq
    b. def
3. ghi

I am using Slate Js as my editor where when a user presses tab I have added the code where the node is updated with its level :
if (event.key === "Tab") {
      event.preventDefault();

      let currentNode = Editor.above(editor,{at : editor.selection})[0];
      if(currentNode.type === "listItem"){
      let newLevel = currentNode.level ? currentNode.level + 1 : 1;

      Transforms.setNodes(editor, {level : newLevel});
}}

Here the level is getting added to the node but I cannot nest this data into a tree structure as slateJs only allows three level of nesting of nodes and it needs a text key in the third level.
Answer: You can. The trick is wrapping the text of a 'list item' node in a 'list item text' node (e.g. a span or p), as explained in this slate schema of @prezly/slate-lists. The subsequent nested list can now be added to the same 'list item' node as a 'list' node.

Can I create nested list in SlateJs?


Is it correct this way to compute that radical ideal?

Question:
Is it correct to compute that radical ideal in this way?
  $$\sqrt{(x^2,xz^2-x,y-z)}=\sqrt{(x^2,xz^2-x,y-z,x)}=\sqrt{(y-z,x)}=(x,y-z)$$

In particular, I added $x$ to generators inside the 'root' because there where $x^2$ and the exponent vanishes after applying the radical.

Is it also always true that an ideal in which appear only terms of degree $1$ is a radical ideal?

Thank you for your help.
Answer: Your computation is absolutely fine. For the second question, the answer is positive in the following sense:
Let $f_1, \dotsc, f_s \in k[x_1, \dotsc, x_n]$ be linear polynomials (i.e. their total degree is $1$, not necessarily homogeneous). Then $I=(f_1, \dotsc, f_s)$ is radical.
We proceed by induction over $n$, the $n=1$-case being trivial, since $(ax-b) \subset k[x]$ is reduced.
W.l.o.g. we can assume, that $x_n$ occurs within $f_1$ and after dividing by some constant, we can assume $f_1=x_n-f$ with some linear polynomial $f \in k[x_1, \dotsc, x_{n-1}]$. We can compute
$$k[x_1, \dotsc, x_n]/I = k[x_1, \dotsc, x_n]/(x_n-f, f_2 \dotsc, f_s)$$ $$\cong k[x_1, \dotsc, x_{n-1}]/(f_2(x_1, \dotsc, x_{n-1},f), \dotsc, f_s(x_1, \dotsc, x_{n-1},f)).$$
The terms $f_i(x_1, \dotsc, x_{n-1},f)$ are some linear polynomials in the variables $x_1, \dotsc, x_{n-1}$. By induction, the generated ideal is radical, i.e. we have shown that $k[x_1, \dotsc, x_n]/I$ is reduced.

Note that the assertion becomes false if we replace total degree by partial degree, since $(xy,x-y)$ is not radical.


Find the value of $\theta$ on $\pi/2 \le \theta \le \pi$ at which the curve $r=\theta - \sin (3\theta)$ is closest to the pole.

Question:
Find the value of $\theta$ on $\pi/2 \le \theta \le \pi$ at which the curve $r=\theta - \sin (3\theta)$ is closest to the pole.

How can I approach this problem? I thought to find the values of theta where $r=0$, but apparently that's not right. Calculators are allowed.
Answer: The problem is that the curve does not cross zero in this interval. The closer that it gets to it is at $\theta = \frac{1}{3}\arccos\left(\frac{1}{3}\right)+\left(\frac{2}{3}\right)\pi\approx 2.5047$. The plot looks like this:
Answer: You are right that the first step is to find where $r=0$. As you have found, the only solution is $\theta=0$ which is outside your allowed values of $\theta$, so this step fails. The given curve does not go through the origin.
Your next step is to find where $r$ is a minimum. The function for $r$ is continuous so we can use the usual calculus methods. We find the derivative and find where it equals zero.
$$\begin{align}
0 & = \frac d{d\theta}\left( r \right) \\[2ex]
 & = \frac d{d\theta}\left( \theta-\sin(3\theta) \right) \\[2ex]
 & = 1 - 3\cos(3\theta) \\[2ex]
\cos(3\theta) & = \frac 13 \\[2ex]
3\theta & = 2k\pi\pm\cos^{-1}\left(\frac 13\right) \\[2ex]
\theta & = \frac{2k\pi}3\pm\frac 13\cos^{-1}\left(\frac 13\right) \\[2ex]
\end{align}$$
The only values of $\theta$ that fit in your required interval have $k=1$:
$$\begin{align}
\theta & = \frac{2\pi}3\pm\frac 13\cos^{-1}\left(\frac 13\right) \\[2ex]
 & \approx 1.6840752966129, \quad 2.5047149081735
\end{align}$$
I'll let you finish form here. Note that there is no value of $\theta$ that makes $r$ undefined, so we have found all the critical points. Find which of those two values of $\theta$ has the minimum value of $r$ (the other has a maximum value). Compare that value of $r$ with those at the endpoints of the given interval and find the absolute minimum of $r$ with its corresponding value of $\theta$. Ask if you need more help.
Here is a polar graph of your problem, done on the TI-Nspire CX Graphing Calculator emulator. This confirms that the correct answer is the larger of the two values of $\theta$ above, $2.5047149081735$. This graph also shows the corresponding value of $r$ and the cartesian coordinates.


Search and wildcard

Question: Is there any simple way to provide searching with a wildcard using the Drupal core search engine?
I know it's possible with Apache Solr, but I'm looking for something very easy to implement.
I need to use it on i18n site.
Answer: The closest module I have found for doing this is the porter stemmer module.

This module implements the Porter stemming algorithm to improve
  English-language searching with the Drupal built-in Search module.
Comment: I've edited my question to i18n support.

Search and wildcard


Complements of hyperplanes in projective space are affine

Question: I'm trying to show that complements of hyperplanes in $P^{n}$ are affine varieties on my way to a bigger result but I've gotten stuck. Am I missing something- or will the complement be a copy of affine space? I'm not seeing it.
Answer: Well, take $H=\{(x_0:\cdots:x_n):x_0\neq0\}$ and show that $P_n\setminus H\cong\mathbb A^n$ by explicitly writing down an isomorphism.
(You did not tell us anything about what you know, so it is difficult to be more explicit here... For example, do you think of varieties as schemes, as algebraic subsets of $\mathbb A^n$$?)
Answer: Start by showing that you may assume the hyperplane is of form $H\colon x_n=0$ (where the points in $\mathbb{P}^n$ are $(x_0\colon\cdots\colon x_n)$. That will simplify things.
Then you want to define a bijection between $\mathbb{A}^n$ and $\mathbb{P}^n-H$. There is a standard embedding of affine space into projective space, so you can start there.
Of course, the trick is to show that this bijection is in fact a homeomorphism in the Zariski topology. This involves making a correspondence between zeros of homogeneous polynomials in, say, $z_0,\ldots,z_n$, and zeros of polynomials in $z_0,\ldots,z_{n-1}$ (to make closed sets in $\mathbb{P}^n$ corresponds to closed sets in $\mathbb{A}^n$).
Do you know any way to take a polynomial in $k$ variables and use it to define a set of zeroes in projective $k$-space? (Hint: If your milk doesn't have clumps of cream in it, then it is <blanked>.) And how would take a homogeneous polynomial in $k+1$ variables and use it to define a set of zeros in affine $k$-space?
Comment: This was likely homework... :)
Comment: @Mariano: Good point.


MLB Pitch Types "Back in the Day"

Question: I was thinking how hard it would be to approach DiMaggio's 56 game hit streak these days.
Not only are there defensive shifts, specialized pitchers to get certain guys out, faster overall pitch speeds, etc...but what were pitch selections like?
Did pitchers have two-seamers, cutters, sinkers, etc back in the middle part of the 20th century?
Answer: I think that a comprehensive source could be found in this book by Neyer/James -
 The Guide to Pitchers: An Historical Compendium of Pitching, Pitchers, and Pitches.
Comment: While it may be a great source, Stack Exchange strongly prefers answers to be self-contained. Jonathan, could you please try and summarise the relevant parts of the book in your answer?
Comment: It seems the question may be a bit large in scope in for self-contained answers (there is a whole book about it, after all?), though I too would certainly find a self-contained answer of value.   Jonathan it sounds like you've read the book and could potentially give a better explanation, though it is understandable that it could be a real time labor to be thorough!  I appreciate the resource though, as it does put a direction in play for getting an answer to this question.

MLB Pitch Types "Back in the Day"


Issue with passing values in JQUERY functions

Question: With some help I have written in JQUERY this:
   $('id').clickToggle(addMarker, destroyMarker);

where clickToggle is a function which calls addMarker and destroyMarker functions.
This is the clickToggle() function:
 $.fn.clickToggle = function(func1, func2) {

        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };

And addMarker() function is
var addMarker = function(){ ....}
I don't have so much xp in JQUERY. What I want to do is to pass a variable inside the addMarker() function. The way my code is written how can I do it?
Comment: OT: `$.proxy(funcs[tc], this)()` -> `funcs[tc].call(this)`
Comment: Which variable do you want to pass to `addMarker`?
Comment: Thanks for the answer! The variable is defined outside the clickToggle() function.  Like this: var id = x;  $('#'+id).clickToggle(addMarker, destroyMarker);
Answer: A demo will be very handy here:
jsfiddle demo
HTML

click me

Javascript/jquery
 $.fn.clickToggle = function(func1, func2) {

        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
//lets pass the strings "world" and "foo" to addMarker and destroyMarker
$('#myid').clickToggle(function(){addMarker("world")}, function(){destroyMarker("foo")});

//pass a variable as a parameter to the functions
var addMarker = function(x){ alert("addmarker "+x)}
var destroyMarker= function(x){alert("removemarker "+x)}

Comment: I had a typo in the code example. It is fixed now :-)
Comment: Thanks but it doesn't seem to work. Nothing is alerted!
Comment: It should work, It is working on my PC (using firefox) so it should work on yours too.
Comment: Yeah. Strange. Instead of the div id I have an image id. It should have the same result.
Comment: What do you mean with image id? The code I posted is the same as in the Jsfiddle except for the comments.
Comment: I use this: $('#'+idImg).clickToggle(function(){addMarker("world")}, function(){destroyMarker("foo")}); Where idImg variable is the id of the img element.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/71772/discussion-between-kasper-taeymans-and-dkar).
Answer: If you're using a global variable, you can do it like this:
var x = 5;

$.fn.clickToggle = function(func1, func2) {

        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            funcs[tc].call(this, x);
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };

$('id').clickToggle(addMarker, destroyMarker);

Fiddle
Comment: @dkar Read about the `.call()` function here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
Comment: Thanks for the answer. But how do I pass then the x variable into the addMarker function()?
Comment: @dkar Here: `funcs[tc].call(this, x);`. The `call` allows you to pass parameters, which is what `x` is doing there after the `this` variable.
Comment: Using  global variables is not recommended when not necessary.
Comment: @kasperTaeymans True, but sometimes you can't change your code and just have to make do.


How to use the parameter passed through url in validation of form

Question: I have following model:
class ArticleUser(models.Model):
   email = models.EmailField(max_length=200)
   fullname = models.CharField(max_length=200)
   article = models.ForeignKey(Article)
   create_time =models.DateTimeField()
   def save(self, *args, **kwargs):
       ''' On save, update timestamps '''
       self.create_time = datetime.datetime.utcnow().replace(tzinfo=utc)
       super(ArticleUser, self).save(*args, **kwargs)

   class Meta:
       unique_together = (('email','article'),)

I am passing the article_id through the url:
url(r'^articlebuffer/(?P<mid>\d+)/$',views.articlebuffer, name="articlebuffer"),

I need to use the article_id in the validation of the form so that article and email are unique together. How can I achieve it in the formset as well as in form
Here is my view using formset:
def articlebuffer(request,mid):
   ArticleBufferFormSet = modelformset_factory(ArticleUser,exclude=('article','create_time'))
    if request.method == 'POST':
        formset = ArticleBufferFormSet(request.POST)
        if formset.is_valid():
            instances = formset.save(commit=False)
            for instance in instances:
                instance.article_id = mid
                try:
                    instance.save()
                except:
                    error="Unique Constraint Error"

            return HttpResponseRedirect('')
    else:
        formset = ArticleBufferFormSet(queryset= ArticleUser.objects.none())
    return render (request, 'tracking/createarticlebuffer.html',{'formset':formset,
                                                       })

Answer: Include it with your POST data when you create a new ArticleBufferFormSet
formset = ArticleBufferFormSet(dict(request.POST.items() + {'article_id': article_id}))


What is correct way to add onChange event inside html element in React?

Question: I am using fullcalendar library for the calendar feature. It has one of the callback function to change the viewRender of the calendar. I am modifying it to change the title to dropdown select by appending the html element.
   viewRender: function(view) {
    let title = view.title;

    $("#calendar").find('.fc-toolbar .fc-left > h2').empty().append(
      "
" +
        "<select id='months-tab' className='Select-input' onChange={this.handleChange.bind(this)}>" +
          "<option data-month='0'>January</option>" +
          "<option data-month='1'>February</option>" +
          "<option data-month='2'>March</option>" +
          "<option data-month='3'>April</option>" +
          "<option data-month='4'>May</option>" +
          "<option data-month='5'>June</option>" +
          "<option data-month='6'>July</option>" +
          "<option data-month='7'>August</option>" +
          "<option data-month='8'>September</option>" +
          "<option data-month='9'>October</option>" +
          "<option data-month='10'>November</option>" +
          "<option data-month='11'>December</option>" +
        "</select>" +
      "
"
    );
  },

How to bind handleChange event on the above appended select tag?
Answer: You will need to implement the event listener in componentDidMount() function in your component. componentDidMount will be called only once when the view is rendered for the first time.
componentDidMount() {
   $('#months-tab').change(function() {
       //Logic to handle change event.
   });
}

Hope this helps.


How to find the surface of integration

Question: The problem gives the curl of a vector field, and tells us to calculate the line integral over $C$ where $C$ is the intersection of $x^2 + y^2 = 1$ and $z= y^2$. I know I should use Stokes Theorem, but how do I find $dS$?
I did $z = \frac{1}{2}(y^2 + 1 - x^2)$ and calculated $dS$ as $\langle-dz/dx,-dz/dy,1\rangle$ but apparently that was wrong.
Answer: I drew a figure illustrating how these two surfaces intersecting with each other
The intersecting curve $C$ is that black line, and let's assume $C$'s direction is rotating counter-clockwise if you look from above. The surface $S$ is part of the $z=y^2$ that is inside the cylinder. Its surface normal is taking gradient of the equation $y^2 - z= 0$: $(0,2y,-1)$, normalize it we have the unit vector normal is $\mathbf{n} = (0,2y,-1)/\sqrt{4y^2+1}$
Suppose the vector field given is $\mathbf{F}$, then by Stokes theorem:
$$
\oint_C \mathbf{F}\cdot d\mathbf{r} = \int_S \nabla \times \mathbf{F} \cdot d\mathbf{S} = \int_S \nabla \times \mathbf{F} \cdot \mathbf{n}\,dS,
$$
where the $\mathbf{n}\,dS$ part is probably what you are looking for. Then what you need to do is just parametrizing $S$, and compute a surface integral for a scalar field.
Answer: So long as there isn't any sort of problem point (such as if the vector field you're integrating is undefined at the origin), you can integrate over any surface that is closed within the definition. So let $z=y^2$ be the surface, and let $x^2+y^2=1$ describe the limits of the surface (because $x^2+y^2=1$ doesn't form a simple surface).
If you convert to cylindrical coordinates, then $z=y^2=r^2\sin^2\theta$ is the surface and the bound is given by $r\leq 1$, $0\leq \theta< 2\pi$. So
$$\mathbf{r}=x\mathbf{i}+y\mathbf{j}+y^2\mathbf{k}$$ and $$d\mathbf{S}=\frac{\partial\mathbf{r}}{\partial x}\times\frac{\partial\mathbf{r}}{\partial y}dxdy=\mathbf{i}\times\left(\mathbf{j}+2y\mathbf{k}\right)dxdy=\left(\mathbf{k}-2y\mathbf{j}\right)dxdy$$ and since $$dxdy=rdrd\theta$$ we have
$$
d\mathbf{S}=(\mathbf{k}-2r\sin\theta\mathbf{j})rdrd\theta
$$

How to find the surface of integration


How to make a topology out of $N$ that involves convergent / divergent sets.

Question: Let $N$ be the naturals $1, 2, \dots$  Call a subset $A$ of $N$ convergent if the reciprocal sum $\sum_{a \in A} \frac{1}{a}$ converges.  Similarly call as set divergent if the sum diverges.  Notice that in this context, since it involves only positive numbers, a set is either convergent or divergent.
Define a topology on $N$ by defining the closed sets to be convergent sets. Clearly arbitrary intersections are convergent as well.  Let $A, B$ be two convergent sets, then $A \cup B$ is also a convergent set. Does this mean that the open sets are precisely the divergent sets?
Answer: Consider $A = \{ 2n : n \in \mathbb{N} \}$ and $B = \{ 2n-1 : n \in \mathbb{N} \}$. Note that $B = \mathbb{N} \setminus A$, and both $\sum_{a \in A} \frac{1}{a}$ and $\sum_{b \in B} \frac{1}{b}$ diverge. Therefore neither $A$ nor $B$ are convergent sets, and so by definition of the topology they are not closed. As a set is open iff its complement is closed, it follows that their complements, $B$ and $A$, respectively, are not open. (So we have two divergent sets which are not open.)
On the other hand every open set (except for $\emptyset$) must be divergent, simply because if $B \subseteq \mathbb{N}$ were a nonempty open convergent set, then $\mathbb{N} \setminus B$ is a closed set distinct from $\mathbb{N}$, and so it must be convergent, and so $\mathbb{N}$ is the union of two convergent sets, which contradicts that $\mathbb{N}$ is not convergent.
Comment: I'm not sure what you mean, do you mean their complements are not closed?
Comment: @EnjoysMath I've added a bit more explanation to my answer.
Comment: Okay, so you exhibited two sets that are neither open nor closed?
Comment: Okay, so $B$ is a divergent set yet not open.
Comment: Okay, so all open sets in the topology are divergent but not all divergent sets are open.


Algoritmos de ordenação - Como descobrir comparações e movimentações

Question:     package faculdade;

import java.util.Random;

public class Ordenacao {

    public static long comparacao;

    public static long movimentacao;

    public static void main(String[] args) {
        int[] vetor = new int[1000];
        fill(vetor);
        System.out.println("Vetor criado:");
        // show(vetor);
        // tempo inicial
        long tempoInicial = System.currentTimeMillis();
        //selectionSort(vetor);
        bubbleSort(vetor);
        //insertionSort(vetor);
        //quickSort(vetor, 0, vetor.length - 1);
        // tempo final
        long tempoFinal = System.currentTimeMillis();

        System.out.println("Executado em = " + (tempoFinal - tempoInicial) + " ms");
        System.out.println("\n Comparações: " + comparacao + " Movimentaçoes: " + movimentacao);
        System.out.println("Finalizado.");

    }

    public static void selectionSort(int[] vetor) {
        comparacao = 0;
        movimentacao = 0;
        for (int i = 0; i < vetor.length - 1; i++) {
            int menor = i;
            for (int j = i + 1; j < vetor.length; j++) {
                comparacao++;
                if (vetor[j] < vetor[menor]) {
                    comparacao++;
                    menor = j;
                }

            }
            swap(vetor, i, menor);
            // show(vetor);
            movimentacao++;
        }
    }

    public static void bubbleSort(int[] vetor) {
        movimentacao = 0;
        comparacao = 0;
        for (int i = vetor.length; i >= 1; i--) {
            for (int j = 1; j  vetor[j]) {
                    swap(vetor, j, j-1);
                    comparacao++;
                }
            }
            show(vetor);
        }
    }

    public static void insertionSort(int[] vetor) {
        comparacao = 0;
        movimentacao = 0;
        for (int i = 1; i < vetor.length; i++) {
            int current = vetor[i];
            int j = i - 1;
            while (j >= 0 && current < vetor[j]) {
                vetor[j + 1] = vetor[j];
                j--;
                comparacao++;
            }
            // at this point we've exited, so j is either -1
            // or it's at the first element where current >= a[j]
            vetor[j + 1] = current;
        }

            show(vetor);
            movimentacao++;
    }

    public static void quickSort(int vetor[], int esquerda, int direita) {

        int esq = esquerda;
        int dir = direita;
        int pivo = vetor[(esq + dir) / 2];
        int troca;

        while (esq <= dir) {
            while (vetor[esq] < pivo) {
                esq = esq + 1;

            }
            while (vetor[dir] > pivo) {
                dir = dir - 1;

            }
            if (esq <= dir) {
                troca = vetor[esq];
                vetor[esq] = vetor[dir];
                vetor[dir] = troca;
                esq = esq + 1;
                dir = dir - 1;
                movimentacao++;

            }
            comparacao++;
        }
        if (dir > esquerda) {
            quickSort(vetor, esquerda, dir);

        }

        if (esq < direita) {
            quickSort(vetor, esq, direita);

        }

    }

    public static void fill(int[] vetor) {
        Random r = new Random();
        for (int i = 0; i < vetor.length; i++) {
            vetor[i] = r.nextInt(100);
        }
    }

    public static void show(int[] vetor) {
        for (int i = 0; i < vetor.length; i++) {
            System.out.print(vetor[i] + " ");
        }
        System.out.println("");
    }

    public static void swap(int[] vetor, int a, int b) {
        int aux = vetor[a];
        vetor[a] = vetor[b];
        vetor[b] = aux;
        movimentacao++;

    }

}

Na hora de executar, o numero de comparação está sendo igual ao de movimentação. Acredito que esteja errado
Answer: Os números de comparação e movimentação são sempre iguais pois vc só acresce ele quando entra no if. Se vetor[j - 1] for maior que vetor[j] ele não entra no if, logo não acresce na variável comparacao, mas a comparação foi feita.
O seu método deveria ser assim:
public static void bubbleSort(int[] vetor) {
    movimentacao = 0;
    comparacao = 0;
    for (int i = vetor.length; i >= 1; i--) {
        for (int j = 1; j  vetor[j]) {
                swap(vetor, j, j-1);
            }
        }
        show(vetor);
    }
}


Push local repo to github. It says "working tree clean" but it is not

Question: I have a local repo that I want to push to github. But it doesn't push, because it thinks that the working tree is clean.
This is the output:
shmuel@nixos  ~/nixos   master ±  git add .  && git commit -m config && git push origin master
[master ab79eda] config
 1 file changed, 1 insertion(+)
To github.com:shmu26/NIX.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'github.com:shmu26/NIX.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
 ✘ shmuel@nixos  ~/nixos   master  git add .  && git commit -m config && git pull origin master
On branch master
nothing to commit, working tree clean
 ✘ shmuel@nixos  ~/nixos   master  git add .  && git commit -m config && git push origin master
On branch master
nothing to commit, working tree clean

I set up the credentials, but when I try to push, it says that first I need to pull.
So I pull.
Then, when I try again to push, it says the tree is clean. So nothing gets pushed.
Comment: This usually happens when there are commits on remote that don't have in local. They are not synchronized. So you may try pull first then push. If it won't work try force push. But remember, this will overwrite changes in remote
Answer: error is not on git push command rather in git add and git commit

nothing to commit, working tree clean

That's because:

The git pull command is actually a combination of two other commands, git fetch followed by git merge. In the first stage of operation git pull will execute a git fetch scoped to the local branch that HEAD is pointed at. Once the content is downloaded, git pull will enter a merge workflow. A new merge commit will be-created and HEAD updated to point at the new commit. source

So, after you run git pull command, git is creating a new merge commit (if there is no merge conflicts).
As a result your working tree is clean and can't stage nor commit.
If you are okay with git created commit, you should just push it to remote
git pull origin master && git push origin master
If it is not what you want, you can use git fetch and merge as you like.
Or you can use rebase option as outline in this answer
git pull --rebase <remote-name> <branch-name>


ASPNET credentials in web.config : how to map username and password with UI

Question: Nothing refers to UI element from ref doc
http://msdn.microsoft.com/en-us/library/da0adyye.aspx
Even looking at some example here http://vishalnayan.wordpress.com/2011/03/22/creating-credential-store-for-form-authentication-in-asp-net-3-5/
I don't understand how  username and password in webconfig credential are mapped with UI elements.
In the example the textbox has id UsernameText and not Username so how can asp.net could do the mapping between the two ?
Answer: It doesn't map to UI elements automatically. After the user enters his username and password it is being checked in code-behind like that:
<code>if (FormsAuthentication.Authenticate(UsernameText.Text, PasswordText.Text))
</code>


New SBS2011 box not setting up Internet

Question: A customer has asked for help with this, and given me remote access, and my Google searching is not helping. SU doesn't seem to have anyone available to help in chat currently, so I'm trying here.
I start it up, run the Setup your Internet address and Configure a Smart Host for Internet e-mail wizards, only to be told that the Connect to the Internet wizard must be completed first. Fine, I'll do that.
I start that wizard, it detects the router IP and the Server IP. DHCP and DNS are disabled in the router, and set for the server. At the end of the wizard, I get Windows SBS did not properly configure your e-mail. To correct this, re-run this wizard.
Doing googling, I ran PS scripts, re-configured IIS, and none of this has worked. Has the customer screwed over his server? Or is there a way to recover from this point? It is accessing the Internet just fine (proof: I'm remoting to it)

EDIT: Logs uploaded

Session "WBCommandletInBuiltTracing" failed to start with the following error: 0xC0000035

(Process w3wp.exe, PID 6452) "RBAC authorization is unavailable due to the transient error: The Microsoft Exchange Active Directory Topology service on server localhost did not return any suitable domain controllers."

The mount operation for the gatherer application cf7f8355-fe55-4b3b-a945-060635a824a7 has failed because the schema version of the search administration database is less than the minimum backwards compatibility schema version supported for this gatherer application. The database might not have been upgraded.

The Microsoft Exchange Throttling Service encountered an Active Directory error while building an RPC security descriptor. This failure may indicate that no Domain Controllers are available at this time. The service will be stopped. Failure details: Microsoft.Exchange.Data.Directory.NoSuitableServerFoundException: The Microsoft Exchange Active Directory Topology service on server localhost did not return any suitable domain controllers.
   at Microsoft.Exchange.Data.Directory.DSAccessTopologyProvider.GetConfigDCInfo(Boolean throwOnFailure)
   at Microsoft.Exchange.Data.Directory.TopologyProvider.PopulateConfigNamingContexts()
   at Microsoft.Exchange.Data.Directory.ADSession.GetConfigurationNamingContext()
   at Microsoft.Exchange.Data.Directory.Recipient.ADRecipientSession.GetWellKnownExchangeGroupSid(Guid wkguid)
   at Microsoft.Exchange.Data.Directory.Recipient.ADRecipientSession.GetExchangeServersUsgSid()
   at Microsoft.Exchange.Data.ThrottlingService.ThrottlingRpcServerImpl.GetRpcSecurityDescriptor()
   at Microsoft.Exchange.Data.ThrottlingService.ThrottlingRpcServerImpl.c__DisplayClass1.b__0()
   at Microsoft.Exchange.Data.Directory.ADNotificationAdapter.RunADOperation(ADOperation adOperation, Int32 retryCount)
   at Microsoft.Exchange.Data.Directory.ADNotificationAdapter.TryRunADOperation(ADOperation adOperation, Int32 retryCount)

An unexpected error occurred while starting the Microsoft Exchange Address Book service. Error details: The wait operation timed out (258)

The Mailbox Replication service was unable to determine the list of mailbox databases hosted in the local Active Directory site.
Error: The Microsoft Exchange Active Directory Topology service on server localhost did not return any suitable domain controllers.

EDIT 2: As per request, here is the DNS Forwarders configuration inside of the DNS MMC snapin:
Comment: @HopelessN00b you are not supposed to do "manual" configuration with an SBS - it's all wizardry land there.
Comment: Have you suggested that maybe he should try running his Exchange server on a real OS?  Or going with a hosted Exchange solution?  Well, that probably not particularly helpful, but maybe the event log entries saying *why* the wizard failed would be of use.  SBS does have event logs... doesn't it?
Comment: @HopelessN00b Exchange is made to run on SBS. What's not real about that?
Comment: @HopelessN00b How is it not a real OS? It does OS functions, therefore it's an OS
Comment: Why are you even running the wizards if the box already has internet access?
Comment: @OliverSalzburg It's the customer's box, that he can't get working :-/ The Exchange connector isn't working, so I know it's not an email issue. They do want the Exchange Server running on it htough
Comment: @HopelessN00b Yes it does. What logs would you like?
Comment: Oh dear, God... what fresh hell is this?  I would suggest posting the app and system event logs showing errors that correspond to the wizard(s) not being applied correctly... but honestly, it might be more productive to assign a domain and create an SMTP smarthost manually.  Though a though does occur:  Windows often prevents you from changing network settings when you're TSed in, to protect you from yourself.  Try connecting with `mstsc /console` and see if that gets you better results on those network wizards.
Comment: @HopelessN00b OK, I will try connecting with console mode, try my troubleshooting again, and post back
Comment: The customer decided that a wipe and reload was a lot easier. Feel free to close as Too Localized, as I won't be able to select an answer otherwise
Comment: @WesleyDavid  You mean, MS made their not-a-real-OS product compatible with the mail server?  Shocking.  What makes SBS not a real OS is everything else about it, primarily its effort to make a server OS that's aimed at and marketed at people who're not technically knowledgeable enough to actually run a server.
Answer:
DHCP and DNS are disabled in the router, and set for the server

You likely have an issue with DNS resolution. The SBS has been designed with the idea of a working company router in mind. While disabling the DHCP server on the router is a good idea, disabling the DNS forwarder is not, as the SBS will try to resolve any of its own external requests through the router's forwarder.
Simply re-enabling the DNS forwarder on the router and re-running the "connect to the internet" wizard should help here.
Comment: The DNS forwarder was set to 18.104.22.168 (Google's DNS). I added the Router as another forwarder, and turned DNS back on in the router. Running the wizard - No change, even after restarting the DNS Server service
Comment: @Luke have you double-checked that it is the *forwarder* which is set (i.e. a forwarder setting in the DNS Server MMC snapin) and not the *resolver* in the TCP/IP configuration of the server? The latter has *always* to point to the SBS server itself, otherwise domain location and any depending services would not work.
Comment: See edit with picture
Answer: I've recently put an SBS2011 and had lots of problems .. it was really fussy!...
Try running "Fix my network" even though it is connected to the internet anyway and just use the same information and make sure you haven't got any other domain controllers or DHCP servers on the same network.
This sorted my problem, as I manually configured my NICs .. it really doesn't like people changing anything manually

New SBS2011 box not setting up Internet


Fragment onStop() being called directly after onStart() - WHY?

Question: I'm having a strange problem with my app -
A have a Fragment Activity which contains a fragment - This fragment starts an AsyncTask onCreate() and cancels the AsyncTask onStop(). My problem arises because, although my Fragment stays running & isn't obscured it's onStop() is called almost directly after it's onCreate().
Does anyone know how to trace why this would be happening?
09-28 11:41:56.785: VERBOSE/SearchFragment1(924): onCreate()
09-28 11:41:56.796: VERBOSE/SearchFragment1(924): onStop()

EDIT
I've removed the code from the Fragment and I'm still absolutely baffled - The problem persists! I've added a few more lines of logging:
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onAttach()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onCreate()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onCreateView()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onActivityCreated()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onStart()
09-28 14:09:00.246: VERBOSE/SearchResultsFragment1(1789): onStop()
09-28 14:09:00.246: VERBOSE/SearchResultsFragment1(1789): onStart()
09-28 14:09:00.246: VERBOSE/SearchResultsFragment1(1789): onResume()

The above behaviour is... baffling. The code used in the Activity looks like this:
if(savedInstanceState == null)
{
    try {
        FragmentTransaction transaction= getSupportFragmentManager().beginTransaction();
        Fragment currentFragment= (Fragment)Class.forName(getIntent().getAction()).newInstance();
        transaction.replace(R.id.singlePane, currentFragment);
        transaction.commit();
    } catch ...

This is the Fragment as it stands during debug:
private static final boolean LOGGING_ENABLED = true;
private static int global_creation_count = 0;
private int local_count = global_creation_count;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onAttach()");
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    global_creation_count+=1;
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onCreate()");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onCreateView()");
    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count,
    "onActivityCreated()");
}

@Override
public void onStart() {
    super.onStart();
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onStart()");
}

@Override
public void onResume() {
    super.onResume();
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onResume()");
}

// Fragment is active

@Override
public void onPause() {
    super.onPause();
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onPause()");
}

@Override
public void onStop() {
    super.onStop();
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onStop()");
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onDestroyView()");
}

@Override
public void onDestroy() {
    super.onDestroy();
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onDestroy()");
}

@Override
public void onDetach() {
    super.onDetach();
    if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onDetach()");
}

EDIT2
From the code it seems that the onStop() is being called directly after onStart(). I've tried to see if it's being called at the same time as onStart() by adding a Thread.sleep(1000) in onCreateView(). The output is the same - which makes me beleive the onStop() is being called/caused directly from Fragment creation process.
EDIT3
Stacktrace when breaking on onStop():

I'm going to try and attach the source code and step through to discover where the problem is.
Answer: Still don't know what it was trying to do... I researched on where to get the source code for the class's involved in called onStop() and found that the source for android-support-v4.jar comes packaged along with the jar in the SDK.
After attaching this source though I soon found it was out of sync and that my android-support-v4.jar was vastly different to the one shipped with the current version of the SDK.
Replacing the jar with the one packaged with the SDK fixes the problem instantly and no onStop() is called after onStart(). Not sure what bug was causing this but the latest version seems to fix it quite handily.
Comment: Thank you - this was causing me much pain.  I guess it was a bug in an old version of the suppport library.


html menu change drop down text color only

Question: I'm trying to change the color of the text on only the part of the menu that drops down. My problem when changing the font color is it changes the font color for the whole menu rather than just the drop down part of the navigation.
i apologize in advance its been years since i worked with html and i'm very rusty.
example here
The code here:

Simology

Needs

Skills

Traits

Moodlets

Lifetime Wishes

Life Time Rewards

Death

Ghosts

Expansion Guide

Ambitions

Generations

Pets

Late Night

Supernatural

World Adventures

University Life

Towns

Sunset Valley

Monte Vista

Hidden Springs

Dragon Valley

Roaring Heights

Free Downloads

 Custom Sims

Sliders

About

Contact

Answer: Try this
#mbt-menu li ul li > a {
    color: // your colour here;
}

Answer: #mbt-menu a {
float: left;
padding: 10px 25px;
color: #FFFFFF;
text-transform: uppercase;
font: bold 12px Arial, Helvetica;
text-decoration: none;
text-shadow: 0 1px 0 #000;
}

This part of the css is the one that is causing the issue. You are setting any link that is part of the menu to be white, even the ones that are not the submenu.
You can instead move that color: #ffffff out, and do
#mbt-menu li ul a{
color: #FFFFFF;
}

This finds all the a tags that are part of the menu that are under a sublist and sets the color to white.
Answer: Here is a way to fix that
#mbt-menu ul a {
   color:coral; //change any color here
}

DEMO


cant import code modules with vscode venv feature

Question: VsCode provided venv creation feature. I tried it. Suppose, I have that project structure:
PJFOLDER
├── .venv/*
├── src/
│   └── inner_main.py
├── utils/
│   └── my_utils.py
└── outer_main.py

In both inner_main.py and outer_main.py I have imports of my_utils.py like that:
from utils import my_utils

Python Interpreter selected correctly (even automatically), basic type checker enabled, no errors. When I run outer_main.py via Ctrl+F5 or just Run Python file - everything ok. But when I try to do the exact same thing with inner_main.py it says ModuleNotFoundError: No module named 'my_utils'.
I tried to type python -m src.inner_main, with activated venv ofc, and it worked!
Well, I thought it is because PATH variable, indeed, it has path_to_project/PJFOLDER/.venv/Scripts/ but not my PJFOLDER explicitly.
I tried this code:
import os

path_var = os.environ["PATH"].split(";")
path_var.insert(0, os.getcwd())
os.environ["PATH"] = ";".join(path_var)

But it didn't help.
Can someone clarify this situation for me, please? How am I supposed to run inner code with inner imports preferably using default VSCode features like debugger and Run Python file? My project in early development and it can have multiple executable .py files and I don't want to type\select everything in terminal...
UPD 1:
Based on @Michael Butscher comment. I've created file import_fix.py with such code:
import sys
import os

sys.path.insert(0, os.getcwd())

This file lays in .venv folder. Since sys.path contains this folder, I can import it in any file in my project if I need. This file inserts current working directory in sys.path and I can use imports. Though it seems odd. Why doesn't sys.path contain cwd by default? Maybe there is a better solution? Maybe some setting in VSCode?
Comment: You can prepend the path to `PJFOLDER` to the list in `sys.path` to make the import work. In my opinion it would be better to place all possible main scripts in the project directory where `outer_main.py` is.
Comment: ```import sys

sys.path.insert(0, os.getcwd())``` You mean this? It works for me. But still looks clunky. Ye, I could store all possible main scripts in root folder, but it seems clunky too... I had no problem when I created venv by hands in root folder btw, but seeing so many unnecesary folders in root folder makes me anxious.
Answer: You either need an __init__.py file in the utils folder or also from ..utils import my_utils should work, since the folder utils is not in the folder where you have inner_main.py, so you need to specify it.
And that's why when you run it from the main folder it's working.
Comment: Created empty `__init__.py` in `utils` folder. Didn't help. Relative import doesn't help either. `__init__.py` never works for me for some reason... I don't even know what it does 0_0
Comment: Theoretically `__init__.py` should index the folder. That's odd that is not working with the relative import though.
Comment: Have you tried both the relative import and the `__init__.py` together?
Comment: Yes, I've tried both together.
Comment: And what about running it from the terminal inside the src folder, does that work?
Comment: No, doesn't work =( Again, I created empty `__init__.py` inside `utils` foder. changed directory via `cd src` with venv activated. Tried both relative and not relative imports. Did I do everything correct?

Btw, check my UPD 1 in question. It seems better, I guess.
Comment: Yeath it seems everything should work. If it works with the new solution keep that I guess. My only other idea would have been to install utils as package in the venv using pip and a `setup.py`, but then you have to install it every time you change something in the package.
Answer: Well, there is 3 ways.

Create import_fix.py file as I described above in UPD 1 and place it in .venv folder. You can run your code or debug.
Install Command Variable extenstion. Add new configuration to launch.json.

        {
            "name": "Python Debugger: Module", // you can use whatever name you like
            "type": "debugpy",
            "request": "launch",
            "module": "${command:extension.commandvariable.file.relativeFileDotsNoExtension}",
            "justMyCode": false, // to debug my breakpoints
        }

Select it. Press F5 or Ctrl+F5 to run the debugger. This extension provides correct module name relative to current working directory. If you manage to make it yourselves without third-party extension, please, let me know.

Create PJFOLDER/.venv/ANY-NON-EMPTY-NAME.pth file with ../ content (or absolute/relative path to your PJFOLDER if you have different structure). This will include PJFOLDER in sys.path despite you using virtual environment.

First way is much simplier to create, but seems odd and you need to import unnecessary file whenever you need to import your code in others directories.
Second way is about debugging only. Though it's more convenient, strict, you don't need separate file to fix imports, you don't need that little overhead. If you want to run only, then you need to type python -m folders_separated_by_dots.module_name. I belive, there is a way to create custom default command in VSCode to run file as module by default (maybe via tasks.json...), but I'm not smart enough. Still, debugger is enough for me.
Third way is ... perfect? Default debugger works, Run Python file works. Still, need to create this file and it's content and, I guess, VSCode should do this by default, but it's better than install VSCode extension and add new debugger configuration and forget about Run Python file (though it's nothing crucial). So, I guess, that's the answer for me.
Though you can add useful info in comments.
UPD: 3rd way is not working with Python 3.12.2 when .pth file has empty name, Read Security
Comment: Hi Eugene, glad to know you've found the solution to resolve this issue! you could click '✔' to mark it as an answer to change its status to Answered. It will also help others to solve a similar issue. See also [can I answer my own question..](https://stackoverflow.com/help/self-answer), Just a reminder :)
Comment: @MingJie-MSFT Ye, I know, but there is 2 days delay before I can mark my answer. 3 hours left :)


How to play Haydn Variation trills

Question: In Haydn's F minor variations for piano, how does one attack the continuous trills, one note after the other?
Comment: The 6 means the same it always does: "These notes must be shortened so that there are 6 of them to one beat rather than 4."
Comment: Are you asking about Haydn or Beethoven?
Comment: Haydn! there is a variation that has nothing but a continuous set of trills in the right hand.
Comment: For longer trills use 123231... or 32313231...
Answer: I'm going to assume you mean this part of Hob.XVII:6. This is from the Edition Peters score.

I think that the extension of the trill notation throughout the whole bar is simply a convenience to avoid having to write tr~~~tr~~~tr~~~tr~~~; it should be played simply as a succession of trills. Although what's going on with the fingering in bar 86, I have no idea.

How to play Haydn Variation trills


How @Value("#{servletContext.contextPath}") is resolved but @Value("${servletContext.contextPath}")

Question: In Spring Boot why @Value("#{servletContext.contextPath}") is resolved but @Value("${servletContext.contextPath}") isn't?
Answer: #{servletContext.contextPath} evaluates expression using servletContext bean, resulting in a call to ServletContext.getContextPath().
${servletContext.contextPath} resolves a property named servletContext.contextPath which normally is not present.
The SpEL is explained in details in Spring Framework docs, chapter 4. Spring Expression Language (SpEL).


Is there a more elegant way to write this Oracle SQL query?

Question: I practice SQL commands on HackerRank website and I came across this challenge:
https://www.hackerrank.com/challenges/weather-observation-station-12/problem
The query needed is this one:

Query the list of CITY names from STATION that do not start with vowels and do not end with vowels. Your result cannot contain duplicates.

My solution is:
SELECT DISTINCT city
FROM station
WHERE city NOT LIKE ('A%') AND city NOT LIKE ('E%') AND city NOT LIKE ('I%') AND city NOT LIKE ('O%') and CITY NOT LIKE ('U%') AND city NOT LIKE ('%a') AND city NOT LIKE ('%e') AND city NOT LIKE ('%i') AND city NOT LIKE ('%o') and CITY NOT LIKE ('%u');

This one works fine but it looks very ugly and verbose.
Is there an elegant solution to this problem?
Also please in Oracle SQL flavor.
Answer: You could use a regexp, like:
where not regexp_like(city, '^[aeiou]', 'i')

Regexp '^[aeiou]' means: 'a' or 'e' or 'i' or 'u' at the beginning of the string. The third argument, 'i', makes the match case-insensitive.
Please note that this only checks that the city does not start with a vowel. If you want to also check that it does not end with a vowel, then:
where not regexp_like(city, '(^[aeiou])|([aeiou]$)', 'i')

Comment: Please elaborat on the downvote. If something is wrong with this answer I am willing to improve it.
Answer: You could use:
WHERE UPPER(SUBSTR(city,1,1)) NOT IN ('A','E','I','O','U')
  AND UPPER(SUBSTR(city,-1,1)) NOT IN ('A','E','I','O','U')

or:
WHERE INSTR('AEIOU', UPPER(SUBSTR(city,1,1))) = 0
  AND INSTR('AEIOU', UPPER(SUBSTR(city,-1,1))) = 0

I try to avoid using regular expressions when there is a "traditional" alternative as regular expressions in SQL are slow!
Comment: SELECT DISTINCT city
FROM station
WHERE UPPER(SUBSTR(city,1,1)) NOT IN ('A','E','I','O','U')
    AND UPPER(SUBSTR(city,-1)) NOT IN ('A','E','I','O','U');
Comment: @MartinSmith True, I didn't read the spec, just the OP's attempt!  Fixed now.
Comment: Thank you! This also looks more simple than a regex. As a beginner this looks more clear to me and easy to understand.
Comment: This only checks the first character as it stands, see the dupe for also checking the last character
Comment: @Daniel you got it!


K-Means Clustering variable results depending on sort order of data

Question: I'm using PASWStatistics18 and K-Means clustering data that I'd previously clustered using an earlier version of SPSS... My problem is that I'm getting different cluster results depending on how the data file is sorted.  I can't remember this being an issue in the earlier versions of SPSS, but I can't repeat the same results, using the same data file, again!  Only by using the saved cluster centres can I get close to the original result.
Have others had similar isues?  Am I doing something wrong?
Comment: I don't know about PASWStatistics18 but it seems like either the initialisation of the first k centers is different for each run, or a mean is immediately updated after each datapoint (or some datapoints) assignation (like for the online k-means) .
Answer: This is a well-known property of k-means. The initialization is usually randomized, so you might even get (and in fact, intend to get) different results for multiple runs. It is a common best practise with k-means to run it multiple times, and choose the one with the minimum average distances (or by some other internal metric).
DBSCAN is mostly order independent. Only for fringe points that could belong to two different clusters, the cluster assignment is not stable (unless you extend DBSCAN to support multi-assignments or use some other stable tie-braking rule).
In general, it actually is even a good idea to shuffle your dataset before doing any kind of analysis. Say your method fails completely, and returns the data set in its original order. If the data was sorted before, the output will look meaningful. So always shuffle your data.
Comment: You will not get a different results using the classical k-means where the means are computed only after each pass over the hole dataset, unless you initialise the first k centers differently for each run, or you update the mean immediately after each datapoint assignation (like for the online k-means)
Comment: Well, it is a best practise to try different random initializations, instead of using the first k objects (which, when the data set is sorted, are biased). And it very often even results in quite different output, so it is sensible to try different initializations (whether or not MacQueen proposed that) ...
Comment: You're right, and in this case, if you have all the dataset available beforehand, it will be much better to use a seeding procedure that allow to initialize centers with datapoints that are far from each other, rather than pure random initialization.
Answer: Actually SPSS has acknowledged, going back at least to version 13 (ca. 2003) that cluster solutions will be affected by sort order.  This applies not only to K-means but to its other clustering algorithms as well.  You'll find this information in the Help files and possibly in the Tutorial.  When using cluster analysis in SPSS I always create a random number and sort by that first.
Comment: can you give link to current help file?
Comment: Hierarchical clustering doesn't depend on case order unless there are ties in the diatance matrix.


Question about S.A. Choudam's proof of Erdos-Gallai theorem

Question: In case (3) of S.A. Choudam's proof for the Erdos-Gallai theorem, the author claims "If $k + 2\geq p$, then $t = p - 1$." How does the latter follow from the former in the context of the proof?
The author also claims that $$\sum_{i=1}^{k} d_{i} = k^{2}-k + d_{k+1}$$
This seems to imply that $d_{k+1} = k$, but it's not clear to me why that would be the case
Here's a link to the proof
Answer: Assumption: The condition for all terms of the degree sequences has been omitted, as the graph is a complete graph, and solving it involves substituting the first position of difference as the second last term. This is just an assumption as we subtract 1 from the next term and would like to make it the last term which we subtract it from.
First we will look at the underlying assumption in the proof for case 3
$k \le t-1$ & $d_k = k$. There is atleast one more term in the degree sequence (otherwise it is the same case as the assumption) so $p \ge t+1$. Since $k+2 \le t+1$ and it is given that $k+2 \ge p$ $\Longrightarrow$ $p = t+1$.
Also for the second part of the question recall that $d_t$ was the first position of difference such that $d_{t+1} \lt d_t$ and $d_{k+1}$ is $d_t$ so it will have the same value as any other $d_i$ $(i \lt k)$ which is $k \Longrightarrow$ $d_{k+1}$ is also $k$.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Ext.js Cannot read properties of undefined (reading 'controller')

Question: enter image description here
enter image description here
I am constantly getting this error that it cannot find the controller
equipChkAttachFileController.js
        // 저장
        onSaveClick: function() {
            debugger;
            var me = this;
            var myForm = me.getView().down('#myForm').getForm();
            //var recipe_id = myForm.findField('recipe_id').getValue();
            var equip_pm_plan_id = myForm.findField('equip_pm_plan_id').getValue();
            var equip_code = myForm.findField('equip_code').getValue();

            var att_type = myForm.findField('att_type').getValue();
            var fileName = myForm.findField('fileupload').getValue();
            var setCrud = "I";

            if(fileName.length == 0){
                toastr.warning("업로드할 첨부파일이 존재하지 않습니다");
                return false;
            }

            var attFile = myForm.findField('attFile').getValue();
            if(attFile.length > 0){
                setCrud = "U"
            }
            myForm.findField('crud').setValue(setCrud);
            myForm.findField('att_doc_no').setValue(equip_pm_plan_id);
            myForm.findField('att_doc_no').setValue(equip_code);

            var msgConfirm = me.getView().저장하시겠습니까;
            var msgResult  = me.getView().파일업로드가완료되었습니다;

            Ext.Msg.confirm(me.getView().확인, msgConfirm, function(btn){
                if (btn == 'yes') {
                    myForm.submit({
                        url: '../saveAttachFile',
                        waitTitle: me.getView().연결중,
                        waitMsg: me.getView().데이터수신중,
                        success: function(form, action){
                            //me.myStore.reload();
                            toastr.info(msgResult);
                            //var recipe_id =  myForm.findField('recipe_id').getValue();
                            var equip_pm_plan_id = myForm.findField('equip_pm_plan_id').getValue();
                            var equip_code = myForm.findField('equip_code').getValue();
                            var parent_store = myForm.findField('parent_store').getValue();
                            Ext.getCmp('equipChkEdit').controller.getAttachFile(equip_pm_plan_id, equip_code);
                            //me.getView().close();

                            me.onRefresh();
                        },
                        failure: function(form, action) {
                            var message = Ext.ux.submitFailure(form, action);
                            Ext.Msg.show({title: action.failureType + '-side failure', msg: message, icon: Ext.Msg.ERROR, buttons: Ext.Msg.OK});
                        }
                    });
                }
            });
        },

This is the function that is giving error.
Ext.getCmp('equipChkEdit').controller.getAttachFile(equip_pm_plan_id, equip_code);
And this is the part that is returning error.
However the error doesn't make sense since I have a seperate js file named equipChkEdit.js and also the controller js file that is named equipChkEditController.js
The example solution I have has exactly the same structure and the same grammar
I have checked the file name and location. They're in the same folder and the names match since theyre all spelled accurately.
I tried Ext.getCmp('equipChkEditController') instead but realized that is actually wrong because .controller part is what makes up for the controller.
equipChkEdit.js
Ext.define('WithGMP.view.equipmaint.equipChkEdit', {
    extend: 'Ext.window.Window',
    requires: [
        'Ext.grid.column.Action',
        'Ext.grid.filters.Filters',
        'Ext.tab.Tab',
        'WithGMP.store.ComboStore'
    ],
    xtype: 'form-equipchkedit-window',
    controller: 'equipmaint.equipchkedit',
    reference: 'equipChkEdit',
    title: '설비 점검결과 등록',
    width: 800,
    height: 350,
    minWidth: 300,
    minHeight: 300,
    layout: 'fit',
    resizable: true,
    border: true,
    modal: true,

This is the equipChkEdit.js file where it defines its controller, which is a correct way of defining it because this is how all the example solutions define their controllers.
equipChkEditController.js
    //첨부파일 조회
    getAttachFile: function(equip_pm_plan_id, equip_code) {
        var me = this;
        var attachImageStore = Ext.create('WithGMP.store.recipe.attachImageStore');

        attachImageStore.load({
            params: {equip_pm_plan_id: equip_pm_plan_id, equip_code : equip_code},
            callback : function(records, operation, success) {
                if (!success) {
                } else {
                    //attImagteBtn.Text = Convert.ToString(dt.Rows[0]["IMGCOUNT"]) + " 건";
                    //myForm.findField('attImagteBtn').setValue(records[0].data + " 건");
                    me.getView().down('#attFileBtn').setText(me.getView().첨부파일 + " " + records[0].data + " 건");
                }
            }
        });
    },

This is the equipChkEditController.js that defines the function getAttachFile, which is used in the part that gives the error
it is correctly defined and spelled
I have no clue why
Ext.getCmp('equipChkEdit').controller.getAttachFile(equip_pm_plan_id, equip_code);
this line is being able to find the controller when executed.
Comment: `Ext.getCmp` looks up a component by id, not by file name. Check documentation how to use it.
Answer: Overall it would be great if you would create a fiddle, so that others can see how the components work together. You are trying to call a window controller from an other window?
There are 6 possible solutions:

See the comment from Peter Koltai:

getCmp Documentation: Link
You have to use an ID for the component. Typically I would not recommend to use an ID. The main reason is, that you might want to open several windows and an ID has to be unique.

Use alternate ways to find the component, which is in case of a window not really easy, because they are not part of the component hirachie.
But in case you defined a parent component you could use reference OR use up and down.:

const editWindow = me.lookupReference('equipChkEdit'),
      upDownEdit = me.getView().up('someParent').down('aField');

You should never, ever call upon a controller directly, because you should never take it for granted that a component exists. If the component does not exist, the controller is not available. Instead fire an Event and listen to it inside the controller, so that the viewController can alter the view.

equipChkAttachFileController.js

    Ext.fireEvent('attachedfilechange', [equip_pm_plan_id, equip_code]);

equipChkEditController.js
    listen: {
         global: {
             attachedfilechange: 'getAttachFile'
         }
     }

You could make use of a utility class or mixin. This works best, if you use the functionality at several places and not only once.

Ext.define('WithGMP.util.Attachments', {
    singleton: true,

    fileAttached: function(equip_pm_plan_id, equip_code) {
        ...do something
    }
});

Call the util function
    WithGMP.util.Attachments.fileAttached(equip_pm_plan_id, equip_code);

Use databinding. If you bind the data to a parent component you can access it from two different windows. To do this you have to define the windows with a parentViewModel.

Last but not least you might have not created the view equipChkEdit yet.


Accessing value from expression

Question: public Method1(Expression<Func<T, TProperty>> valueToCompare) {
    //Examine expression
}

public Method1(TProperty valueToCompare) : this(x => valueToCompare) {}

and i run them like this
Method1(x => 1);

and
Method1(1);

If i examine the expression when the first overload is called then I get a constant expression. However when I examine the second one I get a member expression.
The question is how do I get access to the value '1' no matter which overload i call.
Update1:
I used to do this until I realised the didn't both return the same thing.
if (valueToCompare.Body.NodeType == ExpressionType.Constant)
{
    var constant = valueToCompare.Body as ConstantExpression;
    ValueToCompare = constant != null ? (TProperty)constant.Value : default(TProperty);
}

What will i get if I compile it?
Tried to do this but it didn't work.
if (ValueToCompare .Body.NodeType == ExpressionType.MemberAccess) {
   var member = ValueToCompare .Body as MemberExpression;
   if (member.Expression.NodeType == ExpressionType.Constant)
   {
       ConstantExpression constant = member.Expression as ConstantExpression;
       ValueToCompare = constant.Value;
   }
}

Cheers.
Answer: Are you happy to just compile the expression and run it? That would seem the easiest solution to me...
Alternatively, you could make your overload taking a TProperty explicitly construct a constant expression, rather than using a lambda expression. It really depends on what you're trying to achieve.
As an example of the latter approach, you'd write something like (untested):
public void Method1(TProperty valueToCompare) : this(x => valueToCompare)
{
     Expression constant = Expression.Constant(valueToCompare,
                                               typeof(TProperty));
     ParameterExpression parameter = Expression.Parameter(typeof(T),
                                                          "t");
     Expression lambda = Expression.Lambda<Func<T, TProperty>> (constant,
                                                                parameter);
     Method1(lambda);
}

Comment: The ParameterExpression is just to represent the parameter for the lambda expression; "t" is just the name. In other words, it's building an expression like (t => 1)
Comment: Seems to have worked. Thanks heaps.
Also what is the ParameterExpression for and why is it set to "t"?
Comment: Thought it might have been. Cool. Thanks.
Answer:
The question is how do I get access to
  the value '1' no matter which overload
  i call.

You don't, as you've discovered.  Not without compiling and executing the expression tree to produce its value.
Remember, the purpose of an expression tree is to capture the compile-time information about the expression and present it at runtime, not the runtime value that evaluating the expression produces.
In your example, you have two different expressions -- one is a constant, one is an outer variable of a closure.  Outer variables are represented by fields, so you get a field access expression. The expression tree you get represents the expression that you put in the lambda.
Perhaps you can describe what you are really trying to do; there is probably a better way. If what you want is the value, why do you need an expression tree at all?

Accessing value from expression


Question about Compact metric space

Question: Please why $$\Delta_p=\lbrace (t_0,...,t_p)\in \mathbb{R}^{p+1},t_i\geq 0, \sum_{i=0}^p t_i=1\rbrace$$
is a compact metric space ?
Thank you
Comment: No i think that is a bounded set it is a convex hull !@HaraldHanche-Olsen
Comment: I would like to know that as well, for as far as I can tell, this is an unbounded set.
Comment: Well, it contains $(x,1-x,0'\ldots,0)$ for *any* real $x$. That looks unbounded to me. Edit: I expect the condition $t_k\ge 0$ for $k=0,\ldots,p$ has been left out of the problem statement.
Comment: Why is bounded? $(-n, 0,...,0,n+1)$ is in your space. Are you thinking in $t_i\ge 0$ ??
Comment: Standard p-simplex is usually defined as $\Delta_p=\lbrace (t_0,...,t_p)\in \mathbb{R}^{p+1}, \sum_{i=0}^p t_i=1, t_i\geq 0, i=1,\dots p\rbrace$. Is this what you wanted to write? Then, it is compact.
Comment: @alans yes i edeted my question burt why it is a metric space ?
Comment: Any subset of a metric space is a metric space, by restricting the metric of the larger metric space – in this case, $\mathbb{R}^{n+1}$ – to the subset. Of course, the implicit assumed metric on $\mathbb{R}^{n+1}$ must be the Euclidean metric: $d(x,y)=\sqrt{\sum_{j=0}^n|x_j-y_j|^2}$.
Comment: It's a closed subset of the compact set $[0,1]^{p+1}$.
Answer: $\Delta_p=\lbrace (t_0,...,t_p)\in \mathbb{R}^{p+1}, \sum_{i=0}^p t_i=1, t_i\geq0\rbrace$ is bounded since $0\leq t_i\leq 1$.
It's closed. Let $t_n=(t_0^n,...,t_p^n)\in \Delta_p$ s.t. $t_n\to t=(t_0,...,t_p)$. Then $1=\sum_{i=0}^p t_i^n\to \sum_{i=0}^p t_i=1$ and $t_i\geq 0$. So $t\in \Delta_p$. Hence it's closed.
Hence it's compact. And it's a metric space with induced metric from $\mathbb{R}^{p+1}$
Comment: @Vrouvrou Any subset of a metric space is a metric subspace with induced metric
Comment: and why metric space please ?
Answer: It is a hyperplane, right? Hence it is unbounded, hence not compact.
Comment: No, you have missed the restriction $t_i\geq 0$; and since the $\sum_i t_i=1$, none of the $t_i$ can exceed $1$.
Comment: True, I missed the restriction.
Comment: But then, indeed, $ 0 \leq t_i \leq 1 $ and hence $ \Delta_p$ is contained in the corresponding $p+1$-dimensional cube, thus bounded. And it is also the intersection of this cube wuth the hyperplane, both of which are closed. Hence, it is compact.
Comment: Indeed. Hence my comment on the original question. We are arriving at exactly the same conclusion, I think. :)
Comment: Exactly! Thanks.

Question about Compact metric space


Finding the Intersection Value of a Linear Equation and a Power Function with a Negative Exponent

Question: Real-life scenario, not theory, homework, etc. My math is so rusty it's basically powder at this point. No need to beat me up; I am already beating myself up for not understanding this very simple problem.
I want to find where a power function line and a linear line intersect. I know the answer is about 1.15243535589047 but I want to know how to do this with simple pen and paper (so-to-speak).
Solving for x: $-4.5657x + 265.58 = 300x^{-1}$

My thought process:
The place where the two lines intersect is where the $x$ in the linear equation equals the $x$ in the power equation. Or, the linear equation minus the power equation should equal zero.
My attempt:
\begin{align}
-4.5657x + 265.58 = \frac{300}{x^1}
&\implies \frac{x^1}{1} (-4.5657x + 265.58) = \frac{300}{x^1} \cdot \frac{x^1}{1} \\
&\implies x^1(-4.5657x + 265.58) = 300 \\
&\implies -4.5657x^2 + 265.58x = 300 \\
&\implies -4.5657x^2 + 265.58x -300 = 0.
\end{align}
Now to test:
If I plug in $1$ for $x$, I get $-38.9857$. If I plug in $1.15243535589047$, I get $0.0000425483196977439$. Since this number is very close to zero, I take that to mean $1.15$ is the $x$ value where both lines intersect (roughly). But I had to use solver or an optimizer function to figure this out.
My question:
How do I take these two equations and set them up so the output will tell me that $x = 1.15$ ? I guess I'm saying I want to find where the two equations equal the same number.
Comment: The last equation you have is quadratic in $x$, which means that you are in luck!  There is a well-known closed-form solution to such equations, provided by the [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula).
Answer: solve the quadratic equation by the formula
$$x_{1,2}=-\frac{b}{2a}\pm\frac{1}{2a}\sqrt{b^2-4ac}$$
with your values i get
$$x\approx 1.15244$$
$$x\approx 57.0161$$
Comment: I can't believe I was asking about the quadratic formula without even knowing it. I guess a perfect example of why they teach us this in school but I didn't realize when to apply it. Thank you!
Comment: ok nice that your Problem is solved now, have a nice evening!
Answer: $x$ is definitely non-zero, this means your steps in setting up the quadratic is correct, which is multiplying both sides by $x$.
You don't really have to plug in values to test and you can instead use the quadratic formula for solving questions in the form \begin{align}ax^2+bx+c=0\end{align}
The formula is given as:
\begin{align}\frac{-b\pm\sqrt{b^2-4ac}}{2a}\end{align}
Plugging in the values for a, b, c and you should get:
$x=57.016082234325$ and
$x=1.1524351890714$


Triangle inequality for an obtuse triangle

Question:
$\alpha < 45^\circ$, how to show that
1) $|AB+AC|>|DB+DC|$?
2) $|AB+AC|>|DB+DC+DA|$?
Comment: Norman: I've added a counterexample to the inequality labeled 2) in the OP.
Comment: @coffeemath any idea
Comment: Norman: See answer below. I only tackled inequality 1), and my method did not use $\alpha<45$, so I wonder if you know of a case where 1) fails for larger $\alpha$.
Answer: For 1), note that the point $A$ is on an ellipse with foci at $B,C$ with length sum $|AB|+|BC|.$ The equality of the two marked angles $\alpha$ means that the ray $\vec{AD}$ is perpendicular to the ellipse at $A$, pointing into the ellipse. If as suggested by the diagram the point $D$ is in fact interior to the triangle $ABC$, then it follows that $D$ is interior to the ellipse, so that the length sum $|DB|+|DC|<|AB|+|BC|.$
Note that this argument didn't use $\alpha <45^{\circ}.$ Do you know of a case where inequality 1) fails when $\alpha$ is more than 45 degrees?
I haven't come up with anything (yet) on inequality (2).
NOTE on further looking at it, you don't need equality of the angles marked $\alpha$ in the diagram, or any inequality on the two angles there. All you need is that the point $D$ is interior to the triangle $ABC$, which the diagram clearly intends. Given any ellipse with foci at $B,C$, and any point $P$ on that ellipse, the triangle $BCP$ lies entirely in the interior of the ellipse, except for the point $P$ itself. It follows that any point $Q$ interior to triangle $BCP$ (so other than $P$) will have smaller length sum to the foci $B,C$ than does the point $P$ on the ellipse.
Inequality 2) counterexample:
Let $A=(0,0),B=(-1,9/10),C=(1,9/10),D=(0,8/10).$
Then $\alpha=\arctan(9/10) \approx 41.98^\circ,$ so that fits, and it's easy to see that $D$ is interior to triangle $ABC$. But computing AB+AC gives $\sqrt{181}/5 \approx 2.69072$, while computing the right side $DB+DC+DA$ gives $1/8+\sqrt{101}/5 \approx 2.80998,$ so that in this example the inequality stated in the OP as 2) turns out to have the right side greater than the left. There are also cases where the inequality does hold, e.g. if $D$ above is replaced by $(0,1/2)$. This shows there isn't an inequality either way between these two quantities, under the given assumptions.


Why use LSTM or in general RNN instead of plain NN?

Question: I understand that in LSTM, there are 3 gates to help keep the memory. But why do we use LSTM instead of NN in the first place?
For example, in a LSTM, my features are just 1-D, time steps is set to be 60, which means the longest memory my LSTM can remember is just 60 days ago, you can't use any information 73 days ago to predict today's target.
But in a plain NN, we can reconstruct the 1-D variable into a 60-D variables with the other dimensions being the variable's value 1-day ago, 2-day ago, ..., 60-day ago. And we predict today's target variable.
What is the difference here? We are all just using 60-day information to predict a single variable.
Answer: A couple of reasons:
First, you might not know how long your sequence will be ahead of time. RNNs let you use a variable length input.
Second, RNNs are a good way to do parameter sharing between different time steps. Instead of having to learn how to extract useful information from each time step separately you can reuse the same parameter matrix recurrently.
Comment: What do you mean by 'Rnns let you use a variable input length input'? In the LSTM in keras, there is a parameter input_shape=(batch_size, time_steps, n_features). Do you mean by picking different time_steps each trial? And check the results on validation set to pick the best time_steps?
Comment: The time_steps that you are specifying there is the maximum number that you expect to see. Not all the sequences need to be the same length. We use LSTMs a lot in speech recognition and translation. Each sentence is a different length and the LSTM handles it perfectly.
Answer: First to clarify: There are 3 types of NNets used for this type of problem. Feed forward NNets (i.e plain NN), Recurrent NNets (RNN), and LSTM, which is a more advanced class of RNN.
The problem with plain NN is that they don't have any memory. Let's take your example of:

But in a plain NN, we can reconstruct the 1-D variable into a 60-D variables with the other dimensions being the variable's value 1-day ago, 2-day ago, ..., 60-day ago. And we predict today's target variable.

Now say there are recursive relationships between you data points, so that the Data(Today) = f[Data(Yesterday)] = f[f[Data(2 Days ago)]], etc...
A plain NN can learn the relationship between these data points during the training phase, but once the training is done, it has no way of applying such recursive relationships for future data points because the data between the inputs and the outputs flows in only one direction.
Putting it another way, a plain NN can predict the value for today. But if you wanted to predict the target variable for 2 days, 3 days, or N days ahead (see one-step ahead vs. multi-sept forecasting) - then the NN has no way of predicting those values, since it has no way of feeding the forecast for today back as an input to generate a forecast for tomorrow and the day after.
RNN and LSTM on the other hand, have feedback loops going from the outputs back to the inputs, which allow them to perform multistep forecasting.
Moreover, LSTM have additional properties that allow them to learn long term dependencies, whereas regular RNN can only learn short dependencies.


Dividir um botão para alterar o background de parte dele

Question: Eu gostaria de fazer igual neste botão no caos, dividir para utilizar o 4 com o background cinza e o restante no branco comum, Obs. estou utilziando o botão do Bootstrap 4.
Answer: Cara isso tem na documentação... Se chama button-group https://getbootstrap.com/docs/4.0/components/button-group/
Exemplo de aplicação

<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />

                <button type="button" class="btn btn-secondary">4</button>

                <input type="text" class="border px-2 border-right-0">
                <button type="button" class="btn border border-left-0">←</button>


Gradient approaching to zero

Question: Either prove or disprove  by counterexample-
Let $f:R^n\to R$ such that $f$ is differentiable on $R^n-\text{{0}}$ , $f$ is continuous at $0$ and $\lim_{x\to 0} \nabla f = 0$ , then show that $f$ is differentiable at $0$. Actually for single dimensional case I can prove it's true by mean value theorem but I don't feel like it's true for $n>1$ but still can't find a counterexample yet. Can somebody help me?
Answer: Let  $h \in \mathbb R^n, h \ne 0$. By the mean value theorem for functions with $n$ variables, there is $z(h) \in \{th: t \in [0,1]\}$ such that
$$f(h)-f(0) = h \cdot \nabla f(z(h)).$$
By Cauchy - Schwarz
$$|f(h)-f(0)| \le  ||h|| \cdot ||\nabla f(z(h))||$$
Hence
$$\frac{|f(h)-f(0)|}{||h||} \le ||\nabla f(z(h))||.$$
This shows that
$$\frac{|f(h)-f(0)|}{||h||} \to 0$$
as $h \to 0$. This means that $f$ is differentiable at $0$ and $f'(0)=0.$
Answer: Fix $ \epsilon > 0 $; by hypothesis there exists a $ \delta > 0 $ such that $ \| \nabla f (w) \| \le \epsilon $ whenever $\|w\|\le \delta$. So by the Mean Value Theorem $$ \|f(w) - f(0) \| \le \|\nabla f (t w) \| \|w\|\le \epsilon \|w\|, \quad t \in (0,1) $$which implies the differentiability of $f$ at $0$.
Answer: With the one-dimensional case plus $\nabla_xf\stackrel{x\to 0}\longrightarrow 0$ you can prove that the partial derivatives exist at $0$ and that they are all $0$. Thus, you have proved that the partial derivatives exist in a neighbourhood of $0$ and that they're continuous at $0$. This implies differentiability at zero (this is sometimes called the "total differential theorem", though some authors refer to it with the unnecessary hypothesis that the partial derivatives should be continuous in a neighbourhood of the point of interest, instead of the single point).

Gradient approaching to zero


Dúvida com relacionamento de tabelas Banco de Dados

Question: Boa tarde, estou desenvolvendo um sistema para meu aprendizado e me deparei com uma situação onde fiquei na dúvida.
Tenho a tabela no banco em que são gravadas as perguntas.
Tabela pergunta :
-IdPergunta;
-IdUsuários;
Tanto o que perguntou, quanto os que responderam gravam nessa tabela.
Minha dúvida é a seguinte, devo criar uma tabela resposta para gravar as respostas ou gravo na tabela Pergunta mesmo ?
Comment: Não sei. Depende do que precisa fazer com essas informações, depende de outros pontos do banco de dados, depende do conceito exato que isso significa. Tem que avaliar as vantagens e desvantagens de fazer de um jeito ou de outro.
Comment: uma dúvida que surgiu enquanto desenvolvo a nível de aprendizado ...
Comment: As perguntas podem ser respondidas mais de uma vez? Se sim, já é um forte indicativo que terá que criar uma nova tabela - se for trabalhar com normalização, é claro. Assim como o bigown disse, você precisa fazer os levantamentos necessários. Dos dois jeitos estará "certo".
Answer: A resposta é: depende.
Uma dica muito boa quando se vai fazer o desenho de uma tabela no banco de dados é perguntar quais são suas entidades de trabalho e quais relacionamentos essas entidades tem entre si. Esse modelo de abstração é o modelo entidade relacionamento, MER.
Ao pensar em um relacionamento, pense também qual a aridade desse relacionamento. Por exemplo, se um usuário pode realizar múltiplas perguntas e pode escrever múltiplas  resposta, cada pergunta podendo ter várias respostas, temos o seguinte modelo:

Note que não coloquei os atributos no modelo, isso é um outro passo.
As chaves primárias, muitas vezes, podem ser chaves artificiais; nos demais casos, podemos criar as chaves artificiais para fazer a ligação, respeitando apenas a unicidade. Esse artigo explica aqui um pouco do que é a chave artificial.
Após saber quais são suas entidades e como elas se relacionam, transformaamos o MER em um modelo mais próximo do banco de dados relacional, o Modelo Relacional, MR. O modelo relacional é um jeito de se escrever estruturas de tabelas graficamente. No phpmyadmin é possível você criar tabelas usando esse modelo através de uma interface bem divertida de se mexer. Achei essa resposta no SO internacional sobre como habilitar essa funcionalidade no phpmyadmin.
O MR é composta de tabelas e ligações/chaves estrangeiras primariamente. Uma tabela é uma coleção de dados bem conhecida, uma tupla cujas posições são nomeadas. Por exemplo, quando se diz que um usuário precisa ter um nome e uma pontuação, ele pode ser representado pela tupla ('Fernando', 64), sendo a primeira posição da tupla o nome do usuário e a segunda posição a pontuação do mesmo usuário; cada coluna da tabela é representada por uma posição na tupla.
Eu gosto de usar a seguinte técnica para converter de MER para MR:
1-> se o relacionamento de A--B é de 1 para 1, então coloca os atributos de B em A
2-> se o relacionamento de A--B é de 1 para 0..1, então coloca os atributos de B em A apenas caso exista dados pertinentes, sendo todos nulos caso não exista B
3-> se o relacionamento de A--B é de 1 para 0..n, então coloca em B uma chave estrangeira para A
4-> se o relacionamento de A--B é de 0..n para 0..n, então crio uma tabela de ligação que contém chave estrangeira para A e chave estrangeira para B
5-> toda tabela advinda de uma entidade tem uma chave artificial
6-> todo atributo da entidade vira uma coluna na tabela

Assim, o MER postado acima se transforma no seguinte MR (assumindo que resposta tem texto, pergunta tem texto e usuário tem nome e pontos):
PERGUNTA(pk_pergunta, fk_usuario, texto_pergunta)
RESPOSTA(pk_resposta, fk_usuario, fk_pergunta, texto_resposta)
USUARIO(pk_usuario, nome, pontos)

Claro, você poderia modelar de outra maneira as entidades. Você poderia dizer que existem posts, sendo que um post pode ser de abertura ou ser um post de resposta, desde que o post de resposta se referencie a um outro post:

Que se transforma no seguinte MR:
POST(pk_post, fk_usuario, fk_post_original, texto_post)
USUARIO(pk_usuario, nome, pontos)


Compact and Weierstrass

Question: If $f:\mathbb{N}\rightarrow{\mathbb{R}}$  :
$f(x)=0 $ , if  $x=1$ and $f(x)=\dfrac{1}{x-1}$ if $x>1$
(i) Proof $ f(\mathbb{N})$ is a compact set.
(ii) Is Weierstrass's theorem  applicable?
$f^{-1}:f(\mathbb{N})\rightarrow{\mathbb{N}}$
Thanks!
Comment: What have you tried? For $(i)$, use Heine-Borel. Regarding $(ii)$, Weierstrass had a lot of theorems, which one do you mean?
Comment: Applicable to what? $f$ or $f^{-1}$?
Comment: is for $f^{-1}$
Answer: See that the set $f(\Bbb N)$ is closed and bounded thus conclude that it is compact. To see boundedness of $f(\Bbb N)$ see that $f(x) \leq 1 $ forall $x \in \Bbb N$.
$f(\Bbb N) = \{0,1,1/2,1/3, \cdots\}$. It is easy to see that $f(\Bbb N)$ is a closed set in $\Bbb R$ since $0$ is the only limit point of the set and it is in the set.
Comment: How proof closed?
Comment: you're right thanks.
Comment: Thanks for accepting my answer
Comment: I have not understand your question of part 2

Compact and Weierstrass


Top-down music learning

Question: Most musical schools start with a bottom-up teaching eg. Czerny etudes for the dexterity and the velocity of fingers. However, teachers usually go through all the etudes before moving on towards real works.
While I agree with the necessity of such basic practice and education, I wonder whether there exists an approach that is rather top-down based and goes like "OK, here's this piece; now if you want to be able to play this part, you need to practice the following exercises: ".
Answer: Interesting - there is a 'top down' for guitar music. I'm thinking of popular guitar tunes, rather than classical guitar.
People who self-teach generally start off learning chord shapes which will enable you to strum your way through a song. A lot of guitar tutorials work this way.
You can also learn "basic" chords which will work, and add more intricacy as you get more confident.
If you then want to move on to the more difficult/intricate parts, eg a solo or some intricate picking, you can tackle that as a separate exercise.
Learning scales (eg good ol' pentatonic as a starting point) and riffs will help with the dexterity for more intricate parts.
Others will answer with more detail for piano/other instruments, but I think what I say here is true for guitar.
Comment: Not really - I'm talking about guitar (for which that would work). OP hasn't  stated a particular instrument, although the etudes is a piano piece. I couldn't really comment on how to go about piano, and there might be (probably are) reasons why going for the standard ways of doing things are best, although I'm a big advocate of innovation. I'm guessing that getting comfortable with your own chord fingering on a piano could amount to getting into unhelpful habits. I guess my point is that it might be different for different instruments, hopefully I'm leaving room for that.
Comment: I'm a guitar player and I teach guitar for a living, but I come from a long line of concert pianists and am familiar with the Czerny etudes. The goal of them is primarily to get the left hand (playing the chords) synchronized with the scales played by the left hand. They supposedly provide a very solid foundation for playing classical music. If you don't want to play classical music make sure you have/ find a teacher who plays the genre you like.
Comment: So you suggest to try to play a particular piece, and eg. in the case of a piano, let the fingering come as comfortable as possible and not let the worldwide taught fingering standards confuse the pupil?
Comment: Yes, it's clear, thank you. Yes, basically I'm approching the subject from the perspective of the piano, I didn't think the efficiency and the unhelpfulness of certain habits might be instrument variant.
Comment: I think there's possibly more scope for getting into a fingery knot on a piano than on guitar. My understanding of piano is limited though. Most simple/popular guitar chords fit the hands in a fairly intuitive way so I think it's probably easier to self-teach fingering on guitar, although there are of course well understood techniques & hand positioning that make things easier.
Answer: There is no need to train on exercises only. My piano teacher gives real songs and exercises in somewhat 50 : 50 % proportion.
Many really nice piano pieces like "Love me Tender" or "Jingle Bells" or "Let it Be" melody line are actually not so difficult to play. There is no lack in "easy piano" books with adapted, simplified versions of really great, real songs. After you master the simplified song (one hand only, for instance), get and try the more complete version.
Of course, such song will never sound like performed by the professional band. The band uses more instruments, additional chords and melody insertions and the like. But hopefully this is not your purpose.
Comment: I like this approach. One question: in case of self-teaching, how does one "extract" and isolate the necessary technique required for a certain piece?
Comment: +1, there's **nothing** wrong with making a piece of music your own and playing it *your* way - unless you're being examined (I'm self taught, I don't play to pass tests). Some songs my left hand plays the song's bassline, some songs my left hand plays the chords, some songs it's a mixture.
Comment: @András Hummer adapting a complex piece to make it simpler seems advanced, you need to buy such notations, or maybe find on the web.
Answer: I once asked a famous violinist this same question, and this is what he said to me:
If you only learn the technique for a certain piece, you need to begin anew with every piece that you learn.  If you achieve technical mastery before the music, learning the piece becomes a matter of applying your technique.
All that said, it's not fun drilling etudes for hours with no music.  So I agree with others' answers in saying that there should be a mix (ideally music that reinforces the learned techniques, or perhaps concert etudes).
Comment: I would add that with every new piece the amount of new technique required to learn will eventually start decreasing.
Answer: False premise.  Music teachers DO start with real music, whether it's a made-up 'Dance of the Goblins' for youngsters or 'Minuet in G' for adults.  Alongside these, there will be some work on scales and arpeggios.  I've never known a teacher work through Czerny before introducing real music.
So, yes, there is an approach that includes real music from the outset.  And everyone uses it.
Answer: Something to consider, when using a "top-down" approach:
When studying pedagogics, we learned about two different approaches:

Learning theory first, then doing experiments to apply it.
Doing experiments first, then learning the theory behind it.

If I understand correctly, the "top-down" approach you describe would be similar to approach 2. First attempting to do a practical task, then learning the theory behind it to be able to understand and complete the practical task. Experiments and tests done with a whole lot students show that approach 2 gives higher motivation, and higher learning rewards. If I remember correctly, also the long-term learning, and learning portability increases. Meaning that the material was remembered for a longer time, and was more likely to be utilized in new situations.
Traditional learning usually prefers approach 1, but this can possibly cause low motivation, and only short-time learning.

Top-down music learning


How to deploy a Firebase app with firestore and express app to be globally accessible?

Question: We have successfully built a Firebase application with Firestore, functions, hosting, auth. Now we are working on an Atlassian confluence integration and a global rollout. The confluence plugin rest endpoints are served by an express app.
What is the proper way to achieve a unique url in all countries around the globe, e.g. https://myapp.com/confluence/api with no or at least acceptable latency to serve health checks as well? Is a hosting rewrite to function serving the express app enough? Do we need to manage any replication to regions around the globe by ourselves?
Thanks a lot for any advice.
Answer: You can use the Firebase hosting to connect a custom domain:

use a custom domain (like example.com or app.example.com) instead
of a Firebase-generated domain for your Firebase-hosted site.
Firebase Hosting provisions an SSL certificate for each of your
domains and serves your content over a global CDN.
Note the following about connecting custom domains:

Each custom domain can only be connected to one Hosting site.
Each custom domain is limited to having 20 subdomains per apex domain, due to SSL certificate minting limits.

When Firebase verifies domain ownership, an SSL certificate is being provisioned for your domain and it's being deployed across Firebase global CDN (content delivery network). This delivery network cashes your content on Firebase edge servers' SSDs to ensure quick content delivery and low latency globally.
Comment: Thanks. What about firestore and functions content?
Comment: @Benjamin for Cloud Functions URL, please refer to the [Use custom domain for Google Cloud Function](https://stackoverflow.com/questions/45850375/use-custom-domain-for-google-cloud-function) thread. Let me know if it helps
Comment: The Firebase Hosting in front of the app works fine. However, we wondered about the global latency. For example, if the function/app is located in the US, an asian client might be pointed to the right function by the Hosting, but is served from the us and might experience an according latency.