Predicting sequence of integers / binary values

Question: The data I am working with are sequences of binary values (0 / 1) which generally have a pattern - a longer sequence of 1's followed by a shorter sequence of 0's, for instance:
1 1 1 1 0 0 1 1 1 1 1 0 0 0
The goal is to predict the next value based on the entire sequence.
Each sequence has 10 to 20 values in it and the prediction should be made for each sequence individually by using all its available data. I realize there are few data points to work with so my question is: are any statistical methods than could achieve this type of prediction? I've never had to work with sequence data, so I don't know how to approach this.
Comment: What is your goal here? Do you have a series of historical values and want to predict a few steps into the future based on that? Or do you want to model that time series so that you can artificially produce timeseries that behave in a similar way (to run simulation on etc.)?
Comment: @user7019377 : Added a new line to clarify that I'd like to predict the next value in the sequence and that it should be predicted based on all the values in the sequence up to that point.
Comment: Are these completely unknown signals from outer space.... Or, is there any possibility to have additional 'information' about the (currently abstract) time sequences? All pieces of additional information, not just the raw variables, can change the probability of the next 0 or 1 and improve the success rate of the predictions.
Comment: @MartijnWeterings - all additional information available is dependent on the 0/1 values; the data shows behavior for real people, but the reasons for them performing (1) or not performing (0) a certain action cannot be known through the data.
Comment: BogdanC, can you explain a bit more? Quantitative analysis relies on assumptions. There is much more that can be done if it is known what those 1's and 0's are, where they come from, what they mean, how they are produced, what the order in the sequence means, what relations are allowed to exist between different numbers in a single sequence and between different sequences. Presenting some numbers, without meaning, and asking consult for statistical methods is a minimal way to make something out of it and only gives you general solutions and advice.
Answer: One approach you could consider is trying to learn a Markov Chain (MC) to represent each sequence and then predict future values based on this MC.
MCs are a way of representing types of learning automata (LA) and can be used when the subsequent state of a system depends solely on the current state. They can be intuitively represented diagrammatically:

This is a very simple LA. It has two states: one where the last number seen was a 1 and one where the last number seen was a 0. There are transition probabilities between the different states noted as well. For example, when the LA is in state 0 it will stay in state 0 with probability $x$ and will move to state 1 with probability $1-x$. This can also be shown in the form of a matrix:
$\begin{bmatrix}x & 1-x \\ 1-y & y\end{bmatrix}$
Estimating from your example sequence, $1 1 1 1 0 0 1 1 1 1 1 0 0 0$, we might say that in this case $x = 0.6$ and $y = 0.77$.
This kind of solution can also be extended; we could learn an LA with more states and more "memory."

or
$\begin{bmatrix}w & 0 & 1-w & 0 \\ x & 0 & 1-x & 0 \\ 0 & 1-y & 0 & y \\ 0 & 1-z & 0 & z\end{bmatrix}$
This LA has four states: 00, where two or more consecutive 0s have been seen; 0, where only one consecutive 0 has been seen; 1, where only one consecutive 1 has been seen; and 11, where two or more consecutive 1s have been seen.
We can again estimate the corresponding probabilities from your example sequence and might say that $w = 0.33$, $x = 1$, $y = 1$ and $z = 0.71$.
Comment: could you show how to the matrix transformation (squared of 2 dimensions, x, y) is applied to the vector in input 11110011111000 ?
Answer: One way to do it is through classification. You need a binary output, which is exactly what classification algorithms can provide.
You can construct a data-set out of this time series. Assume you have $n$ values right now. Further assume that you think the value in $n+1$ can be determined based on the $t$ last values between $n$ and $n-t+1$. Like this, you have $n-t+1$ observations (all except the first few in the time-series because there would not be enough lag observations for them) with $t$ binary variables each (all ordered in the same way starting from the then current value towards the lag values). You can construct all sorts of classifiers based on this data-set, compare their performance and choose the best one to predict. $t$ is a parameter to be tuned.
This will always be a high risk forecast though. Since you basically want to forecast only one number which can only have two values. Per definition, this is going to be all or nothing.
If the costs associated with falsely predicting a 0 are different from the costs of falsely predicting a 1, you can reflect that and bias your algorithm towards predicting more readily the value that would be more expensive to miss.
Answer: I may worth to try a neural network for classification, specifically an LSTM is doing quite what you would like to achieve.
It could be used as follows:

LSTM need input sequences to be the same length. This could be solved by padding the data by adding leading characters. The padding character should be not 0 or 1. Another solution is to use batch size 1 without resetting the status after each batch.
Once padded data should be encoded using the one hot method. You can use 3 categories: 0, 1 and the padding character.
The last binary value of each sequence should be used as a target, the rest as input. Of course the padding character will never be the target because we padded on the front.
Stacking 2 LSTM will do a better job
Your network could look like: Input->LSTM->LSTM->Dense->Dense->Output
The more data you have the better it will learn the patterns. Such a network will learn very easily that the padding character is never the output, so don't worry about it.
Comment: I like the idea you're suggesting, however I don't have extensive experience with neural networks in general and LSTM in particular. I will pursue this idea when I have the time though.
Answer: Using a Neural Network (NN) would be a solution. NN learn/train on dataset to target dataset, and then make a forecast on that particular database set. NN are very good at processing binary data (some of them generalize input data for better processing).
There is no need to know what binary data represent or how they are translated back (using non-generalized data leads to overwhelming complex models, a beginner overkill).
Some Open Source Statistical Software Packages for Mining Data feature learning NN like Orange/Quasar, JASP, KNIME to name a few, to start on. In general, the more dataset the better outcome. There are more heavy-weight software packages that feature learning NN but there is a huge learning curve not only for starting to use such software packages, but also what in particular all those tools are, what they are for, how and when to use them, and how they perform, especially for a beginner.
The easiest way to start on that in MS Excel is to use XLSTATA, NeuralSolution, PALISADE as MS Excel Add-ins, to name a few, but they are all commercial some offer a full trial use. In Excel such Add-ins offer more easy "control" over steps performed on those tools, like SVM, k-NN, and Log regression, ... to start on.
Comment: What do you mean by "generalize input data for better processing" ?
Comment: Also "NN learn/train on dataset to target dataset, and then make a forecast on that particular database set" sounds weired.


What is the center of $\mathbb{C}S_3$?

Question: How do I found the center of symmetric group algebra $\mathbb{C}S_3$? and in general $\mathbb{C}S_n$?

I did an example on a smaller group algebra: $\mathbb{C}S_2=\{a (1)+b(12) \mid a,b\in \mathbb{C}\}$
So the center of $\mathbb{C}S_2=C(\mathbb{C}S_2)=\{x \in \mathbb{C}S_2 \mid \forall g\in \mathbb{C}S_2 ~~ xg=gx\}$
Now fix $x=a(1)+b(12)$ and let $g=a'(1)+b'(12)$
$$xg=[a(1)+b(12)][a'(1)+b'(12)]=(aa'+bb')(1)+(ab'+ba')(12)=gx$$
Hence $C(\mathbb{C}S_2)=\mathbb{C}S_2$

Can I apply the same method to find the center of $\mathbb{C}S_3$? Or is there a better way to do it?
Answer: Observe that given a vector $v\in \mathbb{C}G$, we have that centerality is equivalent to commutation with respect to the basis vectors $1g$ for $g\in G$. Writing $v=\sum_g v_gg$, take $v=hvh^{-1}=\sum_i v_g hgh^{-1}$ so that commutation is equivalent to $v_g=v_{hgh^{-1}}$, or that the coefficents are constant on the conjugacy class of $g$. Thus the center is $\bigoplus_{Z}\mathbb{C}i_{Z}$, where $Z$ goes over all conjugacy classes, and $i_V$ is the indicator function.
Now in the case of $G=S_n$, conjugacy classes corrospond to partition of $n$, so namely in the case of $S_3$, there are three cycle types, $3, 1|2, id$, so that every central element in the the three dimensional vector subspace of $a1+\sum_{i,j} b(ij)+\sum_{i,j,k}c(ijk)$.
Comment: This is a bit off topic, but since we can write $\mathbb{C}G=\bigoplus_i End(V_i)$ where $V_i$ are the irreduicible representations of $G$, which all add exactly one dimension of central elements, coming from the identity endomorphism (since the endomorphism ring is central simple), so that we have found that irreduicible representations are in bijection with conjugacy classes, atleast in number!
Answer: There is a ring isomorphism
$$
C(\mathbb{C}S_3)\simeq \mathbb{Z}\begin{pmatrix} 1 \cr 1\cr 1 \end{pmatrix}\oplus
\mathbb{Z}\begin{pmatrix} 3 \cr -3\cr 0 \end{pmatrix}\oplus \mathbb{Z}\begin{pmatrix} 2 \cr 2\cr -1 \end{pmatrix},
$$
see Example $2.1.4$ here, about the method how to find the center.

What is the center of $\mathbb{C}S_3$?


How to make user browser download gmail attachment directly from GMAIL?

Question: How to make user browser download gmail attachment directly from GMAIL when accessing 3rd party web app which can get the attachment information using gmail api?
Here's the scenario:
1) There's web application with server side code that can fetch emails using GMail API.
2) If the message has attachment and the user clicks download attachment button I want the user browser to download the attachment directly from GMail without having the web app download it first to server and then send it to the user browser.
So basicly I'm asking how to create URL that points to gmail and makes the user browser get the attachment from there. Does this make any sense?
We can assume the user browser can/is authenticated to GMail.
Tried finding possible solutions but failed.
Answer: There is no way to make an URL to an attachment using the Gmail API. CORS is enabled however, so you could use the access_token on the front end to download the attachment right away, but exposing the access_token to the client comes with a set of security risks you will have to take into consideration.


Show that the subspace $U$ is $\phi^z$-invariant

Question: Let $\mathbb{K}$ be a field and let $V$ be a $\mathbb{K}$-vector space.
Let $\phi,\psi:V\rightarrow V$ be linear maps, such that $\phi\circ\psi=\psi\circ\phi$.
I have shown using induction that if $U\leq_{\phi}V$ (i.e. it $U$ is a subspace and $\phi$-invariant), then $U\leq_{\phi^k}V$ for all $k\in \mathbb{N}$.
Now I want to show that if $\phi$ is invertible and if $U\leq_{\phi}V$, then $U\leq_{\phi^z}V$ for all $z\in \mathbb{Z}$.
For that we have to take cases, if $z\in \mathbb{Z}_{>0}$ then we would get the previous case and if $z\in \mathbb{Z}_{<0}$ we use the inverse linear map of $\phi$ and then we get the previous result.
My idea is the following:
If $z=:n\in \mathbb{Z}_{> 0}$, so $z=n\in \mathbb{N}$, the from the previous result it follows that $U$ $\ \phi^n$-invariant.
Since $\phi$ isinvertible there is a linear map $\chi$ such that $\chi:=\phi^{-1}$.
If $z=:-n\in \mathbb{Z}_{< 0}$, with $n\in \mathbb{N}$, then $\phi^{-n}=\left (\phi^{-1}\right )^n=\chi^n$.  Then if we show that $U$ is $\chi$-invariant then it follows from the previous result that $U$ is $\ \phi^{-n}$-invariant.
Is that correct?
Or do we show that in an other way?
Comment: Depends. How do you use the inverse linear map to show this?
Comment: And how would you show that $U$ is $χ$-invariant?
Comment: It does not. You only have shown $χφ(U) ⊆ U$, you want $χ(U) ⊆ U$. Thing is, the statement is false in general and only true if you consider finite dimensional subspaces $U ⊆ V$. Can you see why?
Comment: I added my idea in the question above. @k.stm
Comment: I thought that as follows: Since $U$ is $\phi$-invariant, we have that $\phi (u)\in U$for $u\in U$. Let $\phi (u)=:v$. Then we have that $\chi \left (\phi (u)\right )=\chi (v) \Rightarrow u=\chi (v)$ Does this help us? @k.stm
Comment: No, unfortunately I don't why. Could you explain that to me? @k.stm
Answer: The result does not hold in general. First consider the level of sets: Doubling and halfing are inverse to each other on $ℚ$, so take $φ \colon ℚ → ℚ,~x ↦ 2x$ and $χ\colon ℚ → ℚ,~x ↦ \frac x 2$. Then $φ(ℤ) ⊆ ℤ$ but $χ(ℤ) \not\subseteq ℤ$.
You can carry this over by taking vector spaces generated by these sets: Let $K$ be a field. For $V = \bigoplus_{x ∈ ℚ} K$ and $U = \bigoplus_{m ∈ ℤ} K$, we have $U ⊆ V$ and since $φ$ and $χ$ are given on a basis of $V$, we can extend both of them them to $V → V$. Now $φ(U) ⊆ U$, but $χ(U) \not\subseteq U$.
The result does however hold if $U$ is finite dimensional. For this observe that if $U$ is $φ$-invariant, $φ$ can be restricted to $φ \colon U → U$. Now $φ$ is injective because it's the restriction of an invertible map. What can you conclude? How does this relate to $χ$?
Comment: @MaryStar Think about it – maybe ask a separate question if you really cannot make any progress. I'm done here.
Comment: If $\phi$ is invertible does it have to be bijective?
Comment: Or is my idea for the proof that $U$ is $\phi^z$-invariant completely wrong?
Comment: Invertible maps are bijective, yes. If $U$ is $ϕ$-invariant, then it is $ϕ^z$-invariant for $z ∈ ℕ_0$. But $U$ does not need to be $ϕ^{-1}$-invariant in general, see my examples. However, if $U$ is finite-dimensional, it is indeed $ϕ^{-1}$-invariant, nonetheless. But this requires an extra argument, exploiting the finite dimensionality of $U$. Think about this.
Comment: What we are not given that condition, are we?
Comment: So do we have to show the desired result using an other way?


How can I solve this differential equation (not a obvious 2nd order ODE)

Question: I am not sure how to manipulate this 2nd order ODE to find the general solution
$$u_r u^{'}+\dfrac{u_r}{r}u=\dfrac{\nu}{r}\left(\dfrac{d}{dr}\left(r u^{'}\right) - \dfrac{u}{r}\right)$$
Where $$u_r=-\dfrac{r_0 v_w}{r}$$ where $r_0$ and $v_w$, $\nu$ are constants. I know I can rewrite the left hand side as $$\dfrac{u_r}{r}\dfrac{d}{dr}(ru)$$ but I am not sure how I can manipulate the right hand side any ideas?
Note $u(r)$ only
Comment: Can you clarify more what are $u_r$ and $u'$ and $\nu$?
Answer: The usage of abbreviation $u_r$ is somewhat misleading. Instead, I would suggest to do as follows. Let us denote constant $r_0 v_w$ as $\mu$. Then your equation can be rewritten as follows:
$$
-\frac{\mu}{r^2}\left(ru'+u\right) = \frac{\nu}{r}\left(ru''+u'-\frac{u}{r}\right).
$$
After simple manipulations, we get
$$
u'' + \left(1+\frac{\mu}{\nu}\right) \frac{1}{r} u' + \left(\frac{\mu}{\nu}-1\right) \frac{1}{r^2} u = 0.
$$
This is the so-called Euler Differential Equation, cf. http://mathworld.wolfram.com/EulerDifferentialEquation.html
And general solution (which depends on $\mu$ and $\nu$) for this equation is known.


Http observable response parse into array

Question: Just started with angular(version 7). I try to get a response from json-placeholder, an array of todos. That should return an array but when i console.log(typeof rsp) it shows an object.
Observable:
url: string = 'https://jsonplaceholder.typicode.com/todos';

getHomeTodos() {
    return this.http.get(this.url);
}

Observer in my component:
ngOnInit() {
this.todosService.getHomeTodos()
    .subscribe((rsp) => {
      this.homeTodos = rsp;
    });
}

Any ideas why the type of rsp is 'Object' but on the json-placeholder it shows it returns an array? Thanks.
Comment: Array is also an Object
Comment: Exactly what i was looking for. Thank you Pranav. I think i should focus more on typescript.
Comment: Try `console.log(typeof []);`: you'll get object too. An array is an object.
Comment: So how can i use a method like splice on the object returned?
Comment: @Fishlex : sure, `(rsp: any[])`
Comment: Please, don't do that. Use the right overload: `return this.http.get>(this.url);`. This will get you a typed response. `any` should be avoide as much as possible. https://angular.io/guide/http#type-checking-the-response
Comment: Ohh, i see. I'll try as much as possible to respect the good practices. Thank you for your answer.
Answer:
So how can i use a method like splice on the object returned?

I think I see what your question is. You need to specify the return type in get as well as getHomeTodos so you add type safety and the IDE can suggest methods/members on the types like splice on an array.
export interface IToDo { /* members here */ }

url: string = 'https://jsonplaceholder.typicode.com/todos';
getHomeTodos():Observable<IToDo[]> {
    return this.http.get<IToDo[]>(this.url);
}

homeTodos: IToDo[];
ngOnInit() {
  this.todosService.getHomeTodos()
    .subscribe((rsp) => {
      this.homeTodos = rsp;
    });
}

This added type safety and now you can use splice or other Array prototype members.


How to differentiate hype from word of mouth in Google Trends?

Question: I'm new to data analysis. I was wondering how I could recognize hyped (fake) growth and word of mouth (true) growth in Google Trends specifically (but I guess it applies even to stock markets and the rest).
For example, the image below is based on the Google Trends plot when you search for 'iPhone':

(Orange, magenta, and green annotation were added to the original.)
Comment: What operational distinction are you making about "fake" *versus* "true" growth?  By definition, Google Trends "compute[s] how many searches have been done for the terms you enter, relative to the total number of searches done on Google over time."  And that's that: it's neither fake nor true, it is what it is.
Comment: So, issues of interpretation aside, would it be correct to understand your question as asking how to separate a time series into one part that reflects "slow but sure" change and another part that consists of "huge spikes"?
Comment: I think @whuber's point is this: Unless you define trend and fad in more quantitative terms it is not possible to answer your question. Consider an analogy: I want to distinguish between tall and short people in a group. Unless I define what tall/short might mean I have no way of moving ahead with the task. For example, I could define tall: Average height + at least 1 standard deviation and so on. In summary: you need to tell us what is your operational definition for trend and fad before an answer can be given.
Comment: We're back to the beginning, then: your question is without meaning, and therefore has no valid objective answer, unless you can characterize "trend" and "fad" in terms of the plots produced by Google Trends.
Comment: I think what you really want to know is if what looks like a movement in the ticker is likely to continue.  I think this is what you mean by 'real' vs. 'fake' and 'trend' vs. 'fad'.  This is a big deal in time series and forcasting, but it requires a book-length treatment.  Moreover, I think the short answer is: *you can't tell* (until after the fact).
Comment: What do you call a plot ? Actually this is my question, how to characterize trend and fad.
Comment: Well, if we consider that Google Trends shows popularity (I should have said that instead of growth), then for the iPhone we can see the general aspect of the curve, the popularity is slowly but surely increasing, this I believe is word of mouth. While huge spikes correspond to announcements etc they are hypes and don't reflect true popularity. @whuber
Comment: Rather sure and unsure, trend or fad. Isn't it what all brokers want to know ?
Comment: Ok hang on I'm gonna schematise.
Comment: Can't add images to the question so here it is http://i.stack.imgur.com/pYHRS.gif and what I was wondering is if I'm making a correct assumption.
Answer: You can apply all sorts of smoothing functions to your time series.  A simple one would be a linear regression, and a more complicated one would be a loess function.
Your orange line looks suspiciously like a linear regression.
Comment: Not sure how to [use it](http://www.apple.com/iwork/numbers/functions.html).
Comment: @user2534: if you're going to do any serious stats, you should get a stats packages, such as R, SAS, Matlab, Stata, etc. etc.
Answer: This answer uses Varsity-level statistics, but people interested in separating long-term trends from shorter-term spikes should really take a look at the discussion in this post about using Gaussian processes to model this sort of thing.
The blue line in the top graph is a smoothed trendline showing more-or-less seasonal variation, the blue spikes in the second graph show the periodic (weekly?) component, and the third graph shows residual patterns (e.g. holidays).
The Matlab code used to do the analysis is available here, as described in one of the comments.
Again, this is probably too advanced for most people (including me!), but it's the best example I know of where someone tried to tackle a problem like this.


How to get all alt attributes of all img tags using jQuery

Question: My html code:

How to get all the alt values of img tag?
Answer: try this : You can make use of attr() method of jquery object. Iterate all images and call $(this).attr('alt'); to get the alt attribute value.

$(function(){
  $('img').each(function(){
    alert($(this).attr('alt'));
  });
});

Comment: `attr()` isn't strictly needed here. `alert(this.alt);` will do just fine.
Comment: yeah, it is one of the way to read `alt` thats why I said You can make use of `attr()`
Answer: You can get all alt's as an array using map() like following

var alts = $('img').map(function () {
    return this.alt;
}).get();
alert(alts);

Answer: $('img').each(function(){
    console.log(this.getAttribute('alt'));
})

Answer: var imgAltTagArr=[];
$('img').each(function(){
    imgAltTagArr.push($(this).attr('alt'));
});
alert(imgAltTagArr);

Answer: $('img').each(function(){

console.log($(this).attr('alt'));

})

working fiddle

https://jsfiddle.net/gub4qs2e/


How to calculate the size of a xylophone bar according to its pitch

Question: I am new to StackExchange, and I have a question about a school project I'm working on involving constructing an instrument. I am building a xylophone-glockenspiel-mash kind of thing, but I wanted to save some money on materials and I need to know:
If I have the right material, and I know the current length and the current pitch in Hz when struck, can I calculate the length it needs to be to reach a specific note (in this case, F4)?
The current length is 3ft or 91.4cm, and currently it hits 218.2Hz when struck. I have found nothing in my searches on the internet so far, although this may be because I don't know the proper terminology to search for.
Thank you for reading, and thanks in advance for helping.
Comment: It will depend entirely on the type of material used for the bars, a certain metal alloy or type of wood. And if it is wood, it will vary with the density of the grain of the wood, its age, or its moisture content. I don't think you can easily generalize. You'll certainly end up having to mill or cut blocks and carefully cut them to tune them by hand and by ear.
Comment: There are other criteria you may want to take into account, especially harmonicity. I'll try to find my old musical acoustics notes, but I have little to no hope.
Comment: Usually the length isn't even that important. In many instruments the lengths are chosen in an aesthetically pleasing way, but you can do a lot by tuning them, see e.g. here: https://www.youtube.com/watch?v=5PesHXkN2M8
Answer: I have corrected this ! The guy below gave the correct answer, but I've worked it out so it can be used practically.
Present length^2 / needed length^2 =  desired frequency / known frequency
Working that out
needed length = Square root of (present length * present length * known frequency /desired frequency )
349.2 hz is desired freq
91.4 cm is present length
218.2 hz is known freq
91.4 * 91.4 * 218.2 / 349.2
= 5220
Get the Square root of 5220
= 72.2 cm
Cut it way longer than that! Then test it and shave it down gradually until you reach the right pitch.
BTW here is a link to the frequencies of the music notes:
https://pages.mtu.edu/~suits/notefreqs.html
Could be handy!
NOTE: from actually doing this several practical tips.
1) Outside of an octave or so you may get different harmonics coming to the fore, especially with cheap wood. So when cutting down a larger piece of wood, you really need to use trial and error. I had a piece of wood that sounded a fairly clear Ab, and another about half as long is a C. I think that's because a different harmonic is coming through on the longer piece.
2) If there are impurities in the wood such as knots or swirls, it tends to affect the pitch, apparently in a downward direction, sometimes by as much as a tone. On my makeshift example I have several bits of wood the same length that are nonetheless different pitches by as much as a tone, and I think it is because one piece of wood has straight grain and the other has a knot in the middle.
3) Because of this you really do need to cut the wood a lot longer than you need!!! Then gradually shave off pieces until you reach the pitch you want.
4) I used a rubber strip attached to nails as a sort of bed for the bars, and it makes a very clear sound. Might be good to do this at the start, for testing the pitch. Otherwise hold the piece of wood at the very end when you hit it.

Here's my makeshift example, 'proof of concept' for xylophone construction lessons at school. Note the lengths of the keys. F is actually slightly longer than E, when it should be shorter, but I think this is because of the big knot on the E bar.

Here is what the 'bed' looks like, in which the bar rests at both ends. It allows the bar to vibrate freely.
Here are the lengths of these bars and the frequencies. They conform to the above equation, roughly, if you want to check!
C 40cm 261 hz
D 40cm 293 hz
E 35cm 329 hz
F 36cm 349 hz
G 32cm 391 hz
A 32cm 440 hz
Answer: Eq. 4.39 of H. Olsen, Music Physics and Engineering 1967
gives the equation for the fundamental frequency of a free bar.  For this problem, where you have the same material and the same cross-sectional shape, the frequency is proportional to 1/(length squared)
Answer: I think that rote numbers will not work.  Wood is not a material of homogenous resilience, and xylophone bars are hollowed out for best resonance (and as part of tuning).  So you need to figure in some waste material for experiments.


Uniqueness of solution of specific ODE

Question: I'm trying to solve the following problem. It's exercise 1.6 of the book Ordinary Differential Equations by Barreira & Valls.
Let $f:(a,b) \rightarrow \mathbb{R} \backslash \{0\}$ be a continuous function.
a) Show that the function $g:(a,b) \rightarrow \mathbb{R}$ defined by
$$g(x) = \int_{x_0}^x \frac{1}{f(y)}dy$$
is invertible for each $x_0 \in \mathbb{R}$.
b) Show that the initial value problem (1.13) has a unique solution. Hint: For a solution $x(t)$, compute the derivative of the function $t \mapsto g(x(t))$
Note: (1.13) is the following IVP
\begin{cases}
x' = f(t,x),\\
x(t_0) = x_0,
\end{cases}
where $(t_0,x_0) \in D \subseteq \mathbb{R} \times \mathbb{R}^n$, and $D$ is an open set.
a) I think I have to use the inverse function theorem, but this theorem requires that $g$ be $C^1$ according to Wikipedia https://en.wikipedia.org/wiki/Inverse_function_theorem. I don't even know if I can integrate $\frac{1}{f(x)}$. What if $f(x) = x$ and $(a,b) = (0,1)$. I could pick $x_0 = 0$ and $g(x)$ wouldn't even be defined. And what if $f(x)$ gets really big and $\frac{1}{f(x)}$ gets really close to zero. Is it still true that $g'(x)$ is nonzero? Sure, if I just blindly apply the fundamental theorem of calculus and the inverse function theorem I get that $g'(x) = \frac{1}{f(x)}$, but is that correct?
b) I do not understand the hint. I have to solve the following (autonomous) problem
\begin{cases}
x' = f(x),\\
x(t_0) = x_0.
\end{cases}
I do what the hint says
$$\frac{dg(x)}{dt} = \frac{dg(x)}{dx} \frac{dx}{dt} = \frac{1}{f(x)}x'(t).$$
I have assumed $\frac{dg(x)}{dx} = \frac{1}{f(x)}$. I don't see how I can get a solution from this. Already Peano's theorem tells me I have a solution because $f$ is continuous but I imagine the book wants me to find a specific solution and then prove it's the only one.
Any help is appreciated.
Comment: You should clarify whether the ODE right hand side is $f(x)$ or $f(x,t)$.
Comment: In (1.13) it is $f(t,x)$ but in the exercise it is $f(x)$ since that is the function we're given.
Comment: @Gonçalo I don't know. Could it be a typo?
Comment: @Gonçalo I did, but I came into the problems described above.
Comment: You can because of $x_0 \in \mathbb{R}$.
Answer: Let us take $x_0\in(a,b)$ and $f(t,x)=f(x)$, which needs to be the intention.
Note that $g'(x)=1/f(x)$ is always positive or always negative (since $f$ never vanishes). Therefore, $g$ is either strictly increasing or strictly decreasing, and so it is invertible.
Using the hint, for a solution $x(t)$ of the equation $x'=f(x)$ we obtain
$$
\frac{d}{dt}g(x(t))=\frac{x'(t)}{f(x(t))}=1
$$
and so $$g(x(t))-g(x_0)=t-t_0.$$ Therefore, $$x(t)=g^{-1}(t-t_0+g(x_0))$$ in some appropriate domain. In particular any solution is unique (given by the former formula).

Uniqueness of solution of specific ODE


How to replace a certain path from the PATH variable?

Question: I am using Cygwin and would like to modify the following PATH via bash shell:
/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VSTSDB/Deploy:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/IDE:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/BIN:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/Common7/Tools:/cygdrive/c/Windows/Microsoft.NET/Framework/v4.0.30319:/cygdrive/c/Windows/Microsoft.NET/Framework/v3.5:/cygdrive/c/Program Files (x86)/Microsoft Visual Studio 10.0/VC/VCPackages:/cygdrive/c/Program Files (x86)/HTML Help Workshop:/cygdrive/c/Program Files (x86)/HTML Help Workshop:/cygdrive/c/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/bin/NETFX 4.0 Tools:/cygdrive/c/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/bin:/cygdrive/c/Python33:/cygdrive/c/_WORK/java/jdk1.6.0_30/bin:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files (x86)/QuickTime/QTSystem:/cygdrive/c/Program Files (x86)/Common Files/Roxio Shared/DLLShared:/cygdrive/c/Program Files (x86)/Common Files/Roxio Shared/10.0/DLLShared:/cygdrive/c/Program Files/WIDCOMM/Bluetooth Software:/cygdrive/c/Program Files/WIDCOMM/Bluetooth Software/syswow64:/cygdrive/c/Program Files/Intel/WiFi/bin:/cygdrive/c/Program Files/Common Files/Intel/WirelessCommon:/cygdrive/c/Program Files (x86)/apache-ant-1.8.3/bin:/cygdrive/c/Program Files (x86)/Code Collaborator Client:/cygdrive/c/Program Files/TortoiseSVN/bin:/cygdrive/c/Program Files/Intel/WiFi/bin:/cygdrive/c/Program Files/Common Files/Intel/WirelessCommon

The path is huge.
Somewhere in the middle there is
c/_WORK/java/jdk1.6.0_30/bin.
What I'd like to do is to temporarily replace this with
c/_WORK/java/jdk1.7.0_40/bin
In other words, I'd like to use different Java SDK versions. Sometimes I would use 1.6 sometimes 1.7.
How would I change the Java SDK path?
Answer: Simply, customize the variable by running these commands:
PATH="path_to_your_jdk_bin_dir:$PATH"
export PATH

The new path will take precedence over the other one. To make this change permanent in your profile, put these two lines to the ~/.bash_profile or ~/.profile file.
Further, I would recommend to set the JAVA_HOME variable properly.
Answer: You can create a symbolic link
Comment: Thanks. Could you elaborate a little bit? Have in mind that the system is shared, so I cannot do much on my own.
Answer: The way to handle different versions of the Java VM installed on your machine via cygwin is to register them in the alternatives system. Check its manpage for details.
This defines the system-wide default selected JRE/JDK.
To override this in a per-user environment, include JAVA_HOME in their .bash_profile.


Windows Server 2008 BitLocker

Question: I would like to configure whole disk encryption on all of my Domain Controllers. Is BitLocker an acceptable method to do this? What are the potential problems with whole disk encryption on a Domain Controller?
Comment: Excellent edit to save the question :)
Comment: Please read the [faq]. Open-ended questions asking for discussion are off-topic. If you have a technical question about it, that's fine, but just asking for people's experience and whether or not it's a "good idea" is entirely subjective.
Answer: I am generally very against FDE on servers. Servers should have tight logical security to keep out electronic attacks, and reasonable physical security to keep people from stealing the whole thing. In the rare situation where you can't implement reasonable physical security, then FDE is appropriate.
BitLocker combined with TPM stored keys works extremely well. If the server doesn't support TPM it will not be able to boot automatically, which may be a serious problem depending on your environment.
Answer: Yes, using BitLocker for Whole disk encryption on a DC is acceptable.  However, Keep in mind that BitLocker encryption is for OFFLINE disk protection.  Once the DC boots, it will run with the file system unencrpyted.  The potential problems are based on how you configure BitLocker.  For example, if you don't have a physical TPM in your servers, you will need a startup key saved on a USB device that would need to be inserted for bootup.  This could potentially circumvent your protection if left in the server.  Say if your DC is physically stolen and you left the USB startup key in.  Your drive encryption is then useless, as the USB key is already inserted.   Also, remember to keep your recovery key around, in case you forget a PIN (optional requirement), or need to move the disks to new hardware.
There is also a slight performance hit when encrypting the drive.
If you are worried about security on your DCs in a low security site, you may want to consider using Read-Only DCs instead.
Comment: Do you know if the performance hit is negligible?
Comment: @FredMarr During the initial encryption process, the CPU and disks are put under much higher load than usual. That said, a DC should be able to keep its entire AD database in RAM, making high disk I/O not a problem at all. Unless you run other services on the DC, that is.

Windows Server 2008 BitLocker


Listar somente se a outra tabela não tiver uma demissão

Question: Boa tarde. Preciso fazer uma listagem de funcionários por ano. Por exemplo. Funcionários ativos de 2018, porém estou tendo problemas, pois em 2019 alguns foram demitidos ai não lista os mesmos, sendo que uso a tabela Funcionários e a ExamesFuncionarios.
Editado: Seguinte, usei a verificação para saber se tinha exames demissionais, até ai tudo bem, não lista essa pessoa, porém essa mesma pessoa tem no memso ano o exame de retorno ao trabalho, ou até mesmo outro exame e eu não quero e não posso que ele exiba. Como faço a condição para que se caso haja exame demissional para tal pessoa ela pule a pessoa mesmo que tenha outros exames.
Seguem os Códigos e as tabelas.
Tabela Funcionário ->
 CREATE TABLE `funcionario` (
  `CodFuncionario` int(11) NOT NULL AUTO_INCREMENT,
  `funcionario_CodEmpresa` int(11) NOT NULL,
  `funcionario_CodSetor` int(11) DEFAULT NULL,
  `funcionario_CodCBO` varchar(6) DEFAULT NULL,
  `funcionario_Nome` varchar(50) DEFAULT NULL,
  `funcionario_DataNac` date DEFAULT NULL,
  `funcionario_DataAdm` date DEFAULT NULL,
  `funcionario_Sexo` varchar(1) DEFAULT NULL,
  `funcionario_CTPS` varchar(20) DEFAULT NULL,
  `funcionario_RG` varchar(10) DEFAULT NULL,
  `funcionario_NIT` varchar(12) DEFAULT NULL,
  `funcionario_Ativo` varchar(1) DEFAULT NULL,
  `funcionario_Cpf` varchar(11) DEFAULT NULL,
  `funcionario_DataDemissao` date DEFAULT NULL,
  `funcionario_TrabalhoAltura` varchar(1) DEFAULT NULL,
  `funcionario_TrabalhoConfinado` varchar(1) DEFAULT NULL,
  `funcionario_HoraEntrada` varchar(100) DEFAULT NULL,
  `funcionario_HoraSaida` varchar(100) DEFAULT NULL,
  `funcionario_InicioRepouso` varchar(100) DEFAULT NULL,
  `funcionario_FimRepouso` varchar(100) DEFAULT NULL,
  `funcionario_Epi` longtext DEFAULT NULL,
  `funcionario_RiscoFisico` longtext DEFAULT NULL,
  `funcionario_RiscoQuimico` longtext DEFAULT NULL,
  `funcionario_RiscoBiologico` longtext DEFAULT NULL,
  `funcionario_RiscoErgonomico` longtext DEFAULT NULL,
  `funcionario_HoraEntrada_S` varchar(100) DEFAULT NULL,
  `funcionario_HoraSaida_S` varchar(100) DEFAULT NULL,
  `funcionario_InicioRepouso_S` varchar(100) DEFAULT NULL,
  `funcionario_FimRepouso_S` varchar(100) DEFAULT NULL,
  `funcionario_ExameOcupacional` longtext DEFAULT NULL,
  PRIMARY KEY (`CodFuncionario`) USING BTREE
)

Tebela ExamesFuncionarios ->
CREATE TABLE `examefuncionario` (
  `idExameFunc` int(11) NOT NULL AUTO_INCREMENT,
  `exameFunc_CodFuncionario` int(11) NOT NULL,
  `exameFunc_NrSeq` int(11) NOT NULL,
  `exameFunc_CodExame` int(11) DEFAULT NULL,
  `exameFunc_Data` date DEFAULT NULL,
  `exameFunc_Tipo` varchar(1) DEFAULT NULL,
  `exameFunc_Natureza` varchar(1) DEFAULT NULL,
  `exameFunc_Apto` varchar(1) DEFAULT NULL,
  `exameFunc_DataProximo` date DEFAULT NULL,
  `exameFunc_Resultado` varchar(1) DEFAULT NULL,
  `exameFunc_FlgRefSeq` varchar(1) DEFAULT NULL,
  `exameFunc_DataUltimo` date DEFAULT NULL,
  PRIMARY KEY (`idExameFunc`) USING BTREE
)

Códigos Mysql 1ª forma ->
select funcionario.CodFuncionario,funcionario.funcionario_Nome
from funcionario
join examefuncionario on examefuncionario.exameFunc_CodFuncionario = funcionario.CodFuncionario and date_format(examefuncionario.exameFunc_Data, "%Y") = '2018'
where funcionario_CodEmpresa = 179
and date_format(funcionario_DataAdm, "%Y") <= '2018'
group by funcionario.CodFuncionario
order by funcionario.funcionario_Nome ASC

Códigos Mysql 2ª forma ->
select funcionario.CodFuncionario,funcionario.funcionario_Nome
from funcionario
join examefuncionario on examefuncionario.exameFunc_CodFuncionario = funcionario.CodFuncionario and date_format(examefuncionario.exameFunc_Data, "%Y") = '2018'
where funcionario_CodEmpresa = 179
and date_format(funcionario_DataAdm, "%Y") <= '2018'
and funcionario_Ativo = 'S'
group by funcionario.CodFuncionario
order by funcionario.funcionario_Nome ASC

Código editado:
select *
from funcionario

join examefuncionario
    on examefuncionario.exameFunc_CodFuncionario = funcionario.CodFuncionario
    and date_format(examefuncionario.exameFunc_Data, "%Y") = '2018'
    and examefuncionario.exameFunc_Natureza != 'D'

where funcionario_CodEmpresa = 179
and date_format(funcionario_DataAdm, "%Y") <= '2018'

group by funcionario.CodFuncionario
order by funcionario.funcionario_Nome ASC

Preciso que liste os funcionários que em 2018 não tiveram exames demissionais.
Em 2018 o funcionário estava ativo porem em 2019 está inativo, então quando uso o where do mesmo alguns que em 2018 estavam ativos não lista.
Comment: Não basta você listar os que estão com funcionario_DataDemissao NULL (não demitidos) ou o ano de funcionario_DataDemissao seja maior ou igual a 2018 (estiveram ativos pelo menos em algum momento de 2018)?
Comment: Da maneira como está seu critério de junção você só selecionará na junção os funcionários que fizeram pelo menos um exame em 2018. Não me parece estar de acordo com o texto de sua pergunta.
Comment: Como sua tabela examefuncionario possui o campo exameFunc_Data não é necessário também verificar se o ano de tal data é 2018 e o tipo de exame é o que deseja?
Comment: Preciso verificar, pois esse relatório é anual, ou seja, no ano de 2019 tudo muda.
Comment: Mas os códigos que você postou não fazem tal verificação.
Comment: date_format(examefuncionario.exameFunc_Data, "%Y") = '2018' so exibe os exames referente a 2018. Porém tem alguns funcionarios que fazer dois, um deles é demissional e eu não posso listar ele, e também não posso usar o funcionario_Ativo = 'S'  porque dai não vai listar outros que em 2018 estava ativos mas agora em 2019 estão inativos.
Comment: Qual a sua versão do `MySQL`?
Answer: Utilize o NOT EXISTS da seguinte forma:
SELECT f.CodFuncionario,
       f.funcionario_Nome
  FROM funcionario f
 WHERE f.funcionario_CodEmpresa = 179
   AND EXISTS(SELECT 1
                FROM examefuncionario ef
               WHERE ef.exameFunc_CodFuncionario = f.CodFuncionario
                 AND DATE_FORMAT(ef.exameFunc_Data, "%Y") = '2018'
                 AND ef.exameFunc_Natureza <> 'D')
   AND NOT EXISTS(SELECT 1
                    FROM examefuncionario ef
                   WHERE ef.exameFunc_CodFuncionario = f.CodFuncionario
                     AND DATE_FORMAT(ef.exameFunc_Data, "%Y") = '2018'
                     AND ef.exameFunc_Natureza = 'D')
 GROUP BY f.CodFuncionario
 ORDER BY f.funcionario_Nome ASC

Comment: Blz, vou tentar. Obrigado.
Comment: A questão é que eu não posso usar a condição se ele está ou não ativo, pois isso seria deste instante, e eu preciso que liste no caso do ano passado, onde p funcionário estava admitido, porém este ano ele está demitido.
Comment: @JoséLuis entendi, vou editar a resposta
Comment: Se eu resolver isso fico grato a todos, porque isso ta me dando um trabalho e não posso fazer meus outros sistemas.
Comment: @JoséLuis pronto, adicionei na resposta. Só que isso não compreende pessoas que foram recontratadas, não sei se é o caso
Comment: Cara ta quase certo, porém falta algo. O certo deveria listar 48 e está listando 44
Comment: A condição tem que ignorar qualquer um que tenha demissional, mesmo que o mesmo funcionário tenha dois exames.
Comment: @JoséLuis mas é isso que está fazendo. Veja se você não consegue bolar um exemplo no [**DB Fiddle**](https://www.db-fiddle.com/) senão fica difícil te ajudar
Comment: Pior que que tem mais de 810 registros no total. Dai fica difícil de separar.
Comment: Me mande seu contato por email. E se tu poder me ajudar por acesso remoto. email@example.com
Comment: O que eu preciso a modo grosso seria assim -> se funcionario tal tiver uma demissão não listar.
Comment: @JoséLuis então, o problema é que essa `query` já faz isso. Aparentemente você tem alguma particularidade nas suas tabelas que impede o resultado ser favorável. Só podemos corrigir se você bolar um exemplo executável. Para isso você não precisa de todos os dados, só dos que são necessários para elaboração da resposta, de preferência em um fiddle executável, assim você pode demonstrar o problema e podemos propor uma solução
Comment: Tu não tem como me ajudar remotamente? Assim poderia lhe explicar melhor também. Este é o ultimo processo que preciso pra entregar este sistema, e o cliente está nos meus ouvidos se é que você me entende.
Comment: Boa noite, não consegui usar o DB Fiddle nem um outro, então resolvi upar no Mega. https://mega.nz/#!tY0n1SLY!oIOgvNDWLRGWikDbIztzQv8Lg9TxpOFMIQBxBMDtNR0
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/95399/discussion-between-sorack-and-jose-luis).
Answer: Acredito que você tenha que colocar também condiçoes relacionadas ao tipo ou natureza de exame. Olhando apenas as amostras das tabelas que vocë passou, eu fico um pouco na duvida do que seria:
exameFunc_Tipo     varchar(1) DEFAULT NULL,
exameFunc_Natureza varchar(1) DEFAULT NULL,

Talvez resolva o seu problema se vocë colocar uma condicao do tipo NOT IN  para pegar os funcionarios que nao tiveram exames do tipo/natureza demissional no ano de 2018, entende?
Existe uma outra questao tbm... ao fazer o join com a Tabela ExamesFuncionarios, você ja leva em considereçao que todo funcionario ativo em 2018 fez algum tipo de exame. Você tem que avaliar se essa condiçao é verdadeira. Todos os anos todos os funcionarios da empresa passam por algum tipo de exame todos os anos? Porque se nao passam, imagino que nao vai existir registro na tabela exames funcionarios... se nao existe registro, quando voc faz o join, esses funcionarios que nao fizeram nenhum exame em 2018 estarao automaticamente fora do resultado da consulta.
Comment: Isso, isso é um relatória anual de tudo que ocorre dentro da empresa. Natureza seria 'Demissional, Periódico e tal'. Como uso o not in?


R: adding an argument to match.call output

Question: Say I have the following function in R:
tst <- function(x,y){
  foo <- match.call()
  print(foo)
}

tst(4,5)

This gives tst(x = 4, y = 5). Awesome. Now, I want to add an argument.
tst <- function(x,y){
  foo <- match.call()
  foo[[length(foo)+1]] <- 6
  print(foo)
}

tst(4,5)

This prints tst(x = 4, y = 5, 6), which is great. However, I need to add an argument name so that the function knows what to do with it. For example, I want it to be tst(x = 4, y = 5, z = 6). I tried simply foo[[length(foo)+1]] <- "z = 6", but that clearly doesn't work. I've also toyed with parse and eval without success. Any suggestions?
Comment: Why do you need a `call` output? How are you going to use it? Wouldn't it better to get a list back in the first place?
Comment: It stems from [this](https://stackoverflow.com/questions/44912496/geom-smooth-with-facet-grid-and-different-fitting-functions/44913300#44913300) question. I want to modify the answer to include `nls`. Unlike `lm` and `loess` in the given answer, `nls` expects additional arguments, like `start`. So, in the `mysmooth` function I'd like to add these arguments.
Answer: You can actually treat the call like a list and give it a named argument:
> tst =
function(x,y){
 foo = match.call()
 foo[["this"]] ="that"
 print(foo)
}
> tst(x=2,y=3)
tst(x = 2, y = 3, this = "that")


What is the maximum number of spheres with same radius that can touch each other in n dimensions.

Question: For 2 dimensions there can be three circles that can touch each other. In 3 dimensions there can be 4 spheres that can touch each other. What would be the number of hyper-spheres that can touch each other directly in n dimensions?
Comment: You can get 4 circles all touching one another in 2 dimensions. One will have to be smaller than the others and placed in the middle, though (or larger and put around them). See the two red circles in [this image](https://en.wikipedia.org/wiki/Descartes%27_theorem#/media/File:Descartes_Circles.svg).
Comment: forgot to add that the circles are of same radius. Will add that in the question.
Answer: In $n$ dimensions, the maximum is $n+1$.
Two spheres (I'll use that term regardless of dimension) of radius $r$ are tangent to each other if and only if the distance between their centers is $2r$. Thus, $n+1$ spheres are all tangent to each other if and only if the distance between any two of those points is $2r$.
These $n+1$ points thus form a $n$-simplex with all sides equal to $2r$. We wish to show that this figure requires at least $n$ dimensions. Why? Because we can calculate its $n$-volume, and that volume is positive.
The $n$-volume of a $n$-simplex with vertices $z_0,z_1,\dots,z_n$ is $\frac1{n!}\left|\det\begin{pmatrix}z_1-z_0&z_2-z_0&\cdots&z_n-z_0\end{pmatrix}\right|$. Or, at least, it is if those vectors are all in $\mathbb{R}^n$. Since we're  varying the number of dimensions, we need a volume formula that can hold up to that. For example, in $\mathbb{R}^3$, the area of a triangle will come from the length of the cross product of two of its side vectors; the cross product serves as a sort of directed area formula.
That matrix $Z$ we took the determinant of in the $\mathbb{R}^n$ case still makes sense if all the vectors are in $\mathbb{R}^m$ for some other $m$; it just won't be square. So, what can we do? Multiply it by its transpose. The resulting matrix is square, symmetric, and positive semidefinite, so we can take its determinant, and then the square root of that determinant. The volume we seek, if the $z_i$ are points in any $\mathbb{R}^m$, is $\frac1{n!}\sqrt{\det(Z^TZ)}$. Writing down the entries of $Z^TZ$, we get
$$Z^TZ = \begin{bmatrix}\|z_1-z_0\|^2&(z_1-z_0)\cdot(z_2-z_0)&\cdots&(z_1-z_0)\cdot(z_n-z_0)\\(z_2-z_0)\cdot(z_1-z_0)&\|z_2-z_0\|^2&\cdots&(z_2-z_0)\cdot(z_n-z_0)\\ \vdots&\vdots&\ddots&\vdots\\ (z_n-z_0)\cdot(z_1-z_0)&(z_n-z_0)\cdot(z_2-z_0)&\cdots&\|z_n-z_0\|^2\end{bmatrix}$$
Those dots are the usual dot product of vectors, of course. Next, we convert all those dot products into a form based entirely on the distances between the points. If $d_{ij}$ is the distance between points $z_i$ and $z_j$, then $(z_i-z_0)\cdot (z_j-z_0) = \frac12\left(d_{0i}^2+d_{0j}^2-d_{ij}^2\right)$. Apply this in our case with all the $d_{ij}$ equal to $2r$, and
$$Z^TZ = \begin{bmatrix}4r^2&2r^2&\cdots&2r^2\\2r^2&4r^2&\cdots&2r^2\\ \vdots&\vdots&\ddots&\vdots\\2r^2&2r^2&\cdots&4r^2\end{bmatrix}$$
The determinant of that $n\times n$ matrix is $2^n\cdot r^{2n}\cdot (n+1)$, so the $n$-volume is $r^n\sqrt{\frac{2^n(n+1)}{n!}}$. That's not zero, so we need at least $n$ dimensions to fit our $n+1$ points at equal distances.
As a side note, I prefer working with that determinant formula a bit more. With some clever linear algebra, we can replace $Z^tZ$ with a $(n+2)\times (n+2)$ matrix that has just squared distances as entries:
$$V^2=\frac{(-1)^{n+1}}{2^n (n!)^2}\det\begin{bmatrix}0&1&1&1&1&\cdots&1\\1&0&d_{10}^2&d_{20}^2&d_{30}^2&\cdots&d_{n0}^2\\1&d_{01}^2&0&d_{21}^2&d_{31}^2&\cdots&d_{n1}^2\\1&d_{02}^2&d_{12}^2&0&d_{32}^2&\cdots&d_{n2}^2\\1&d_{03}^2&d_{13}^2&d_{23}^2&0&\cdots&d_{n3}^2\\ \vdots&\vdots&\vdots&\vdots&\vdots&\ddots&\vdots\\ 1&d_{0n}^2&d_{1n}^2&d_{2n}^2&d_{3n}^2&\cdots&0\end{bmatrix}$$
It wasn't necessary for this problem, but it's a neat one to know - the higher-dimensional generalization of Heron's formula.


XYPlot Android same x value, multiple y-values

Question: I'm trying to create a plot using Kotlin and androidplot library. My source code is:
val domainLabels = arrayOf<Number>(1,2,3,6,7,8,9,10,13,14)
val series1Number = arrayOf<Number>(1,4,8,12,16,32,26,29,10,13)

val series1 : XYSeries = SimpleXYSeries(Arrays.asList(* series1Number)),SimpleXYSeries.ArrayFormat.Y_VALS_ONLY,"Series 1")
val series1Format = LineAndPointFormatter(Color.BLUE,Color.BLACK,null,null)
binding.plot.addSeries(series1,series1Format)
binding.plot.graph.getLineLabelStyle(XYGraphWidget.Edge.BOTTOM).format = object : Format(){
        override fun format(p0: Any?, p1: StringBuffer, p2: FieldPosition?): StringBuffer {
            val i = Math.round((p0 as Number).toFloat())
            return p1.append(domainLabels[i])
        }

        override fun parseObject(p0: String?, p1: ParsePosition?): Any? {
            return null
        }

    }

Although it works, I have some troubles when the domainLabel is the same. Look at the image below for x value equals 8. I expect that since the x value is the same, it will be shown only one time, and I will have two points. Do you have any suggestions?
Answer: This looks suspiciously like a precision error, and this would appear to be the likely culprit:
val i = Math.round((p0 as Number).toFloat())

I'm not positive but I suspect the above Kotlin code is not functionally identical to:
int i = Math.round(((Number) obj).floatValue());

Which I did just confirm works as expected.  Best suggestion would be to check this out in the debugger and see if your 9's are getting truncated to 8's.


how to write the regular expression patterns for the following scenarios

Question: Can any body give me some regular expression patterns which will extract the version numbers(1.5) from some sample strings like
    "jdk1.5","jdk-v1.5","jdk-V1.5","jdk V1.5","jdkv1.5","jdk version1.5","1.5.6","v1.5","V1.5","version 1.5","Version 1.5","14.5.4","1.5.4","14.5.4""jdj14.5"

I want to store the regex patterns in a string array and will check these patterns with the above strings. If there is a match with any of the stored patterns, then the output should be the version number 1.5. I want to extract the version numbers (1.5) only from the above strings.
valid string formats :
      "jdk1.5","jdk-v1.5","jdk-V1.5","jdk V1.3","jdkv1.4","jdk version1.5","1.5.6","v1.5","V1.5","version 1.5","Version 1.5","14.5.4","1.5.4","14.5.4""jdj14.5","22.214.171.124"
Invalid String formats : "jdk1..2","jdk.1.2.",".1.2."
Comment: -1 for what amounts to a "Give me teh codez" question. *[what have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/)*
Answer: Try with:
^(jdk[- ]?)?([vV](ersion)? ?)?\d\.\d(\.\d)?$

You can ommit [vV] with v if you set CASE_INSENSITIVE flag.
Answer: Try this regular expression:
(?<=([\w\s]))(\d)\.(\d)(.\d)?
This will match all your valid formats , and not match any invalid format.
See it working here : http://regexr.com?31ubc
I would be grateful if someone can assist me in making it better, and also on how to make it
match 1.5.6
Comment: @hsz yes, I have already mentioned that in answer and asked for suggestions.
Comment: Sorry, didn't noticed :) However you should use `^` and `$` to be sure that whole string is tested. If done, your regex does not works :-(
Comment: Hi i can have not only three precisions. but more than that like 184.108.40.206 or 14.5.6 is also valid.
Answer: Requirements
If you can formulize what you want as:

Anything in format 1.5 or 1.5.6 or 188.8.131.52 or 220.127.116.11.8 etc. is valid version number by default (numbers can be one or more digits like 12.60.70).
A version number 1.5 can be followed by a dot (.) only if it is in the format 1.5.6.
A version number 1.5 never preceded by a dot (.) like .1.5.

Solution
Then, I can suggest you this regex:
(?!\.)(\d+(\.\d+)+)(?![\d\.])

See it in action, includes all positive samples and excludes all negative samples you provided.
How to use
First capture group will be your version number. Sample code:
Pattern pattern    = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])");
Matcher matcher    = pattern.matcher(inputStr);
boolean matchFound = matcher.find();

if (matchFound)
{
    String version = matcher.group(1);
    System.out.println("Version number: " + version);
}
else
{
    System.out.println("No match for the input!");
}

Note: This will work only with Java 7+, because look-aheads doesn't supported by older versions.
Comment: Hi thanks for ur help... But still i want to match also 1.6.2 or any version numbers with periods... for example 1.2.5 or 188.8.131.52
Comment: OK, I changed my answer according to your last comments. See if it works.
Comment: Thanks... But the problem is it was matching the string 1.25.655. (see here there is a dot at the end). It was returning 1.25.65. But it is incorrect version number    :(   And can u explain me how to do write this in java. I want that matched version number as output.
Comment: Thanks for counter-examples, I fixed my answer properly and explained with sample code. Please, give me feedback about the results.
Comment: Hi mmdemirbas, Thanks for ur help in completing this issue. It was working fine. But there is some problem with the parsing again. If the string is "DB2 10.5 fix" it was returning 2 10.5. and if there are any years like "DB2 release 2009" it was returning 2009.. Can u please help me solving this last fix..   :(
Comment: @SrinivasB Sorry, I have forgotten to escape dot (`.`) in `(.\d+)`. Escaping it fixes these errors. I updated the answer.
Answer: (?<![\d.])(\d+[.])+(\d+)(?![\d.])
Check this...
It will match the string of the form
number.number.number.number
not followed or preceded by a dot
Answer: For Strings like 1.5.6 you can just use:
[0-9](.[0-9])+
http://regexr.com?31ubo
Answer: Use the regex:
(^([jJ][dD][kK])([\s]*[vV]*\d+.\d+(.\d+)*))$

This would make your day :)
Answer: If you want to catch more than two numbers like "1.5.6" or "1.5.0" you can use
[0-9](.[0-9])+
Or if you only want the first two digits
[0-9].[0-9] , but this will not work on strings like 22.214.171.124, it will catch 1.5 and 0.0.
Comment: But it should take more than two precisions also.
Comment: The first regex also works for 22.214.171.124.7 or anything like (one digit Number).(oneDigitNumber)...


Some confusion about normal vector, curvature and normal curvature in Do Carmo's textbook.

Question: There is this part of a text from Do Carmo's Differential Geometry that I don't quite understand.

I understand the definitions of curvature, normal curvature, normal section etc. But what I am confused at is the part that says "In a neighbourhood of $p$, a normal section of $S$ at $p$ is a regular plane curve on $S$ whose normal vector $n$ at $p$ is $\pm N(p)$ or zero; its curvature is therefore equal to the absolute value of the normal curvature along $v$ at $p$."
First, is the neighbourhood of $p$ a part a curve $C$, a surface $S$ or a neighbourhood of $p$ on the normal section? It is not that clear. Especially when it mentioned the curvature it seems that it refers to the curve $C$.
Another thing that confuses me is why is the normal vector either $N(p)$ or zero? And why is the curvature equal the absolute value of the normal curvature?
Here is how I worked it out: $k_n=k\cos\theta$ and $\theta=0$, so $k_n=k$, where $k_n$ is the normal curvature. Am I correct? Or should I reason as follows: $n=0$, so $\cos\theta=<0,N>=0$, so $k_n=0$?
I have been looking back and forth for the definitions and tried to work it out myself but still couldn't really understand the text. Could someone please help clarify the confusion? Thanks.
Answer: "Neighborhood of $p$" refers to either a small region around $p$ on $S$, or a small regions around $p$ in 3-space -- either interpretation leads to the rest of the sentence. I'd choose the 3-space version.
Part 2: suppose that your surface is a cylinder, and your "curve" is one of the straight lines parallel to the axis of the cylinder. Then the curve-normal would be zero.
More generally: the plane chosen contains the surface normal $N$, right? That surface normal is perpendicular to the tangent plane of $S$ at $p$ (definition). And the tangent to any curve on $S$ that passes through $p$ is actually in the tangent plane to $S$ at $p$. (Indeed, some books define the tangent plane as the set of all tangents-to-curves-through-$p$.) So the tangent to the curve, which is a tangent to the surface as well, is perpendicular to $N$. And it lies in the slicing plane as well.
Now look in the slicing plane: you've got a curve in there whose tangent IS a surface-tangent. The curve-normal, for a plane curve, is always perpendicular to the curve-tangent. So the curve-normal must be perpendicular to the curve-tangent, AND lie in the slice-plane. And there's only one possibility (up to sign/scale). Now look at N: it's both perpendicular and lies in the plane. So it satisfies the conditions. So it MUST be the curve-normal in the plane.


i cant see my image when i draw it in pygame, even tho its in the same folder as my python script and other python modules i need for the script

Question: Im making a python program where i want to draw an image on my screen/surface with the module pygame, but when i try to draw the image, i dont see it. The image is in the same folder as my python script so that shouldn't be the problem. My syntax is also correct. So I don't know, i would appreciate if someone responds. Thanks!
import pygame,sys

pygame.init()
clock = pygame.time.Clock()
screen=pygame.display.set_mode((800,800))
second_surface=pygame.Surface([100,200])
second_surface.fill((0,0,255))

isaac=pygame.image.load('isaac.png')
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill((255,255,255))
    screen.blit(second_surface,(0,50))
    isaac.blit(isaac,(100,200))
    pygame.display.flip()
    clock.tick(60)

Comment: It is a typo. `isaac.blit(isaac,(100,200))` must be `screen.blit(isaac,(100,200))`
Comment: Hi, Welcome to SO. could you please add the output you are currently getting as well as your folder structure to help with debugging
Comment: yeah, that was actually the mistake, thank you!
Answer: Answer by Rabbid76:
Where it says isaac.blit(isaac,(100,200)) it should be screen.blit(isaac,(100,200)).
Comment: There is a recommendation not to answer typo-question. Questions like these are off-topic and should not be answered but closed as they are not helpful to other contributors. The questions will be closed and finally deleted. If the question is deleted, your gained reputation points will be lost.
Comment: Because of this, I did not answer the question.


Setting access backcolor using variable color name

Question: I am pulling colors from a database field and I want that column to determine the color of a control on a form. So I know I can do this to statically set back color:
Me.txtPartNum.BackColor = vbRed

Now, I have a color red in my database so I tried doing:
Me.txtPartNum.BackColor = "vb" + varMyColor

However, this results in Run TIme error '13' Type Mismatch

How do I use variable colors to set the background color of forms or controls in a form.
Comment: `vbRed` is equivalent to `255`, i.e. `vbRed` is not the same thing as `"vbRed"`. I'd create a helper function here to parse the color stored as text, i.e. "red", and return the equivalent color constant.
Comment: But the color is entered by a user. Is there a place where I can get a list of colors codes equivalent to these constants. Are these constants hexadecimals. I can setup my database column to store hexadecimal numbers instead.
Comment: [This may be helpful](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/color-constants).
Comment: I ended up using the solution I posted
Answer: I ended us using this function which gives vbcolor values from hex values:
Function HexToLongRGB(sHexVal As String) As Long
    Dim lRed As Long
    Dim lGreen As Long
    Dim lBlue As Long

    lRed = CLng("&H" & Left$(sHexVal, 2))
    lGreen = CLng("&H" & Mid$(sHexVal, 3, 2))
    lBlue = CLng("&H" & Right$(sHexVal, 2))

    HexToLongRGB = RGB(lRed, lGreen, lBlue)

End Function


Is giving an argument the same name as the kwarg parameter bad practice in Python?

Question: I have written this code in Python 3;
dotenv_path = r"./../.env"
load_dotenv(dotenv_path=dotenv_path)

Notice how I have named the variable containing the path to the .env file the same as the name of the argument load_dotenv() takes. This results in ...(dotenv_path=dotenv_path)
Is this considered bad practice? If so, what can be done to more clearly differentiate between variables (apart from simply choosing a different name), not just in this specific context but in a broader sense, without compromising for reduced code readability and/or self-documentation?
Answer: It's unlikely to be considered bad practice, given that it is used more often than not in the major python packages; see e.g. a random pandas example here (takes a while to jump to the right line).
As for readability I would instead consider it beneficial to have identical names in both scopes whenever you are referring to the same thing. If appropriate, you can still use more specific names to refer to more specific concepts outside the function, such as the production environment file (e.g. dotenv_prod_path = r"./../.env.prod"; load_dotenv(dotenv_path=dotenv_prod_path)).
If you are concerned about reduced readability as it might be unclear which scope the name belongs to, I would suggest to keep methods/functions short and not to use  global and nonlocal variables.


How to set the sessions in .aspx according to the rows

Question: I face the following problem :
when I set my sessions in my aspx according to my requirements like this :
<Columns>
<asp:TemplateField ItemStyle-Width="10px">
<ItemTemplate>
<a id="btnShowPopup5" runat="server" class="thickbox" href='<%#"PopUp.aspx?AR=2"+"&TBiframe=true&height=530&width=750"%>'
<asp:Image ID="Image23" runat="server" ToolTip="Back" ImageUrl="Images/cross.png" />
<asp:HiddenField ID="HDN_TaskCode" Value='<%# Session["s_TaskCode"] = DataBinder.Eval(Container.DataItem, "TaskCode") %>'
runat="server" />

I note that : Session["s_TaskCode"] was set always with the first row task code value in the gridview!!
and this's not what i want.
I want to set my sessions according to the rows .
say my gridview has two rows :

The first task_code value is 7
The second task_code value is 10

I want to set the session with the correct value according to the hyper link i click on .
Like data keys.
Note : i want to set my sessions in the .aspx not .cs .
Answer: You have using only one Session Variable (Session["s_TaskCode"]) in your code. So, how can you retain multiple values in it. It will always contain the value last written to it.
To store row-wise values in session, you have to do something like:
Session["s_TaskCode" + rowIndex]
Here, rowIndex is <%# Container.DataItemIndex %>
So you can use like: <%# Session["s_TaskCode" + Container.DataItemIndex] %>
Edit:
Instead of session, why don't you pass the value of TaskCode in the 'btnShowPopup5' href url QueryString parameters:
href='<%#"PopUp.aspx?AR=2"+"&TBiframe=true&height=530&width=750&" + DataBinder.Eval(Container.DataItem, "TaskCode") %>'

Comment: <%# Container.DataItemIndex %> will give you rowIndex.
Comment: @just_name you can encode the sensitive data before passing it to QueryString.
Comment: Then with this way I will set the session with the first row value also plus the row index !!
Comment: yes, but you can always check if rowIndex = 0 then use Session["s_TaskCode"].
Comment: also i get compile error `The name 'rowIndex' does not exist in the current context`
Comment: no i want to set the session with the correct value according to the link click. cuz i use this value later
Comment: Could u update in my code `Value='<%# Session["s_TaskCode"] = DataBinder.Eval(Container.DataItem, "TaskCode") %>'`
Comment: I used the query string ,and then i find those data have to be more secure so i have to use sessions instead. and because we used `Thickbox` jquery i should use this method of setting the sessions in the `.aspx`


Inserting 200k records while parsing CSV locks up system

Question: I'm trying to insert 200k records into three different tables. When I parse the CSV file and try to insert these records, Ruby locks up my entire system. Here is my code:
def upload_country
  @upload = Upload.new(:upload => params[:upload])
  if  @upload.save
  csv = CSV.parse(csv_text, :headers => true)

  csv.each_with_index do |row, index|
    unless row["name"].blank? or row["country_code"].blank? or row["destination"].blank? or row["code"].blank?
      @country = Country.new(:name => row["name"].gsub(/\s+/, " ").strip, :country_code => row["country_code"].gsub(/\s+/, " ").strip, :user_id => current_user.id, :subscriber_id => get_subscriber_id)
      @country.save

      if row["country_code"] == "1"
        p = @firstname.lastname@example.com+row["code"].gsub(/\s+/, " ").strip
      else
        p = @country.country_code.to_s+row["code"].gsub(/\s+/, " ").strip
      end

      @code = DestinationCode.create(:code => p, :country_destination_id => 1, :user_id => current_user.id)
    end
  end

  @upload.destroy
  @countries = Country.find_all_by_subscriber_id(get_subscriber_id)
  render :partial => '/mycarriers/carrier_country', :layout => false
end

Comment: The request takes long time to perform? creating 200k objects and insert them is probably not that fast. You should probably batch insert instead in some way.
Comment: @kashifali: how long did you leave it running?
Answer: If you have long-running requests, it means that no other users can access your application at that time if you have only one rails instance running.
I would recommend you use delayed_job gem to do long processing task in the background. On the controller side, you should enqueue the job and response 202 (Accepted) to the browser. On the client side, you should periodically send the request to the server whether the job is finished or not. Then, update the ui accordingly.
Take slideshare.net as an example. When the user finishes upload, slideshare redirect to the new page, and periodically update ui while it converts the presentation file.
An alternative solution is that you can run rake script in the background. Check out this episode from railscasts.
Answer: why dont use use Mass Insert here a gem that can help you in the quest I personally used it in my application to insert 500K records with resque for the background processing
Hope it help you


For Loop help, checking prime numbers

Question:         for (int i = lo; i <= hi; i++)
    {
        boolean isPrime = true;  // each value of i starts out assuming it IS prime
        // Write a loop below that divides i by 2,3,4,5 etc upto i/2
        // If at any time you find a divisor that evenly divides i
        // Then set isPrime to false

        /* your prime checking loop HERE */
        for (int j = 2; j <= hi / 2; j++)
        {
            if (i % j == 0)
            {
                isPrime = false;
            }
        }
        // DO NOT REMOVE OR MODIFY LINE BELOW
        if ( isPrime )
            System.out.print( i + " " );
    }

Okay, here is the code I currently have and i'm assuming the problem lies within. The program takes a text input file and sets the first value as lo (in the text demo I have, the lo = 3 and hi = 73.) For whatever reason, the only numbers that are output as 'prime' start at 41 and then go totally fine after that. I have no idea why the first half of the numbers aren't being outputted at all.
Keep in mind I must use for loops for this project, methods and such are not in the 'vocabulary' at the moment. Trying to keep it simple. I'd appreciate the help guys.
Answer: Read the comment block again.  It says to loop until i/2.  You're looping until hi/2.
The issue is that you keep using modulus of the number on itself.
3 % 3 is zero, but 3 is prime.
Comment: Holy hell, can't believe I missed that. Thanks a bunch! Works great now!
Comment: Glad I could help!  Make sure you accept the answer.
Answer: the prime checking loop, choose one:
for (int j = 2; j < i / 2; j++)

or
for (int j = 2; j <= sqrt(i); j++)

For Loop help, checking prime numbers


Create DNS alias

Question: How i can create DNS alias?
ie.: i have one domain named example.com and second domain - example.net. Zone-file of first domain contents:

example.com. IN A 10.1.2.3
  www.example.com. IN A 10.1.2.3
  *.example.com IN CNAME example.com.

What should i write to second's domain zone-file, that redirected from http://www.example.net to http://www.example.com?
Answer: dns does not handle http redirection.. You can just cname example.net to example.com just fine.. but you would have to do the redirect on your webserver side
Comment: There is an example of what you want to do on Super User [**here**](http://superuser.com/questions/122810/apache-redirect-from-one-domain-to-another-domain)

Create DNS alias


Inject a file record through SQL

Question: I am currently trying to inject a value and file into a user field called "field_user_pdf".
I am adding values to the following tables which is successful initally:
field_data_field_user_pdf
field_revision_field_user_pdf
file_managed
file_usage

The user is then able to see the file on their user profile. The user does not have permission to add/edit the file themselves, only an admin does, using the field_permissions module.
However if they edit and save their profile, all record of the file is deleted from the database.
This behaviour does NOT occur if the file was added to the user by an admin in the CMS, it only occurs when the file is inserted in MySQL by circumventing Drupal.
I have come to the above tables by both scrutinizing MySQL Insert logs as well as MySQL Database Dump diffs before and after.
Is there a table or column I am overlooking? Is there any where I can view the SQL Schema for inserting SQL for file fields?
Comment: Why are you trying to do it this way? Can you use hook_user_insert() and hook_user_update()?
Comment: It's an external service that needs access to the Drupal backend in order to inserts file into the site. It extracts user information, compiles a PDF and then the idea is to associate that PDF back with the user. The external service is written in Python and so we're trying to glue the 2 services together, and figured the common ground is MySQL
Answer: What you are doing, sorry, is plain wrong. There is a field API and you should use it instead of messing around with the SQL tables. If you are going around the field API and it breaks, you truly get to keep both parts. I find it astonishing you expect support for going around such a complex API.
Comment: I understand the horror of the situation, unfortunately it's an external service written in a different language (python) that needs to insert values into a drupal site. This marriage is also throw away so quick-and-dirty is the order of the day.

Inject a file record through SQL


List most recents files used

Question: We have a Documents bundle which is a list of documents, and an Accordeon which includes the previous one.
NODE_PAGE
|
|--- DOCUMENTS
|
|--- ACCORDEON
|    |
|    |--- DOCUMENTS

With this choice, I can attach documents directly to the node or to Accordeon sub-elements.
How can I list the most recent documents in a view? (I have to mix file_managed directly linked to the node and file_managed linked to the paragraph which is linked to the node.)
Is it possible from the view setting, or do I have to alter the query with hook_views_query_alter()?
Comment: I take you mean that the second content type has an entity reference field that references nodes of the first content type. In Drupal, a content type cannot contain another content type.
Comment: @kiamlaluno : I am using "paragraphs" so DOCUMENTS is a paragraph, and ACCORDEON is also one.

And my problem is I don't know how to access to a paragraph that is in a paragraph using Views .
Answer: Finally I choose to create a View of type File and to alter data with the hook_views_pre_render(). I can now do queries and other custom treatments and set the results data of my view.

List most recents files used


Getting an IP Allocation from ARIN

Question: The datacenter I am looking to Colo with is being very stingy about IP addresses, only giving me 8 for a quarter rack. I need like 40 and am planning to need a lot more. I saw on the Arin site that I could get about 4k ipv4 for about $1250, is that a total cost or is that annually. Also once I have the IP address allocation what do I do with it, i hear i need a bgp router, would the data center have one, is this something I would need? Any help would be great, thanks!
Comment: Would you mind describing (generally) why you need 40 IPs within a quarter rack?
Comment: IPv4 addresses are running out, so the price will go up dramatically in the near future. I would consider architectural changes to reduce IP address usage. If you're doing SSL hosting, you might be stuck, but certificates with alternative principal names can reduce your IP usage by a huge amount.
Comment: We are a hosting company with many VMs and we give each client their own ip associated with their VM.
Comment: "The datacenter I am looking to Colo with is being very stingy about IP addresses." Pick a different colo?
Comment: @embobo Perhaps the ipcalypse/arpageddon started early?
Answer: ARIN is pretty strict about their allocations, especially in recent years. Unless you can demonstrate a need for a /20 or a /22 they all but require you to get your addresses from an upstream provider. You might have an easier time buying additional IPs from your hosting provider. If they won't or can't give you additional addresses then that's probably a good indication that you should look for a different provider.

Getting an IP Allocation from ARIN


Dimension of Tensor Product Space should be $\leq \dim(V)+\dim(W)$

Question: Let $V$ and $W$ be two vector spaces of dimensions $m$ and $n$ over the same field $F$.
$V \otimes W$ is defined as the vector space of equivalence classes of vector space $F(V \times W)$ with bases as the tuples of form $(v,w)$ under the relation specified by:
$$
\begin{align}
(v_1 + v_2, w)&=(v_1, w)+(v_2, w)\\
(v, w_1+w_2)&=(v, w_1)+(v, w_2)\\
(sv,w)&=s(v,w)\\
(v,sw)&=s(v,w)
\end{align}
$$
Now in the following, I try to construct a representation of each equivalence class.
Let
$$z = a_1(v_1,w_1)+a_2(v_2, w_2)+ ... + a_n(v_n, w_n) \in F(V \times W)$$
Then:
$$
\begin{align}
z &\sim a_1(v_1,w_1)+a_2(v_2, w_2)+ ... + a_n(v_s, w_s) \qquad (1)\\
  &\sim (a_1v_1,w_1)+(a_2v_2, w_2)+ ... + (a_sv_s, w_s) \qquad (2)\\
  &\sim (a_1v_1+a_2v_2+...+a_sv_s, w_1+w_2+...+w_s)
\end{align}
$$
where, $a_i \in F, v_i \in V, w_i \in W$ for $i=1,2, ..., s$.
Now the additions, are in original vector spaces, $V$ and $W$, rather than $F(V\times W)$, so we can just perform the addition and get some element $v$ of $V$ in the first slot and some element $w$ of $W$ in the second slot of the tuple.
So we see that the equivalence class of any $z \in F(V \times W)$ can be represented by $(v,w)$, where $v \in V$ and $w \in W$. But are these representations, unique?
In going from step $(1)$ to $(2)$, each of the $a_i$'s could have been moved in front of either $v_i$ or $w_i$, and the equivalence class would still have been the same. But, the final vectors in the two slots of the tuple would have been different. This suggests there are different representations of the same equivalence class.
In other words, we may not have unique equivalence classes corresponding to each tuple of the form $(v,w)$. So, we let $\{v_1, v_2, ..., v_m\}$ and $\{ w_1, w_2, ..., w_n \}$ be a particular basis of $V$ and $W$, and proceed further:
$$
\begin{align}
(v,w) &\sim (\sum_{i} \alpha_i v_i, \sum_{j} \beta_j w_j)\\
      &\sim \sum_{i,j} (\alpha_i v_i, \beta_j w_j)\\
      &\sim \sum_{i,j} \alpha_i \beta_j (v_i, w_j)
\end{align}
$$
Previously we showed that all equivalence classes had a representation: $(v,w)$. And now, we have shown that all equivalence classes have a representation of the form $\sum_{i,j} \alpha_i \beta_j (v_i, w_j)$. As the set:
$$\{(v_i, w_j) | i \in [m], j \in [n]\}$$
spans the equivalence classes, and as there are at most $m+n$ variables that we choose here, ($m$ $\alpha_i$'s and $n$ $\beta_j$'s), I don't see how the Tensor product could possibly have dimension as $m \times n$.
Where did I go wrong?
Comment: I agree with your (1) and (2), but your next line is wrong.
Comment: Dimensions multiply.
Answer: You're allowed to do
$$
(v_1,w)+(v_2,w)\sim(v_1+v_2,w),\qquad
(v,w_1)+(v,w_2)\sim(v,w_1+w_2)
$$
but it's generally false that
$$
(v_1,w_1)+(v_2,w_2)\sim(v_1+v_2,w_1+w_2)
$$
which you are using in the line after $(2)$.
If you denote by $K$ the subspace of $F(V\times W)$ generated by the given relations, then the idea is that the map $\tau\colon V\times W\to F(V\times W)/K=V\otimes W$ defined by
$$
\tau(v,w)=(v,w)+K=v\otimes w
$$
is bilinear. It' cannot be also a linear map if you endow the set $V\times W$ with the componentwise operations, unless one of the spaces is the trivial vector space. You may try your hand on this exercise.


Finding fixed points

Question: I am trying to find the fixed points of the following system,
$$x'= y$$
$$y'= x \cos y$$
By setting $x'=0,y'=0$
From the first equation it gives us that $y=0$ then if $y=0$ in the first equation then since the $\cos 0=1$ then x must be $0$
So are the only fixed points from this system $(0,0),(0,1)$
?
Comment: that is the only fixed point? (0,0)?
Comment: ah no it doesn't, thanks I did not see this originally. Silly mistake
Answer: Fixed point means that
$$x'=x \\
y'=y$$
Setting this in your system you get
$$y=x \\
x \cos(y)=y $$
Therefore, the fixed points are given by $(y,y)$ where
$$y \cos(y)= y \Leftrightarrow y=0 \mbox{ or } \cos(y)=1$$
Comment: so then what are the fixed points? (0,0)?
Comment: @fr14 $\cos(y)=1$ has infinitely many solutions.
Comment: so then how do I show its fixed points?
Comment: @fr14 You just solve $\cos(y)=1$. You should know the solutions, they are....
Comment: yeah so if I set y to answer number besides 0 then this will not be true for x' correct?
Comment: @Moo Why do you need them equal to $0$? Fixed point means $T(z)=z$.
Comment: @fr14 What is YOUR definition of fixed point?

Finding fixed points


counting particular rows in a table in zend framework

Question: I am trying to count rows in a table that match a particular column called cat_id. I'm stuck getting this error:
Message: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

This is the code I have so far:
public function getNoJobs($id)
{
    $select=$this->_db->select();
    $select->from('job','COUNT(id)');
    $select->where('cat_id=?',$id);
    $result=$this->getAdapter()->fetchAll($select);
    return $result;
}

I call this from an action called index. The $result is the cat_id i get from a form:
$result=$this->_request->getParam('category');
$validate=new Application_Model_DbTable_Procedure();
$job=$validate->getNoJobs($result);

What am I doing wrong?
Comment: This is most probably because `$id` is null or undefined.
Comment: Can you add a zend tag, please?
Comment: @EngineerDollery Any idea if that was the correct tag?
Comment: After : $select->where('cat_id=?', $id); , try die($select->__toString()); you will see if you have a valid SQL query.
Comment: your category parameter value is empty. post the uri here.
Answer: Most probably it is that $id is NULL as @sbooob suggested.
This question and Why you should always validate your data in every function especially in models are answered here:
https://stackoverflow.com/a/6679842/840409
What I would like to add as a tool is a live "on-site" debugger like ZFDebug if you've had it on you'd most probably already seen the answer for your self since you'd be able to monitor all the generated queries. I strongly encourage using such tools.


Is this MEAN stack design-pattern suitable at the 1,000-10,000 user scale?

Question: Let's say that when a user logs into a webapp, he sees a list of information.
Let's say that list of information is served by one of two dynos (via heroku), but that the list of information originates from a single mongo database (i.e., the nodejs dynos are just passing the mongo information to a user when he logs into the webapp).
Question: Suppose I want to make it possible for a user to both modify and add to that list of information.
At a scale of 1,000-10,000 users, is the following strategy suitable:

User modifies/adds to data; HTTP POST sent to one of the two nodejs dynos with the updated data.
Dyno (whichever one it may be) takes modification/addition of data and makes a direct query into the mongo database to update the data.
Dyno sends confirmation back to the client that the update was successful.

Is this OK?  Would I have to likely add more dynos (heroku)?  I'm basically worried that if a bunch of users are trying to access a single database at once, it will be slow, or I'm somehow risking corrupting the entire database at the 1,000-10,000 person scale.  Is this fear reasonable?
Answer: Short answer: Yes, it's a reasonable fear. Longer answer, depends.
MongoDB will queue the responses, and handle them in the order it receives. Depending on how much of it is being served from memory, it may or maybe not be fast enough.
NodeJS has the same design pattern, where it will queue responses it doesn't process, and execute them when the resources become available.
The only way to tell if performance is being hindered is by monitoring it, and seeing if resources consistently hit a threshold you're uncomfortable with passing. On the upside, during your discovery phase your clients will probably only notice a few milliseconds of delay.
The proper way to implement that is to spin up a new instance as the resources get consumed to handle the traffic.
Your database likely won't corrupt, but if your data is important (and why would you collect it if it isn't?), you should be creating a replica set. I would probably go with a replica set of data before I go with a second instance of node.
Comment: So the bottleneck isn't going to be the node dynos, it's going to be the fact that there's only one db?  What do you mean "spin up a new instance as the resources get consumed" -- spin up a new instance in node?
Comment: @George Well not necessarily, but unless your application is CPU intensive, your bottle neck will most likely be the database writes/reads. 1k-10k isn't a huge number of users unless they all decide to use it at the same second. Are you already hitting this number with your users? I used the term instance as in EC2 instance, but I meant Dyno in your case. (Dynos are fractional uses of EC2 instances). Heroku has Adept Scale, which will +/- Dynos automatically, but you still need to optimize your app to use it properly. Starting point https://devcenter.heroku.com/articles/node-concurrency


What would be good ways, preferably books, to practice dynamics on drums

Question: After working out both hands practicing technique, it would be interesting to work on dynamics. However, apart from the advice to "play with others" I have not really seen a more concrete pointer. The book Jazz Workshop is good and I'm wondering if there are other books that address dynamics specifically when playing drums.
I'm aware of the exercises where one can adjust the volume of one specific limb or a drum but I'm wondering if there is more theory available on when/how to play soft or hard, etc. This may go into composition, arrangements, and orchestration, and it would be ok to address these topics at the same time.
Comment: Listen critically to some jazz. Except in big band pieces, dynamics are almost never marked in jazz, and depend mostly on coordination between the members of the rhythm section and their reactions to the dynamics and movement of the current soloist.
Comment: Only now I've found a very similar question [here](https://music.stackexchange.com/questions/27296/books-on-orchestration-specializing-in-dynamics).
Answer: Maybe not the sort of answer you're looking for. The when to play soft/hard will be directed by the piece in question, and who's playing what at that moment. Dynamics can be practised, but good drummers are listening all the time, and should complement the dynamics of the band in each number, sometimes even dictating them. Reading about this may put you on the nursery slopes. The how will depend on kit, sticks, damping and you. While you're at it - learn to play quietly and still swing. I've never met anyone who didn't like working with a drummer who could do that. Seriously!
If there's no others to play with, to get used to varying dynamics, then there's always 'Music minus One' - recordings of songs, less a particular instrument, as the title suggests. Certainly available on CD, and probably other formats now, they become your personal tame band.
If you are a reading drummer ( dots, not books!) then the dynamics should already be on the sheets.
Comment: Thanks, Tim! I'm not looking for any specific answer but rather wishing to see the approach others are taking at this. And, yes, perhaps books are not the best way to teach/learn this topic. Your note about listening is the key. I assume one has to listen and play actively all the time. You also point out probably the only exercise one can do - play the same groove but very softly or at different levels. This will help when expressing oneself later during the "real" play with others.


Como pegar o valor de um input type="month" no qual traz mês e ano e separá-lo em duas variáveis (mes e ano)

Question: Tenho um input type="month" no meu HTML, no qual seleciono nesse campo o mês e ano.
Essa informação chega no JavaScript no formato "mm/AAAA" conforme código abaixo:
<input type="month" id="month" />

No JavaScript, pego o value desse input conforme trecho abaixo:
let datainput = document.getElementById('month').value;

O retorno do datainput é "09/2022" por exemplo.
Porém, preciso separar o mês e o ano em variáveis diferentes dentro do JavaScript.
Como posso realizar isso?
Comment: `const [mes, ano] = datainput.split('/');`
Comment: `var data = new Date(datainput.value);   data.getMonth() data.getFullYear()`... input retorna uma strg que pode ser passada por parâmetro no Date que retorna inteiro. só o mês que inicia apartir de 0 a 11.
Answer:
Essa informação chega no JavaScript no formato "mm/AAAA"

Tem certeza? Pois segundo a documentação e a especificação, o value de um campo input type="month" sempre é uma string no formato "YYYY-MM" (para browsers que suportam este tipo, claro).
O que acontece é que o browser pode mostrar o campo em um formato diferente. Mas internamente o value sempre é "YYYY-MM". Faça o teste, preencha uma data e clique no botão "Mostrar value" (mas teste em um browser que suporte o tipo month):

function mostrarValue() {
    console.log(document.getElementById('month').value);
}
<input type="month" id="month" />
<button onclick="mostrarValue()">Mostrar value</button>

Cada browser vai exibir o campo em um formato diferente. Estou usando Chrome configurado em inglês, então para mim mostra os nomes dos meses em inglês:

Já no Firefox, atualmente (setembro/2022) ele ainda não suporta este tipo, então só aparece como um input text simples (que eu posso digitar qualquer coisa). A documentação cita meios de contornar isso, mas acho que está além do escopo da pergunta.

Enfim, para browsers que suportam o input type="month", o value sempre estará no formato "YYYY-MM", então uma forma de separar os campos é com um split simples:

function separarAnoMes() {
    let [ano, mes] = document.getElementById('month').value.split('-');
    console.log(mes, ano);
}
<input type="month" id="month" />
<button onclick="separarAnoMes()">Separar ano e mês</button>

Lembrando que o value é uma string, e o resultado do split é um array de strings. Então meses anteriores a outubro terão o zero à esquerda (02, 05, etc). Mas se quiser que sejam números (sem o zero à esquerda), basta trocar para:
let [ano, mes] = document.getElementById('month').value.split('-').map(v => parseInt(v));

Outra forma é pegar o valor como uma data (um objeto Date), usando valueAsDate em vez de value, assim seria possível obter o mês e ano usando os getters, como foi sugerido nos comentários. Mas tem uma "pegadinha", veja:

function mostrarValue() {
    var date = document.getElementById('month').valueAsDate;
    console.log(date.toString()); // data no fuso do browser
    console.log(date.toISOString()); // data em UTC
}
<input type="month" id="month" />
<button onclick="mostrarValue()">Mostrar value</button>

A saída pode variar de acordo com o fuso horário que está configurado no seu browser (que geralmente é o mesmo do sistema operacional). No caso, o meu está configurado no Horário de Brasília, e eu escolhi o mês de maio de 2022. A saída foi:
Sat Apr 30 2022 21:00:00 GMT-0300 (Brasilia Standard Time)
2022-05-01T00:00:00.000Z

Pois é. Ao converter o valor do campo (que só tem mês e ano) para uma data, ele preenche os campos faltantes com valores default (no caso, dia 1 e horário meia-noite), mas tudo isso em UTC. Só que 1 de maio à meia-noite em UTC equivale a 30 de abril às 21h no horário de Brasília. Então se eu usar getMonth() para obter o mês, não necessariamente será o mesmo que foi preenchido. Felizmente existe getUTCMonth() para obter o mês em UTC. Portanto, seria algo assim:

function mostrarValue() {
    let datainput = document.getElementById('month').valueAsDate;
    let mes = datainput.getUTCMonth() + 1;
    let ano = datainput.getUTCFullYear();
    console.log(mes, ano);
}
<input type="month" id="month" />
<button onclick="mostrarValue()">Mostrar value</button>

Lembrando que em JavaScript os meses são indexados em zero (ver mais aqui e aqui), ou seja, janeiro é zero, fevereiro é 1, etc. Por isso precisei somar 1 no código acima.
Lembrando que o código acima retorna os valores numéricos, portanto valores menores que 10 não terão o zero à esquerda. Se deseja que tenha, teria que gerar uma string com mes.toString().padStart(2, '0').
Answer: Você pode usar o .split() para separar a string pelo '/' da data.
A função .split() retornará um array, no qual o índice 0 será o mês e o índice 1 será o ano.
Exemplo:
let datainput = document.getElementById('month').value;

let dataString = datainput.split('/') // Retornará ['09', '2022']
let mes = dataString[0]
let ano = dataStrig[1]


Saving video with title or file name

Question: I am working on an app that saves video to the user's library. I would like to display the videos with a user inputed title on a table view controller, like "Amy's 1st Birthday." This is my first time working with the Photos Framework and AVFoundation, and I'm not sure how to begin.
My guess to build a object model to save a title string with the saved video, but I'm not sure how to associate it with the video being saved. Is there a property of PHAsset that will let me do something similar?
Can someone point me in the right direction?
Answer: You may associate the title with the PHObject's localIdentifier property which is unique for every asset.
Comment: can i later on get on chronological order?
Comment: You can set a predicate on fetchAssetsInAssetCollection's options parameter. And like any other NSPredicate you set the predicate sort descriptors and predicate condition (for localIdentifier comparison & sorting via creationDate property).
Comment: i just used a timestamp and and identifier in last...and that worked as

Saving video with title or file name


OpenIdDict 3.0 error from ASP.NET Core 3.1 web application

Question: I am hosting my ASP.NET Core 3 web application in Azure, whenever I do a new publish to Azure, it works as expected. However, the next day, the site is down, then I need to republish again, then it works, then it is down again the following day.
The full error message from Azure is this:

Application '/LM/W3SVC/975757150/ROOT' with physical root 'D:\home\site\wwwroot' hit unexpected managed exception, exception code = '0xe0434352'. First 30KB characters of captured stdout and stderr logs:
Unhandled exception.
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Keyset does not exist
at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)
at Internal.Cryptography.Pal.CertificatePal.<>c.b__66_0(CspParameters csp)
at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func2 createCsp, Func2 createCng)
at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate1 matchesConstraints)   at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)   at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()   at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKeyStatus()   at Microsoft.Extensions.DependencyInjection.OpenIddictServerBuilder.AddSigningKey(SecurityKey key)   at Microsoft.Extensions.DependencyInjection.OpenIddictServerBuilder.AddSigningCertificate(X509Certificate2 certificate)   at ackids.Startup.<ConfigureServices>b__6_6(OpenIddictServerBuilder options) in D:\ackidsRepos\ackids\ackids\Startup.cs:line 154 at Microsoft.Extensions.DependencyInjection.OpenIddictServerExtensions.AddServer(OpenIddictBuilder builder, Action1 configuration)
at ackids.Startup.ConfigureServices(IServiceCollection services) in D:\ackidsRepos\ackids\ackids\Startup.cs:line 118
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.g__Startup|0(IServiceCollection serviceCollection)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.b__0(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at ackids.Program.Main(String[] args) in D:\ackidsRepos\ackids\ackids\Program.cs:line 16
Process Id: 14164.
File Version: 13.1.21196.18. Description: IIS ASP.NET Core Module V2 Request Handler. Commit: 0a2e366eaf4d29b24b9a98e5782a04bef573189e*
Comment: Are you able to access in local now ? Could you please share your .csproj reference packages ?
Comment: Yes , I can run the web site locally.
Comment:
Answer: The reason for this error might be the The OpenIddict versions that you are using which are not compatible for ASP.NET 3.1.

Try upgrading to the latest versions.
Comment: I have upgraded to the latest version, and wait to see if it resolves the problem, thanks.