If $2u$ is an element of the subspace $W$, is $u$ also an element of $W$?

Question: Suppose $V$ is a vector space over an arbitrary field $\mathbf{k}$, $W$ is a subspace of $V$, and $u \in V$.
The question is: if $2u \in   W$, then is $u \in W$?.
Intuitively I think this is true, because if $W$ is a subspace then it's closed under scalar multiplication, so if $u\in W$, then $cu\in W$ for all $c \in \mathbf{R}$. But I'm not sure how to show this as a proof, or if my statement is enough.
Comment: It really depends on the field of scalars the Vector space is build on. If $2$ has a multiplicative inverse, then yes.
Comment: @b00nheT  We haven't gotten to multiplicative inverse yet
Comment: Since you said "over an arbitrary field," I am going to assume multiplicative inverses are implied to be assumed knowledge. In this case, since it is a field, the answer to your question is "yes".
Answer: If you are dealing with real vector spaces, for instance, then yes, it is true. If $2u\in W$, then$$u=\frac12(2u)\in W.$$
Comment: I'm not really sure what you said proves
Comment: If $2u \in W$, and $W$ is closed under scaler multiplication, then multiplying it by scaled $1/2$ means its still in $W$. But since the field is $\mathbb{R}$, we get back $u$ which is in $V$ to begin with.
Comment: @LtotheV I am. Where do you think there is a mistake?
Answer: You said that you don't know what it means to be invertible. If you have a field $\mathbf{k}$, an element $x\in \mathbf{k}$ is said to be invertible if there exists some element $y\in \mathbf{k}$ such that $xy=1$. Take for example any nonzero element in $\mathbf{R}$ or $\mathbf{C}$.
Let $\mathbf{k}$ be our field, and let $\lambda\in \mathbf{k}$ such that $\lambda$ is invertible. Then for a $\mathbf{k}-$Vector space $V$, with a subspace $W$ such that $v\in W$, we have
$$\lambda v\in W\iff \lambda^{-1}(\lambda v)\in W\iff (\lambda^{-1}\lambda)v\in W\iff v\in W.$$
This follows from closure of subspaces under scalar multiplication by $\mathbf{k}$. Of course, in the case where $\lambda$ is not invertible, this might not be true. Take $\mathbf{Z}/p\mathbf{Z}$, for $p$ some prime. Then $pv\in W$ for any choice of $v$, because $pv=0$, but $v$ might not be an element of $W$.
Answer: If $2\in {\bf k}$ is invertible, which is equivalent to $2\neq 0$ since ${\bf k}$ is a field, then $$2u\in W \implies u = 2^{-1}(2u)\in W.$$
The problem is when the field ${\bf k}$ is of characteristic $2$.


Regularization: How do you penalize weights of some exact value?

Question: Assume we have a loss function of the form:
L(f(X; theta),T) where X is the input dataset and T is the target dataset?
Then you would update the the paramters by doing
p = p - p.grad
where p.grad is the gradient achieved through gradient descent (not important here)
then I understand that L2 norm is a method of regularisation used to penalize large weights.
~L = L(f(X;theta),T) + (lambda/2) * (frobenius norm)
consequently, p = p - lr * p.grad - lambda * p
But what if I want to discourage weights of some exact magnitude. What If I want to penalize weights that are near +-0.75 more than others? Is that possible? How would the new loss function look like?
edit: Could I simply make a function of theta that increases as theta approaches 1? then that would magnify lambda (the scaling factor of the penalty) for values near 1.
Comment: you can used whatever regularization term you want. just choose a function that is large where you want it to be
Comment: but what if the loss function the model uses is predefined and cant be changed. Then what I can do is update p such that my new constraint of penalizing weights near 0.75 occurs. So I want to influence p every epoch in addition to just updating it with its gradient. How would I do that?
Comment: If you want to use gradient descent (GD), you have to change your loss function as @J.Delaney said. What you are suggesting here is changing the method of gradient descent. You could, of course, try this but you would have to make sure that your new optimization method, that replaces GD, is still actually optimizing the parameters theta in some more or less satisfying way. This is not that easy. The best bet is to change your regularization. Maybe you should explain more why you have to penalize a special theta and also why you cannot change the regularization. Maybe there are workarounds.
Answer: A solution I can think of is adding a function of $\theta$ that tends to infinity to the lost function. For example, $\frac{1}{\theta+1}+\frac{1}{\theta-1}$ would be a good choice. For your example, swap 1 with 0.75
This is an interesting question.
If anyone knows a much better solution, let me know.


Partial expectation of a function of a lognormal random variable

Question: Let $X$ be a lognormal random variable with pdf $f(X)$ and cdf $F(X)$.
The mean and variance of $X$ are assumed to be $\mu$ and $\sigma^2$ respectively.
If we assume any constant $k \ge 0$ and $0 < \alpha < 1$, how can we calculate following partial expectation?
$$\int_k^\infty x^{1-\alpha} f(x) dx$$
Comment: Welcome to MSE. It will be more likely that you will get an answer if you show us that you made an effort.
Comment: I know that $X^{1-\alpha}$ is also lognormal and its mean and variance are $\mu (1-\alpha)$ and $(\sigma (1-\alpha))^2$.
Comment: And partial expecation of lognormal can be written as a function of standard normal cdf $\Phi(\cdot)$ as follows: $$\int_k^\infty x f(x) dx = e^{\mu + \frac{1}{2} \sigma^2} \Phi \left( \frac{\mu + \sigma^2 - \ln k}{\sigma} \right)$$
Comment: Do you mean that the mean and variance of $\ln X$ are assumed to be $\mu$ and $\sigma^2$ respectively?
Answer: We assume that the the mean and variance of $\ln X$ are $\mu$ and $\sigma^2$ respectively. That is, $X=e^{\mu+\sigma\xi}$, where $\xi \sim N(0, 1)$ is a standard normal random variable. Then
\begin{align*}
\int_k^\infty x^{1-\alpha} f(x) dx &= \mathbb{E}\left(\mathbb{I}_{X\ge k} X^{1-\alpha} \right)\\
&=e^{(1-\alpha)\mu}\mathbb{E}\left(\mathbb{I}_{\xi\ge \frac{\ln k-\mu}{\sigma}} e^{(1-\alpha)\sigma \xi} \right)\\
&=e^{(1-\alpha)\mu}\int_{\frac{\ln k-\mu}{\sigma}}^{\infty}\frac{1}{\sqrt{2\pi}}e^{(1-\alpha)\sigma x} e^{-\frac{x^2}{2}}dx\\
&=e^{(1-\alpha)\mu}\int_{\frac{\ln k-\mu}{\sigma}}^{\infty}\frac{1}{\sqrt{2\pi}}e^{-\frac{(x-(1-\alpha)\sigma)^2}{2}+ \frac{(1-\alpha)^2\sigma^2}{2}}dx\\
&=e^{(1-\alpha)\mu + \frac{(1-\alpha)^2\sigma^2}{2}}\Phi\left(\frac{-\ln k +\mu + (1-\alpha)\sigma^2}{\sigma} \right),
\end{align*}
where $\Phi$ is the cumulative distribution function of a standard normal random variable.


Piano exercise for sequencing right hand chords with fixed top-most note

Question: Is there a diagram of all chords with the same melody note on top? with voice leading? with 7th?

Eb G C |  E G C |  E  A C  |
F  A C |  F A D |  F# A D |
b3 5 1.   3 5 1.   3  6 1.

When one is playing harmony in the right hand, the melody note must be on top.  The exercise(diagram-treble clef notation) requested is to practice all common chords with C on top.  Above we have Cm C Am F then we move to Dm with D on top then D triad.
I currently play harmony L hand melody R hand.  I would like to play shells in the left hand & harmony R hand.  In order to do this from a lead sheet, one must play the melody with the pinky then the rest of the chord with the other fingers RH.  I am trying to practice all chords with C on top, all chords F on top, all chords Bb on top or
stepwise C D E F# on top.
Comment: I'm not sure I understand. What are the notes listed here the melody notes?
Comment: I think the OP wants something like a regular piano chord diagram listing, but grouped according to the highest note instead of the root note. All triads, sus4 chords, sevenths etc. that have a C note, in an inversion that has the C on top. Dbmaj7: Db-F-Ab-C, Dbmmaj7: Db-E-Ab-C, Dbmaj7sus4: Db-Gb-Ab-C, Dbmaj7-5: Db-F-G-C, ... E7+5/D: D-E-G#-C ... G7sus4/D: D-F-G-C ... F#7-5/E: E-F#-A#-C ... C7sus4/F: F-G-Bb-C ... Fm6/D: D-F-Ab-C ... It's a very long list. There are 11*10=110 three-note combinations with C on top, and 11*10*9=990 four-note combinations with C on top, inside one octave.
Comment: A diagram of all the chords would be the piano keyboard itself... This question is unclear, because you do not specify the chords you're after (there's a ton), and, given the context, it is not clear what "voice leading" is. You could identify the scale in which the piece is played, and then use [an online tool](https://www.scales-chords.com/chordid.php) to look up some of the available chords.
Comment: piiper is the only one who understands. I did develop an exercise: Eb G C, E G C, E A C, F A C to F A D, F# A D
Comment: piiper is the only one who understands. I did develop an exercise: Eb G C, E G C, E A C, F A C to F A D, F# A D, F B D, G B D to G B E, G# B E, G# C# E, A C# E.
Comment: It seems like you want to have a chord on each note of the melody... are you trying to do 'block chord' style? https://en.wikipedia.org/wiki/Block_chord
Comment: @scidoc I understand your question as well but the way you wrote was a little unclear. I edited the question so you can get an answer
Comment: "with voice leading..." voice leading to where? If you make the list of chords like `Cm, Ab, etc.` with the `C` voiced on top, each of those chords can be voice lead to _any chord_. The permutations are gigantic, not practical. Worse yet you may end up with a chart of chord changes that aren't normal. @scidoc your comments example is roots by descending third which is common, but the minor/major changes are kind of atypical.
Comment: Are you wanting the top voice to be a sort of "ostinato"?  Or just an exercise, anyway?
Answer: I don't think such an approach would be useful.  Voicing and fingering will be very dependent on context.  You won't need a block chord under every melody note.  As @Pyromonk commented, the best exercise will be lots of sight-reading of printed arrangements and transcriptions in the style you favour.  You'll find the harmony notes shared out between the two hands in various, ever-changing ways.
Answer: Here's a pattern that hits every basic triad (dim, min, maj, aug) containing the target "top pitch", with a clear voice-leading pattern that progresses chromatically through all twelve "top pitches".
X: 1
T: Basic triad pattern
M: 4/4
L: 1/4
K: C
|[_E_GC'][E=GC'][E_AC'][E=AC']|[=EGC'][E^GC'][EAC']2|[F_AC']2[F=AC']2|[^FAC']4||[E^G^c]

Considered with the initial top note as the tonic pitch, the chord pattern is
io6 i6 (bVI)64 vi64 | I6 (I+)6 vi64 | iv IV | viio7/(bii = #i) ||
Presumably there is a similar pattern that would work for seventh chords; however, there would be 65 chords for each different "melody" note:

Five common seventh chords: dim, half-dim, min, dom, maj
Four of them have three inversions with the top note fixed: half-dim, min, dom, maj
Plus the fully diminished chord, for which all inversions are enharmonically equivalent
Thus, 4^3 + 1 = 65


Opacity issue in Internet Explorer and Opera

Question: I've problem with opacity for IE8 and Opera9-10. My little JS adds a CSS class to a row (<tr>) when users click on it. This is the class:
<code>.selected {
    opacity: 0.5;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"; /* IE8 */
    filter: alpha(opacity=80); /* IE7 */
}
</code>
Opacity is applied in Firefox and Google Chrome but not in IE and Opera.
Answer: From the IE Blog:
<code>.selected {
    opacity: 0.5;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"; /* IE8 */
    filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);  /* IE7 */
}
</code>
If this still doesn't work, it's probably an issue with some inheritance and we'll need to see  some scirpt and markup or an online example.
Answer: What happens if you apply your class to a single TD in the table? Does that work any better? Another option would be to use a PNG with alpha-transparency as a background image for the TR and apply this via your class (but this wouldn't work in IE6).
Comment: Applying opacity on td (for i.e. on click) doesn't work for Opera and IE :)
Comment: I see that on Opera opacity support in JQuery is enabled on IE no


Summarizing and visualizing a 3d data

Question: I need a visually appealing way to show 3d data. My data is a demand at time $t$ in region $r$ in scenario $w$, i.e., $d(t, r, w)$. $T$ is $15$, $W$ is $50$, $R$ is $250$.
One example: I can plot $\vert R \vert$ 2d plots with $x$-axis as time and $y$-axis as the demand, each graph will have $\vert W \vert$ scenarios. But this seems too much information, not well summarized.
Comment: Why do you switch from $t$, $r$, and $w$ to $T$, $R$, and $W$?
Comment: @ThePointer it is not a typo. small letters denote indices and capital letters denote the cardinality of the set.
Answer: Probably you could use a tool like Plotly. Take a look at the examples here: https://plotly.com/python/3d-scatter-plots/

Summarizing and visualizing a 3d data


activation functions of elman recurrent neural network

Question: From the Book"fundamentals of neural network", the input layer of a feedforward neural network has linear activation function. Elman recurrent NN is the same as a feedforward except that it has context layer. What should be the activation functions of each layer in an elman recurrent NN?
I have searched for this answer from many sources but many journal papers do not mention about the activation functions. Some information online says that the hidden layers should have tansig activation function.
So, What should be the activation functions of each layer in an elman recurrent NN?
Answer: An Elman network leaves the choice of the activation function to the user, since it only specifies these equations for the recurrence:
\begin{align}
h_t &= \sigma_h(W_{h} x_t + U_{h} h_{t-1} + b_h) \\
y_t &= \sigma_y(W_{y} h_t + b_y)
\end{align}
Variables and functions:

$x_t$: input vector
$h_t$: hidden layer vector
$y_t$: output vector
$W$, $U$ and $b$: parameter matrices and vector
$\sigma_h$ and $\sigma_y$: Activation functions

{1}, which is one of the most cited references defining an Elman network, doesn't seem to indicate that an Elman network should use some specific activation functions either.
FYI Comprehensive list of activation functions in neural networks with pros/cons

References:

{1} Elman, Jeffrey L. (1990). "Finding Structure in Time". Cognitive Science. 14 (2): 179–211. doi:10.1016/0364-0213(90)90002-E.  https://www.cs.swarthmore.edu/~meeden/cs63/f07/elman.srn.pdf ; http://dx.doi.org/10.1207/s15516709cog1402_1
Comment: Yes , i agree and thanks for replying. I saw these equations in most journal papers. But I needed some proof or some reliable sources to confirm your answer :/
Comment: @user7085565: sounds good I added one reference


how to move to the top an array element

Question: I have selected rows from a table
target row is a row having id equal to $_GET['id']
I want to move it at the top of rows
$sq = "select * from video order by ind asc";
$st = $db->prepare($sq);
$st->execute();
$rows = $st->fetchAll();

if(isset($_GET['id'])){
    foreach($rows as $row){
        if($row['id'] == $_GET['id']){
            unset($rows[$row]);  // error line
            $rows = $row + $rows;
        }
    }
}

error - Illegal offset type in unset...
also - is there a shorter way to do this, i.e. to avoid loop
something like:
$rows[having id equal to $_GET['id']] -> move-to-top

Answer: For this line,
unset($rows[$row]);  // error line

you need to unset the key in $rows and not $row itself which is a value in the foreach loop.
So, for unsetting it would look like:
<?php

foreach($rows as $key => $row){
    if($row['id'] == $_GET['id']){
        unset($rows[$key]);
        // code line to move to the top
        break;
    }
}

Don't use $rows = $row + $rows; kind of syntax as it makes it difficult to read during code reviews.
For a shorter syntax, you can use array_filter to filter out the row and then perform a swap taking the help of symmetric-array-destructuring.
Snippet:
<?php

$row = array_filter($rows, fn($arr) => $arr['id'] == $testID);
[$rows[array_keys($row)[0]], $rows[0]] = [$rows[0], $rows[array_keys($row)[0]]];

Online Demo
Comment: thanks a lot. Can't believe - there is no a function - to move elements up and down in php
Comment: @provance Glad to help. To be honest, it isn't really a very common use case for PHP devs to create inbuilt functions for such swaps. However, to push things to the end, you do have `array_push`, but to move to the top, it would involve reindexing the entire array.

how to move to the top an array element


Functional equation with integral: $ f(x) = \int_0^x f(s) \, \mathrm ds $

Question: I was hoping for some help with this integral relation. I would prefer hints to answers. I'm trying to find any solution to this relation:
$$ f(x) = \int_0^x f(s) \, \mathrm ds $$
I feel like it should be some variation of the exponential function that is $0$ for $x \le 0$, but I'm not sure.
Any help would be appreciated!
Comment: Try taking the derivative of both sides and remember FToC. You're going to be sad to know that the only analytic solution is $y = 0$.
Comment: Hint: substitute $x=0$ to get $f(0) = 0$.
Comment: @kaynex how is that the only solution? the fundamental theorem of calculus yields $$\frac{df}{dx} = f(x)$$
Comment: So the function can't change since the initial rate of change is 0 is the intuition I guess. @Kaynex I am sad indeed.
Comment: That's what I arrived at, leading me to believe that $e^x$ is a solution, but plugging into integral does not confirm that. I get $e^x = e^x - 1$. Am I doing something wrong?
Comment: @mlc cheers for that.
Comment: A [related](http://math.stackexchange.com/questions/815687) question.
Comment: What hypothesis do you have on $f$?
Answer: Take the derivative of both sides
$$\frac{d}{dx}f(x)=\frac{d}{dx}\int_{0}^{x}f(s)\space ds$$
Note that $\int_{0}^{x} f(s) ds=F(x)-F(0)$. The derivative of $F(x)$ is $f(x)$ and the derivative of $F(0)=0$. Hence
$$f'(x)=f(x)$$
There are two possiblities.
Once is $f(x)=0$, another is $f(x)=ce^x$
But if we substitute $f(x)=ce^x$ into the first equation the left hand side is
$$\frac{d}{dx}ce^x=ce^x$$
And the right hand side is
$$\int_{0}^{x}ce^s\space ds=ce^x-c$$
If set both side to equal eachother we get
$$0=-c$$
Hence $f(x)=0$ is the only solution.
Comment: I think the procedure is fine but you need to make some assumption on $f$


Problemas com file_get_contents e DOMDocument

Question: Estou tentando baixar o conteúdo de uma site, porém está dando este warning:

`DOMDocument::loadHTML(): Unexpected end tag : tr in Entity

E está indicando diversas linhas. também não estou conseguindo arrumar a acentuação.
Alguém poderia me ajudar a entender e solucionar estes problemas?
$content = http_build_query([
    'Local' => 'Adamantina',
    'Inicio' => '01/01/2015',
    'Final' => '31/12/2015',
]);

$context = stream_context_create([
    'http' => [
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $content,
    ]
]);

$contents = utf8_decode(file_get_contents('http://www.ciiagro.sp.gov.br/ciiagroonline/Listagens/BH/LBalancoHidricoLocal.asp', false, $context));

$dom = new DOMDocument();
$dom->loadHTML($contents);
$dom->saveHTML($dom->documentElement);

$xpath = new DomXPath($dom);
$rows = $xpath->query('//table/tr[position()>0]');

foreach ($rows as $row) {
    $tds=$row->getElementsByTagName("td");

    foreach ($tds as $td) {
        print($td->nodeValue);
        echo "
";
    }
}

Comment: assim:  `$rows = $xpath->query('//table');
$rows2 = $xpath->query('.//tr', $rows);

foreach($rows2 as $row){
 $tds=$row->getElementsByTagName("td");
 foreach($tds as $td){
  print ($td->nodeValue);
  echo "";
 }
}`  não funcionou
Comment: É, este não é o problema, veja se a resposta ajuda a questão.
Answer: Problema de Warning:
Para corrigir o problema do Warning você deve utilizar o libxml_use_internal_errors(), na verdade ele irá apenas ocultar os erros do libxml.

Utilize o seguinte:

libxml_use_internal_errors(true);

Fonte:  http://php.net/manual/pt_BR/function.libxml-use-internal-errors.php
Problema de acento:
Para corrigir o problema de codificação utilize o mb_convert_encoding(), isto irá converter para HTML, mas remova o utf8_decode() anterior!

Utilize o seguinte:

mb_convert_encoding($td->nodeValue, 'HTML-ENTITIES', 'UTF-8');

Fonte: http://php.net/manual/pt_BR/function.mb-convert-encoding.php

Altere para algo similar à isto:

$contents = file_get_contents('http://www.ciiagro.sp.gov.br/ciiagroonline/Listagens/BH/LBalancoHidricoLocal.asp', false, $context);

Removendo o utf8_decode().
Nota:

A maneira mais fácil para saber quando usar o HTML-ENTITIES, para mim, é saber que apresenta o ? ao invés de <?> (com fundo preto) ou algumas combinações de caracteres "aleatórios". Lógico, isto é apenas para mim, que vou chutando até funcionar.
Acredito que seja melhor usar cURL ao invés de file_get_contents(),

Estou sem tempo, desculpe, irei tentar melhorar a resposta em breve.
Comment: Descobri que o site que estou tentando pegar os dados tem problemas no desenvolvimento, então deve ser o problema dele. Mas obrigado pela ajuda.


How to calculate conditional probability

Question: I have data on average time a real estate property is in the market/time to lease at different price points.

I'd like to calculate the conditional probability for a new property to get leased, given the price.
Additionally, I'd like to include information about the market such as level of supply which affects the avg. time the property is on the market.
How would I frame this as a bayesian probability estimation problem?
Comment: Your plot is not relevant to your question: you want to swap the axes so that the software estimates average days as a function of price, rather than the other way around.
Answer: A simple way to obtain a conditional probability for your problem is to use a logistic regression.
A logistic regression is a way to model a conditional probability in which we assume that a binary variable $y$ is conditionally distributed over ${\bf x}=(x_1, \ldots, x_M)$ as
$$
t\vert{\bf x} \sim \text{Bern}(\sigma({\bf w}^T {\bf x}))
$$
You could obtain the expectation of the conditional distribution via maximum likelihood, a.k.a., minimization of the cross-entropy cost function, or follow a probabilistic approach and find the predictive conditional distribution.
To solve your problem via maximum likelihood you can use a library such as scikit-learn. I am not aware of any libraries that let you find the predictive conditional distirbution, but you can check this notebook for a guide on how to implement it.


IPBlockListProvider vs. IPAllowListProvider

Question: I am using Spamhaus SBL and Spamcop as RBL providers in Echange 2016 which works fairly well for me. However, some connections are blocked which really shouldn't. To prevent false positives I went on to configure IP allow list providers (list.dnswl.org to be specific).
Everything seems to be configured correctly, using Test-IPAllowListProvider returns matches for "falsely" blocked IP addresses. Yet Exchange still blocks these connections because they appear on the RBL.
How do IPAllowListProvider and IPBBlockListProvider interact in connection filtering? Can I configure exchange to accept e-mails from servers which appear on the DNS white list even when they also appear on the black list?
Answer: You probably want to run the following Exchange cmdlets:
Get-IPAllowListProvidersConfig | Format-List *Enabled
Get-IPAllowListConfig | Format-List *MailEnabled

Make sure that you actually have the white list providers enabled.
Assuming that looks good, try
Get-IPBlocklistProvider
Get-IPAllowListProvider

Look at the priority.  If the priority of your Blocklist Provider is higher than the priority of your Allowlist Provider, that might be your problem.  If you don't already have something set as priority 1, try
Set-IPAllowListProvider list.dnswl.org -Priority 1

(assuming that's what you called the provider) and see if that helps.
Comment: Thanks for your suggestion. I checked that everything is enabled. The priorities are set properly. What can't be done with the -Priority command is giving say list.dnwsl.org priority 1 and sbl.spamhaus.org priority 2 (f these are the only list providers). Automatically both will have priority 1. Somehow exchange must internally have a way to prioritize.
Comment: I have an allowlistprovider set to Priority 1 and a blocklistprovider set to Priority 3.  You might have to `Set-IPBlockListProvider sbl.spamhaus.org -Priority 2` or whatever.
Comment: Perhaps you had some old block list providers with a higher priority which you deleted? I can't set a higher priority than the number of providers I have.... In any case, even then allow lists are ignored by my server.


Pandas Data Frame add new calculated field using Partitioned Data

Question: I am trying to add a new calculated field.  I am trying the 2nd best answer in Adding calculated column(s) to a dataframe in pandas because it seems the best in my opinion as it is neat.  Please feel free to offer better alternatives.
Either way my initial code is below:
import pandas as pd

#https://github.com/sivabalanb/Data-Analysis-with-Pandas-and-Python/blob/master/nba.csv
dt_nba = pd.read_csv("data//nba.csv")

#note this is just basic function.  I want to pass partitioned data like team's average salary
def GetSalaryIncrement(val):
    return val * 1.1

dt_nba["SalaryPlus10Percent"] = map(GetSalaryIncrement,dt_nba["Salary"])

dt_nba[["Name","Team","Salary","SalaryPlus10Percent"]][:5]

However, the result is not what I expected:
+----+---------------+----------------+--------------+--------------------------------+
| ID |     Name      |      Team      |    Salary    |      SalaryPlus10Percent       |
+----+---------------+----------------+--------------+--------------------------------+
|  0 | Avery Bradley | Boston Celtics | 7730337.0000 | <map object at 0x7fb819e9b7b8> |
|  1 | Jae Crowder   | Boston Celtics | 6796117.0000 | <map object at 0x7fb819e9b7b8> |
|  2 | John Holland  | Boston Celtics | nan          | <map object at 0x7fb819e9b7b8> |
|  3 | R.J. Hunter   | Boston Celtics | 1148640.0000 | <map object at 0x7fb819e9b7b8> |
|  4 | Jonas Jerebko | Boston Celtics | 5000000.0000 | <map object at 0x7fb819e9b7b8> |
+----+---------------+----------------+--------------+--------------------------------+

In particular I am interested in passing "window/aggregate data" where it should gracefully ignore Nan values.
Example in T-SQL I can do this:
-- INCREASE EACH PLAYERS SALARY BY 10% OF AVERAGE SALARY OF THE TEAM
SELECT NewSalary= Salary + (.1 * AVG(Salary) OVER (PARTITION BY Team))
FROM nba_data

I want to do that in Pandas if possible. Thank you.
Answer: I think you are looking for
dt_nba["Salary"]=dt_nba["Salary"].map(GetSalaryIncrement)

Also you can do with
GetSalaryIncrement(dt_nba["Salary"])

dt_nba["Salary"].apply(GetSalaryIncrement)

To calculatedINCREASE EACH PLAYERS SALARY BY 10% OF AVERAGE SALARY OF THE TEAM
dt_nba['Newsa']=dt_nba.groupby('Team')['Salary'].transform('mean')*0.1+dt_nba["Salary"]

Comment: @Earl, in this case Wen_Ben's solution on the bottom will work. Your function is just adding 10% to each row, inconsiderate of the aggregate on team.
Comment: looks like it is working if I isolate the average team data, the values of the average does not repeat.  I have not done actual tally yet.   However, the GetSalaryIncrement formula does not seem to work.  Did i make a mistake on my function?  A salary of 7730337 returns 8148487.4857.
Comment: sorry Ignore my mistake above.  I miss-type the column names I was actually looking at average team salary increment.   So far the figures match on the function.   I shall evaluate the group by values now.
Comment: Okay, I confirm the window aggregation code works perfectly.  I have checked the Boston Celtics and it gives 4181504.857 as expected and Brooklyn Nets gives 3501898.333 as expected.    Pandas looks a very good library.  Thanks Wen-Bee and Efran for the answer and comments.


android soundpool heapsize overflow

Question: I get this error hundreds of times when I run in Debug, it doesn't seem to affect the program, but how do I get rid of it?
I know it can be traced back to the SoundPool based on other posts
09-15 09:03:09.190: ERROR/AudioCache(34): Heap size overflow! req size: 1052672, max size: 1048576
Comment: @Roflcoptr that is a terrible suggestion, and one that is not applicable on Android. Apps don't have the ability to set JVM heap size on Android.
Comment: Soundpool isn't designed to hold a large amount of data, just small collection of sound effects. Consider using MediaPlayer as an alternative if needed.
Comment: Then just increase your heap size
Comment: http://viralpatel.net/blogs/2009/01/jvm-java-increase-heap-size-setting-heap-size-jvm-heap.html
Comment: On which device do you have that error ? It occured  also on galaxytab10.1
Comment: Do you get this error when you play a sound? Or nevertheless?
Answer: SoundPool is hard code the buffer size as 1M for all loaded file. So you probably will get 'heap size overflow' error when you load too much files into SoundPool. I also have this issue on a game project that will load game sound FX into SoundPool and the solution is as follow:

Play long/large background music in MediaPlayer.
Play short sound files in multi SoundPool instances to prevent the heap error. The sample code for multi SoundPools:

 /**
  * Multi SoundPool to prevent memory error.
  */
public class SoundPools {

  private static final String TAG = "SoundPools";

  private static final int MAX_STREAMS_PER_POOL = 15;

  private List<SoundPoolContainer> containers;

  public SoundPools() {
    containers = Collections.synchronizedList(new ArrayList<SoundPoolContainer>());
  }

  public void loadSound(Context context, String id, String file) {
    Log.d(TAG, "SouldPools load sound " + file);
    try {
      for (SoundPoolContainer container : containers) {
        if (container.contains(id)) {
          return;
        }
      }
      for (SoundPoolContainer container : containers) {
        if (!container.isFull()) {
          container.load(context, id, file);
          return;
        }
      }
      SoundPoolContainer container = new SoundPoolContainer();
      containers.add(container);
      container.load(context, id, file);
    } catch (Exception e) {
      Log.w(TAG, "Load sound error", e);
    }
  }

  public void playSound(Context context, String id, String file) {
    Log.d(TAG, "SouldPools play sound " + file);
    try {
      for (SoundPoolContainer container : containers) {
        if (container.contains(id)) {
          container.play(context, id, file);
          return;
        }
      }
      for (SoundPoolContainer container : containers) {
        if (!container.isFull()) {
          container.play(context, id, file);
          return;
        }
      }
      SoundPoolContainer container = new SoundPoolContainer();
      containers.add(container);

      container.play(context, id, file);
    } catch (Exception e) {
      Log.w(TAG, "Play sound error", e);
    }
  }

  public void onPause() {
    for (SoundPoolContainer container : containers) {
      container.onPause();
    }
  }

  public void onResume() {
    for (SoundPoolContainer container : containers) {
      container.onResume();
    }
  }

  private static class SoundPoolContainer {
    SoundPool soundPool;
    Map<String, Integer> soundMap;
    AtomicInteger size;

    public SoundPoolContainer() {
      this.soundPool = new SoundPool(MAX_STREAMS_PER_POOL, android.media.AudioManager.STREAM_MUSIC, 0);
      this.soundMap = new ConcurrentHashMap<String, Integer>(MAX_STREAMS_PER_POOL);
      this.size = new AtomicInteger(0);
    }

    public void load(Context context, String id, String file) {
      try {
        this.size.incrementAndGet();
        soundMap.put(id, soundPool.load(context.getAssets().openFd(file), 1));
      } catch (Exception e) {
        this.size.decrementAndGet();
        Log.w(TAG, "Load sound error", e);
      }
    }

    public void play(Context context, String id, String file) {
      android.media.AudioManager audioManager = (android.media.AudioManager) context
          .getSystemService(Context.AUDIO_SERVICE);
      final int streamVolume = audioManager.getStreamVolume(android.media.AudioManager.STREAM_MUSIC);
      Integer soundId = soundMap.get(id);
      if (soundId == null) {
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
          @Override
          public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            soundPool.play(sampleId, streamVolume, streamVolume, 1, 0, 1f);
          }
        });
        try {
          this.size.incrementAndGet();
          soundPool.load(context.getAssets().openFd(file), 1);
        } catch (IOException e) {
          this.size.decrementAndGet();
          Log.w(TAG, "Load/Play sound error", e);
        }
      } else {
        try {
          soundPool.play(soundId, streamVolume, streamVolume, 1, 0, 1f);
        } catch (Exception e) {
          Log.w(TAG, "Play sound error", e);
        }
      }
    }

    public boolean contains(String id) {
      return soundMap.containsKey(id);
    }

    public boolean isFull() {
      return this.size.get() >= MAX_STREAMS_PER_POOL;
    }

    public void onPause() {
      try {
        soundPool.autoPause();
      } catch (Exception e) {
        Log.w(TAG, "Pause SoundPool error", e);
      }
    }

    public void onResume() {
      try {
        soundPool.autoResume();
      } catch (Exception e) {
        Log.w(TAG, "Resume SoundPool error", e);
      }
    }
  }

}
Answer: Maybe your media resource is too big for playing with soundpool. Soundpool only plays short sound effects. On the Soundpool API there is no specification about the maximum of a resource for playing with soundpool, but if You use it, play just short sound effects like, for example, a short explosion in a shooter game.
If this is Your problem, You should use MediaPlayer for playing your sounds.
Answer: It is not possible for this error to be about heap size, because there aren't any device with such a small heap 1052672 ~ 1Mb., but about SoundPool buffer size.
SoundPool has hardcoded limit of 1Mb of raw PCM_16 data in memory. This limit applies for every sound you are loading into memory, and not for sounds in sum per one SoundPool. So the most voted answer about SoundPools is very wrong!
Let me introduce SoundPoolCompat which uses AudioTrack under the hood and have custom bufferSize. All data within specified buffer will be loaded into memory and played with small latency like SoundPool does. All data that exceed that bufferSize will be loaded on demand (which adds latency, similar to MediaPlayer). Api is very similart to SoundPool, also it is added a feature to load sounds from Uri (for example gdrive). And there is playOnce method, all resources will be unloaded after file is played.
implementation 'com.olekdia:sound-pool:3.0.2'

https://gitlab.com/olekdia/common/libraries/sound-pool

android soundpool heapsize overflow


Can the keywords (and standard library) of C++ be localised? (Modifiable parser syntax)

Question: This question is conceived out of curiosity and is mostly a mental exercise:
According to the C++ standard (and as described in this question and its answers), a compiler should support Unicode (and even more precisely UTF-8 in source) in the names of identifiers (variables, functions, etc.) I know that Clang supports that fully (I mean you can use UTF-8 encoded source files) and GCC supports it only if you use \u codes in the identifiers, but let's assume this works directly with utf-8 on all compilers.
That is great! Now I no longer have to write my code in English and can finally do it in my native Bulgarian, or maybe Esperanto. That's the point of this requirement of the standard, after all. Take that as a joke, of course, but I'm just curious to understand to what extend this could be taken. To illustrate, let's take this (purely example) code:
First using identifiers in English (ASCII):
int i = 0;
while(i < 100)
{
    auto f = static_cast<float>(i);
    std::string currentName = "name_" + toString(f);
    std::cout << getPrettyName(currentName) << ": " << getSalary(currentName) << std::endl;
}

And then using identifiers in Bulgarian (to see what can be achieved):
int и = 0;
while(и < 100)
{
    auto д = static_cast<float>(и);
    std::string текущоИме = "име_" + превърниВНиз(д);
    std::cout << красивоИме(текущоИме) << ": " << заплата(текущоИме) << std::endl;
}

As you can see, the second code is still mainly in English because of keywords and the standard library. If we assume the goal of this feature is to make it easy for non-English speakers to code, then:

Most of it is still in English, so people still have to know English to be proper programmers
Should we accept that, this is still very annoying to write when using a script other than latin (like cyrillic but also others). It requires constant switching, which is slow.

It looks like for this feature to be useful, the C++ language should support localised keywords and standard library classes. That has been done for ALGOL 68 and possibly others. Let's see how that would look in Bulgarian (with my own translations of the keywords):
цяло и = 0;
докато(и < 100)
{
    авт д = статично_преобразуване<дробно>(и);
    стд::низ текущоИме = "име_" + превърниВНиз(д);
    стд::изх << красивоИме(текущоИме) << ": " << заплата(текущоИме) << стд::кред;
}

Still having in mind that this is just a mental exercise, it would be interesting to see what's the people's take on these questions:

Is this actually allowed/possible according to the standard right now? I may be missing something…
Is there any way to make a workaround in a decent way myself? Macros would work for the keywords but that would be awful. using would work about standard library classes (namespace стд { using низ = std::string; }) but there is no way to deal with methods (std::string::size() -> размер()?) apart from subclassing… or is there?
In case that is not possible or even considered, how should one go about suggesting this idea to the C++ gurus that make the standard?
Comment: I'd say you should stick to english for variables etc as well, so your code can be broadly understood. You just have to accept that learning english is pretty much a requirement for programming in C++.
Comment: You could write your own scripting language to achieve this: https://accu.org/index.php/journals/2252
Comment: If one wants to follow programming or any significant scientific related career, they should learn English, otherwise it'll be difficult even in finding and reading documents
Comment: actually in Japanese you don't need to change keyboard layout at all. After typing the sentence/word just press space and the IME will convert that to the correct form automatically for you, or you can specify it manually if needed
Comment: @LưuVĩnhPhúc I didn't know that. Edited!
Answer: No, keywords are fixed in the C++ standard (C++11, C++14, etc...). You cannot change them (or else the language won't be C++ anymore).
You might use preprocessor tricks like:
#define стд std

(or, as you commented, using стд = std;; but for proper keywords like while you can "replace" them only with the preprocessor). But I am not sure that is working, and I really believe it is a very bad idea.
A C++ programmer is expecting the names mentioned in the standard. Don't confuse him.
And programming is not about coding in a near natural language (that was the ambition of Cobol, which failed completely on that aspect). The point is that programming is difficult so it takes ten years to learn it, so you do expect programmers to be able to use English looking keywords and read technical documentation in English.
Comment: @LyubomirVasilev, if you use Bulgarian for your identifiers, you will be promptly fired from any programming job, even in most Bulgarian companies. Because most companies either work with people/companies abroad and need them to be able to make sense of their code, or expect to do so one day.
Comment: `using стд = std;` is better than that. As I said macros are an awful solution but I meant macros for keywords as `using` won't work for that. My idea is that maybe the standard should allow that. If it does, "a C++ programmer" will recognise them, because they will be in the standard. Plus, the whole point of this is for people that don't want to use English in the code. If I'll use Bulgarian names for identifiers, some person that doesn't speak Bulgarian will already not be able to understand the code, even though the keywords are in English.
Answer:
That is great! Now I no longer have to write my code in English and can finally do it in my native Bulgarian, or maybe Esperanto. That's the point of this requirement of the standard, after all.

I am pretty sure it isn't. The point of the standard seems to be purely compatibility with other programming systems that may generate such symbols. After all, the specification does not require accepting actual utf-8 anywhere. The only thing it requires is the \u escapes supported in gcc.

Is this actually allowed/possible according to the standard right now? I may be missing something…

No, it isn't. The specification specifies the exact symbol names.

Is there any way to make a workaround in a decent way myself? Macros would work for the keywords but that would be awful. using would work about standard library classses (namespace стд { using низ = std::string; }) but there is no way to deal with methods (std::string::size() -> размер()) apart from subclassing… or is there?

You could cover them with the #defines, but obviously it would apply to the same name everywhere, which is rarely appropriate.

In case that is not possible or even considered, how should one go about suggesting this idea to the C++ gurus that make the standard?

Forget it. It is extremely bad, borderline evil, idea. Remember, that most code out there is, or one day will be, maintained, or at least reviewed, by somebody on the other end of the world, who has different native language. English makes that possible. Switching from it would be very, very bad. At least bad for the big software companies and keep in mind that the key people in C++ standards committee do represent big software companies.
Comment: @LyubomirVasilev, if you ask about whether it makes sense to suggest this idea to the C++ committee, politics *must* be discussed, because the C++ committee decision *will* be pretty much a *political* one.


Iterate through temp table and insert into another table

Question: I have a query that returns ID, ORG ID and NAME.
Code:
CREATE TABLE #TMP (ORG_ID INT)

INSERT INTO #TMP SELECT ORG_ID FROM [dbo].[fx_Rights_OrgIDs] (331)

SELECT [BRN_ID],[BRN_ORGID],[BRN_Name]
FROM [dbo].[BranchDetails]
WHERE [BRN_ORGID] IN (SELECT ORG_ID FROM #TMP)

DROP TABLE #TMP

Returns:
BRA_ID    BRA_ORGID     BRA_Name

289      333            Office

290      334            Store

What I want to do is Iterate through #TMP and insert into another table: SitePrefix if the value exists in SitePrefix don't insert.
So for example insert BRA_Name from temp table into SitePrefix and if it exists then skip.
SitePrefix columns looks like this: (SPF_ID,SPF_Name,SPF_Prefix)
SPF_ID is auto generated, SPF_Name should come from BRA_Name and the SPF_Prefix is EMS
Answer: Try the below query which uses EXCEPT which is SET Difference operator in SQL Server
INSERT INTO SitePrefix
   SELECT [BRN_Name], 'EMS'
   FROM [dbo].[BranchDetails]
   WHERE [BRN_ORGID] IN (SELECT ORG_ID FROM #TMP)
   EXCEPT
   SELECT SPF_Name, 'EMS'
   FROM SitePrefix

Answer: try this,any problem then tell,
MERGE siteprefix AS T
using (SELECT [brn_id],
              [brn_orgid],
              [brn_name]
       FROM   [dbo].[branchdetails]
       WHERE  [brn_orgid] IN (SELECT org_id
                              FROM   [dbo].[Fx_rights_orgids] (331))) AS s
ON t.spf_name = brn_name
WHEN NOT matched THEN
  INSERT (spf_name,
          spf_prefix)
  VALUES (brn_name,
          brn_orgid)


Linear map on a finite dimensional vector space over an algebraically closed field of characteristic $p>0$

Question: Let $V$ be a finite dimensional vector space over an algebraically closed field $F$ of finite characteristic $p$. Let $\alpha: V\longrightarrow V$ be a linear operator on $V$, and suppose that there exists a positive integer $n$ such that for all $v\in V$, $\alpha^n(v)=v$, while for each positive integer $i<n$ there exists $v_i\in V$ such that $\alpha^i(v_i)\neq v_i$. I have proved that if $n$ is not divisible by $p$ then $\alpha$ is diagonalizable.

Prove that $\alpha$ is diagonalizable if and only  if $n$ is not divisible by $p$.

Dear Professors,
I am a 1st year student preparing for Qualifying exam. I am quite sorry that I post such questions but I really need to pass the exam of such questions if I want to continue my PhD. I will be very grateful for your tolerance and be more grateful if you give a help.
Comment: @DerekHolt They are visible only for users rated 10k+.
Comment: Could you provide a little context, and perhaps your thoughts on the problem? It's rather boring to just attempt a problem without any insight into why it might be interesting
Comment: Unfortunately, deleting the answer doesn't make it invisible!
Comment: Also, I believe the majority of people here are not really professors. I'm quite far from it, myself.
Answer: If $\gcd(n,p)=1$, then $X^n-1$ has no multiple roots. Let $m_{\alpha}\in F[X]$ be the minimal polynomial of $\alpha$. Then $m_{\alpha}\mid X^n-1$, and therefore $m_{\alpha}$ has also no multiple roots, so $\alpha$ is diagonalizable.
Conversely, let's assume that $\alpha$ is diagonalizable and $\lambda_i\in F$ are its eigenvalues. Since $\alpha^n=\hbox{id}_V$ we have $\lambda_i^n=1$. If $p\mid n$, then write $n=pm$ and notice that $\lambda_i^m=1$, so $\alpha^m=\hbox{id}_V$, a contradiction.
Answer: Here's one way of getting you started. I'm not saying that this is the best way - just a very concrete way.
Let's do the case $n=2$. So $p>2$, and $1/2\in F$. If $v$ is any vector, you can write it as a sum
$$
v=\frac12(v+\alpha(v))+\frac12(v-\alpha(v)).
$$
Show that above we have written $v$ as a sum of two eigenvectors of $\alpha$. Why does the claim follow from this?
If $n=3$, let $\omega\in F$ be a primitive cubic root of unity. Why does that such an element exist? In that case you can do the same with
$$
v=\frac13(v+\alpha(v)+\alpha^2(v))+\frac13(v+\omega\alpha(v)+\omega^2\alpha^2(v))+\frac13(v+\omega^2\alpha(v)+\omega\alpha^2(v))
$$
instead.
Generalize, or think of another, less computational way.


Is a Metric space $(X,d)$ with $X=\{x\}$ an open set?

Question: I've recently started to study functional analysis using "Introduction to functional Analysis" of Edwin Kreyszig. In this book there is a theorem that states that every metric space $X$ is an open set. But what about a metric space that contains only one element? Such space couldn't be a open set because $d(x,x)=0$, and the definition of open set requires $d(x,y)=r$ where $r>0$.
Comment: The one point set $\{x\}$ consists of all points $y$ such that $d(x,y)<0.47$.
Comment: The definition doesn't say anything about $d(x,y) = r, r > 0$. It says:  "given any point $x$ in $U$, there exists a real number $\epsilon > 0$ such that, given any point $y$ in M with $d(x, y) < \epsilon$, $y$ also belongs to $U$."  So, as @AndréNicolas suggested, take $\epsilon = 0.47$.  There is only one possible $y$, namely $x$, and this is in the set, so you're done.
Comment: As an aside, it doesn't make sense to ask "Is $(X,d)$ an open set?" There are no such things as "open sets" -- instead there are things such as "open sets of $T$" (for appropriate kinds of $T$). You really meant to ask "Is $X$ an open set of $(X,d)$?"
Comment: Where in the definition does it require an $y\in X$ so that $d(x,y)=r$, $r>0$? In this case any open ball centered at $x$ would equal the singleton $\{x\}$.
Comment: the book uses the same definition of open set that is in the wikipedia: http://en.wikipedia.org/wiki/Open_set#Metric_spaces
so i don't understand why a set with only one element (and a metric) is an open set.
Comment: Thanks @RobertIsrael! Now I see where was my mistake.
Comment: @Don Ismael Singleton set is neither open nor closed
Comment: On a side-note, do you really want to delve into functional analysis without understanding completely what's going on in general topology? That's asking for trouble, I think.
Comment: And thus $0.47$, despite being afflicted with an incurably dull personality, had made it into the Academy of Pop Stars, where all the most popular mathematical constants had learned their trade. Much work would have to make up for its lack of a particular talent. But at the Academy, they would eventually find a fitting role for it...
Answer: Well, a set $X$ is a metric space when there exists a map $d \colon X \times X \to [0,+\infty)$ such that

$d(x,y)=d(y,x)$
$d(x,y)=0$ implies $x=y$
$d(x,y)\leq d(x,z)+d(z,y)$

for all $x$, $y$, $z \in X$. I can't see any reason why $\operatorname{card}X>1$.


Power shell executing base on how many files is in the path how to solve this issue?

Question: I have a code in PowerShell  for file watcher fo my FTP folder and when the code see that there is new file in that folder it will open a batch file that will run a program for my database.
My problem is when i sent multiple files "2 files to be exact" the power shell also execute it twice or more i just need to run it once when the file is already uploaded in the specified folder.
here is my code thank you in advance!
<code>$searchPath = "D:\Upload\ftp\"

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $searchPath
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

$created = Register-ObjectEvent $watcher "Created" -Action {
  Start-Process "C:\eGaps\Isabela\Automatic-Upload\automata.bat"
}
</code>
Answer: This is because the event watcher you have in place is designed to look for write to the folder as the occur and you are specifically telling it to take an action on that.
Either set this code as a scheduled task to say run every hour and grab all new files in the folder or change the coded to  look for a certain number of new files before your trigger is called.
The scheduled task is the easiest route IMHO, the below article is an example of how to do the scheduled task approach.

Scan Folder for Changed/Added Files
Description: Script to check if files have been updated or added in
  the past 10 minutes, with the expectation that the script will be run
  as a scheduled task every 10 minutes.
If there is a hit the script will send an email with the changed/added
  files in the body of the email.
https://community.spiceworks.com/scripts/show/1595-scan-folder-for-changed-added-files


Importar dados de uma planilha excel para o Banco de dados- Epplus

Question: Senhores, estou com o seguinte problema: criei o código abaixo, realizei algumas alterações, entretanto não consigo importar meu arquivo. A minha aplicação é em .NET, e o banco de dados é o Oracle Sql, e adaptei a biblioteca EPPLUS.
Se alguém tiver um norte do que eu posso fazer para melhorar meu código, agradeço, e se alguém tiver alguma sugestão do que eu posso estar fazendo, agradeço também.
Tentei usar o Dapper, porém não consegui.
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.IO;

namespace Teste1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
            return View();
        }

        [HttpGet]
        [Route("Import")]
        public void ImportExcel()
        {
            //Esta dando erro na minha linha aqui tbm->  using (ExcelPackage xlPackage = new E(new FileInfo(@"C:\YourDirectory\sample.xlsx")))
            var myWorksheet = xlPackage.Workbook.Worksheets.First(); //selecionando o arquivo
            var totalRows = myWorksheet.Dimension.End.Row;
            var totalColumns = myWorksheet.Dimension.End.Column;

            var sb = new StringBuilder(); //Estes são seus dados
            for (int rowNum = 1; rowNum <= totalRows; rowNum++) //selecionando a linha
            {
                var row = myWorksheet.Cells[rowNum, 1, rowNum, totalColumns].Select(c => c.Value == null ? string.Empty : c.Value.ToString());
                sb.AppendLine(string.Join(",", row));
            }
        }
    }
}
</code>
Comment: Qual é exatamente o erro?
Answer: Usando a biblioteca ExcelDataReader na versão 184.108.40.206, você consegue transformar o array de bytes do seu arquivo em DataSet e consequentemente fazer um foreach para inserir seus dados.
Controller:
<code> [HttpPost]
    public JsonResult Insert(FormCollection form)
    {
        try
        {
            BinaryReader reader = new BinaryReader(Request.Files["UploadFile"].InputStream);

            byte[] fileBytes = reader.ReadBytes(Request.Files["UploadFile"].ContentLength);

            bool idHvi = vContratoHviBusiness.Inserir(Convert.ToDateTime(form.GetValues("ContratoHviEntity.dtCriacao")[0]), Convert.ToInt32(form.GetValues("ContratoHviEntity.idContratoItem")[0]), form.GetValues("idContrato")[0], fileBytes, Path.GetFileName(Request.Files["UploadFile"].FileName));

            return Json(new { success = true, idHvi });
        }
        catch (Exception ex)
        {
            return Json(new { success = false, responseText = ex.Message });
        }
    }
</code>
Business:
<code>  using (MemoryStream stream = new MemoryStream(fileBytes))
            {
                IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                ds = excelReader.AsDataSet();
                stream.Close();
            }

            if (ds.Tables[0].Rows[1][0].ToString() != idContrato)
            {
                throw new Exception("Este HVI não pertence a esse contrato!");
            }
            else
            {
                for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
                {
                    entidadeHvi.dtCriacao = dtCriacao;
                    entidadeHvi.idContratoItem = itemContrato;
                    entidadeHvi.nmPlanilha = fileName;
                    entidadeHvi.nrFardo = ds.Tables[0].Rows[i][1].ToString();
                    entidadeHvi.vlMIC = Convert.ToDecimal(ds.Tables[0].Rows[i][2]);
                    entidadeHvi.vlUHML = Convert.ToDecimal(ds.Tables[0].Rows[i][3]);
                    entidadeHvi.vlSTR = Convert.ToDecimal(ds.Tables[0].Rows[i][4]);
                    entidadeHvi.vlUI = Convert.ToDecimal(ds.Tables[0].Rows[i][5]);
                    entidadeHvi.vlCodUniv = Convert.ToDecimal(ds.Tables[0].Rows[i][6].ToString() == "" ? null : ds.Tables[0].Rows[i][6]);
                    entidadeHvi.vlELG = Convert.ToDecimal(ds.Tables[0].Rows[i][7]);
                    entidadeHvi.vlRd = Convert.ToDecimal(ds.Tables[0].Rows[i][8]);
                    entidadeHvi.vl_b = Convert.ToDecimal(ds.Tables[0].Rows[i][9]);
                    entidadeHvi.vlCGrade = Convert.ToDecimal(ds.Tables[0].Rows[i][10]);
                    entidadeHvi.vlLeaf = Convert.ToDecimal(ds.Tables[0].Rows[i][11]);
                    entidadeHvi.vlTrArea = Convert.ToDecimal(ds.Tables[0].Rows[i][12]);
                    entidadeHvi.vlSFI = Convert.ToDecimal(ds.Tables[0].Rows[i][13]);
                    entidadeHvi.vlTrCnt = Convert.ToDecimal(ds.Tables[0].Rows[i][14]);
                    entidadeHvi.vlMR = Convert.ToDecimal(ds.Tables[0].Rows[i][15]);
                    entidadeHvi.vlSCI = Convert.ToDecimal(ds.Tables[0].Rows[i][16]);
                    entidadeHvi.vlCSP = Convert.ToDecimal(ds.Tables[0].Rows[i][17]);
                    entidadeHvi.nrLote = Convert.ToDecimal(ds.Tables[0].Rows[i][18]);
                    entidadeHvi.nmProdutor = ds.Tables[0].Rows[i][19].ToString();

                    vContratoHviRepository.Insert(entidadeHvi);
                    Save();
                }
            }
</code>
Lembrando que nesse caso eu passo o formulário de dados por ajax e o arquivo eu pelo por Request.Files["nomedoarquivo"].
Espero ter ajudado ;-)


Editing a program with Ollydbg

Question: This is my C++ code:
#include <conio.h>
#include <iostream>

using namespace std;

void func1()
{
    static int _count = 0;
    if (_count < 5)
    {
        __asm
        {
            pop eax
            push func1
        }
    }

    _count++;
    cout << _count << endl;
}

int main()
{
    func1();

    cout << "ok" << endl;
    return 0;
}

Now, I need to remove asm inline.
It is loaded into Ollydbg, and this is position of asm inline:

I will fill two instructions which is marked in the image with NOP's. Ok. I know how to do it. Then, I saved it with a new name.
But when I loaded the program that I edited into Ollydbg.
The places that I edited was added a new instruction.

And the new instruction makes the program crashs.
Ok, If my question is clearly enough, I need to know:
How did that instruction was added automatically?
And How do I fix it?
Thanks.
UPDATE 1:
The following is how I modified the program

But.. I don't know why?
Answer: A NOP allocates 1 byte, so to replace those two instructions by NOPs
POP  EAX              ; 1 byte
PUSH Console.func1    ; 5 byte

You need to put 6 of NOP not 2. Otherwise, you have 2 NOPs and 4 bytes of garbage.
Comment: It seems that he used the option 'Fill with NOP's' and got 90909090**80**90 instead of 909090909090.

Editing a program with Ollydbg


COPY s3 files to Redshift table with IDENTITY column without EXPLICIT_IDS

Question: I have a bunch of s3 files I want to copy into Redshift (using AWS Data Pipelines and RedshiftCopyActivity). The challenge lies in the fact that my s3 files have one column less then target Redshift table.
Table itself has "id" column - an IDENTITY column which values are auto-generated during insert.
I understand that I should/could be using transformSql property of RedshiftCopyActivity but I am failing in constructing helpful query. Execution always returns me an error:
Exception ERROR: cannot set an identity column to a value

Some more details:
Identity column is the first column of the table.
Data is successfully inserted into table called staging, as it should be. Also, I see my transformSQL was run and data is inserted into table called staging2. Logs show:
create temporary table staging2 as select myField1, myField2, ..., myFieldN from staging

but after that comes:
INSERT INTO target_table SELECT * FROM staging2

which causes error to happen.
So, how can I approach this and make Redshift ignore the fact that I am offering one column less?
Maybe solution could be to make "id" column as the last one, I still didn't try this one. To be honest, I don't like how it sounds - like very fragile approach.
Answer: Amusing you table table-name
id(identity) |  Name(string)| Address(String)
Copy command should like
COPY table-name
Name , Address
FROM data-source
CREDENTIALS 'aws-auth-args';

Note: Syntax for Copy
COPY table-name
[ column-list ]
FROM data_source
[ WITH ] CREDENTIALS [AS] 'aws-auth-args'
[ [ FORMAT ] [ AS ] data_format ]
[ [ parameter [ argument ] [, ... ] ]

Comment: Thanks for the answer, but I have to ask how this helps with data pipelines and transformSql? I fail to understand that.
Answer: At the end, I wasn't able to make this working using RedshiftCopyActivity.
It was always complaining about how value cannot be set to identity column. Event transformSQL parameter didn't help.
The solution that fits my needs utilizes ShellCommandActivity which runs a simple shell script.
Basically, the idea is to install PSQL on EC2 running that is running mentioned shell script, connect to Redshift using PSQL and trigger COPY command that copies data from S3 to Redshift tables.
There are no problems with identity column using COPY command.


Definition of Kronecker Delta

Question: Is $\delta _{mn}=1$ when $m\neq n$, and $\delta _{mm}=0$?
I am not very good at Math. So would you give me the answer and explanation please?
Comment: This is known as the Kronecker Delta instead of the Dirac Delta function just for clarity.
Comment: You got it the other way round.
Comment: Thank for correct my mistake.
Answer: No, the Kronecker delta is defined as $\delta_{mn}=1$ when $m=n$ and $\delta_{mn}=0$ when $m\ne n$. (As Berrick Fillmore said).
It is useful in certain matrices and sum. For example, the identity matrix $I$ has entries $(\delta_{ij} : 1\le i,j\le n)$. And
$$\sum_{i=1}^n a_i \delta_{ij} = a_j$$
Answer: Late to the party, but here's another way to see why this quantity is special: let $V$ be a vector space and $V^*$ its dual. Define a tensor $\delta\colon V^* \times V \to \Bbb R$ by $\delta(f,v) = f(v)$. If $\mathcal{B} = (e_1,\ldots,e_n)$ and $\mathcal{B}^* = (e^1,\ldots,e^n)$ is the dual basis, the components of $\delta$ are, by definition: $$\delta^i_{\;j}\doteq \delta(e^i,e_j) = e^i(e_j) = \begin{cases} 1, & \mbox{if }i=j \\ 0, & \mbox{if } i \neq j\end{cases}$$
Fun thing is: the numerical value of the components does not depend on the bases $\mathcal{B}$ and $\mathcal{B}^*$ themselves. Also, if $V$ has a inner product $\langle\cdot,\cdot\rangle$, you can raise and lower indexes of $\delta$. Using orthonormal bases, one concludes that the numerical values of $\delta^i_{\;j}$, $\delta_i^{\;j}$, $\delta_{ij}$ and $\delta^{ij}$ are all the same.

Definition of Kronecker Delta


Area below the curve $y=\left[\sqrt{2+2\cos2x}\right]$

Question: Find the area below the curve $y=[\sqrt{2+2\cos2x}]$ and above the $x$-axis , $x\in [-3\pi,6\pi]$, (where $[.]$ denotes the greatest integer function) .
My approach:
$$y=[\sqrt{2+2\cos2x}]$$
$$=[\sqrt{2+2(2\cos^2x-1}]$$
$$=[\sqrt{2+4\cos^2x-2}]$$
$$=[|2\cos x|]$$
After this, I do not know how to solve it and how to find the area.
Comment: From $0 < x \leq \frac{\pi}{3}$, $y=1$. So the area of this part is just the area of the rectangle of sides $\frac{\pi}{3}$ and 1. Similarly calculate all other areas and add them.
Answer: $$0\le 2|\cos{x}|\le 2\implies [2|\cos{x}|]\in[0,1,2]$$
The function $[2|\cos{x}|]$ is discontinuous for those values of x that make it 2, but those are single points of removable discontinuity and they're not going to affect the integration properties of this function. So, the area lies between values of $0$ and $1$. Therefore, we need to find that value of x (just find one such value, the rest of the problem is going to be take care of by symmetry and repetition) which serves as the boundary point between values that are above 1 and values that are below 1:
$$
2\cos{x}=1\implies x=\frac{\pi}{3}
$$
Using symmetry and the fact that the area is just a bunch of rectangles that are the same, we have the following:
$$
\int_{-3\pi}^{6\pi}\sqrt{2+2\cos(2x)}\,dx=
\int_{-3\pi}^{6\pi}[|2\cos{x}|]\,dx=
18\int_{0}^{\frac{\pi}{3}}\,dx=6\pi\ sq.\ units.
$$
Answer: The values of $y$ are $0,\,1,\,2$. The last of these is achieved only on a measure-$0$ set irrelevant to integration. Thus $\int_{-3\pi}^{6\pi}ydx$ is the sum of the lengths of intervals on which $y\ge 1$ (i.e. $|\cos x|\ge\frac12$). With respect to $[-3\pi,\,6\pi]$, the complement of these intervals' union is the union of intervals over which $\cos x$ bijects from $\pm\frac12$ to $\mp\frac12$. There are nine such intervals, $\left(k\pi-\frac{8\pi}{3},\,k\pi-\frac{7\pi}{3}\right)$ for integer $k$ from $0$ to $8$ inclusive. As their total length is $9\times\frac{\pi}{3}=3\pi$, the sought integral is $9\pi-3\pi=6\pi$.


TypeError: __init__() got an unexpected keyword argument 'n_folds',sentiment_analysis_with_SVM

Question: I am trying to implement svm for sentiment analysis, i trying to implement this gitlink https://github.com/jatinwarade/Sentiment-analysis-using-SVM/blob/master/SVM.ipynb.
from sklearn.model_selection import ShuffleSplit
from sklearn.model_selection import StratifiedKFold

i refered this as it says to change cross origin to model_selection since it is depricated Error: __init__() got an unexpected keyword argument 'n_splits'
so I replaced with this
grid_svm = GridSearchCV(
    pipeline_svm, #object used to fit the data
    param_grid=param_svm,
    refit=True,  # fit using all data, on the best detected classifier
    n_jobs=-1,  # number of cores to use for parallelization; -1 for "all cores" i.e. to run on all CPUs
    scoring='accuracy',#optimizing parameter
    cv=StratifiedKFold(liked_train,n_folds=5),
)

This Returns Error:
TypeError                                 Traceback (most recent call last)
<ipython-input-49-61dd1e818fa4> in <module>
      5     n_jobs=-1,  # number of cores to use for parallelization; -1 for "all cores" i.e. to run on all CPUs
      6     scoring='accuracy',#optimizing parameter
----> 7     cv=StratifiedKFold(liked_train,n_folds=5),
      8 )

TypeError: __init__() got an unexpected keyword argument 'n_folds'

Please Help me solve this error
Comment: I tried adding n_split also, it return's the same error
Answer: As you can see in the documentation for model_selected.StrafiedKFold, there is no keyword argument called n_folds and you should indeed use n_splits.
Note, however, that the data should not be passed as an argument to the validator and by doing so, you're effectively passing liked_train as the argument for n_splits, which won't work. Rather, you should pass the data only to the fit of your grid_svm after initialization.
Comment: That's because the first argument to `StrafiedKFold` is `n_splits` and you're already passing `liked_train`. Change your call to be `cv=StratifiedKFold(n_splits=5)` and you're good.
Comment: I tried adding n_split also, it return's the same error  :  TypeError: __init__() got multiple values for argument 'n_splits'


can't install pptk in python

Question: I'm trying to install the pptk module in PyCharm for visualising 3D point clouds.
Initially I tried installing in PyCharm via File > Settings > Python Interpreter > Install > pptk
However, it couldn't be found and advised I use pip instead.
So on my command prompt I navigated to the folder containing Python 3.9 and tried pip install pptk
And I got the following error ERROR: Could not find a version that satisfies the requirement pptk (from versions: none) ERROR: No matching distribution found for pptk
I'm not sure what I'm doing wrong or why no version can be found? Am I missing something obvious in the installation?
Comment: Your Python is probably on the wrong version. Try Python 3.6.
Comment: @thethiny thanks, I'll give that a try and update the post with my result
Comment: you were right @thethiny. Downloaded with Python 3.6, no issues. Thanks!
Answer: According to the requirements by the pptk module, the minimum Python version required is 3.6. Judging by the fact that there's no distribution found for 3.9 I believe that it was missing a PyPi repo for it, therefore downgrading to Python 3.6 should fix the problem. Judging by your response to my comment, that did work.
Answer: Not sure if this answer was wrong or it is simply outdated, but it doesn't support 3.6 as well.
I successfuly instaled it on Python 3.7. Just to save you the time - the latest version with installers - https://www.python.org/downloads/release/python-379/

can't install pptk in python


CSS current page nav bar color change

Question: I'm working on an assignment that has a page with a vertical nav bar in which each of the links are enclosed in a box. The assignment requires that the current link's box be changed to red. I have tried several different methods but none of them seem to work. This is what I have:

   /* the styles for the elements */
* {
 margin: 0;
 padding: 0;
}
html {
 background-color: white;
}
body {
 font-family: Arial, Helvetica, sans-serif;
    font-size: 100%;
    width: 850px;
    margin: 0 auto;
    border: 3px solid #931420;
    background-color: #fffded;
}
a:focus, a:hover {
 font-style: italic;
}
/* the styles for the header */
header {
 padding: 1.5em 0 2em 0;
 border-bottom: 3px solid #931420;
  background-image: -moz-linear-gradient(
     30deg, #f6bb73 0%, #f6bb73 30%, white 50%, #f6bb73 80%, #f6bb73 100%);
 background-image: -webkit-linear-gradient(
     30deg, #f6bb73 0%, #fffded 30%, white 50%, #fffded 80%, #f6bb73 100%);
 background-image: -o-linear-gradient(
     30deg, #f6bb73 0%, #fffded 30%, white 50%, #fffded 80%, #f6bb73 100%);
 background-image: linear-gradient(
     30deg, #f6bb73 0%, #fffded 30%, white 50%, #fffded 80%, #f6bb73 100%);
}
header h2 {
 font-size: 175%;
 color: #800000;
}
header h3 {
 font-size: 130%;
 font-style: italic;
}
header img {
 float: left;
 padding: 0 30px;
}
.shadow {
 text-shadow: 2px 2px 2px #800000;
}
/* the styles for the main content */
main {
 clear: left;
}

/* the styles for the section */
section {
 width: 575px;
 float: right;
 padding: 0 20px 20px 20px;
}
section h1 {
 color: #800000;
 font-size: 150%;
 padding-top: .5em;
 margin: 0;
}
section p {
 padding-bottom: .5em;
}

#boldp{
 font-weight: bold;
}
#navlist .current{
 background-color: #800000;
}
#navlist ul li{
 margin: 5px;
 background-image: url("../images/right.jpg");
 background-repeat: no-repeat;
 background-position: 95%;
 border: 2px solid black;
 border-radius:25px;
 padding: 10px;
 width: 175px;
 height: 35px;
 box-shadow: 5px 5px 2px #800000;

}

#navlist ul{
 list-style-type: none;
 padding: 10px;
}

/* the styles for the article */
article {
 padding: .5em 0;
}
article h2 {
 font-size: 115%;
 padding: 0 0 .25em 0;
}
article img {
 float: right;
 margin: .5em 0 1em 1em;
 border: 1px solid black;
}

/* the styles for the aside */
aside {
 width: 215px;
 float: right;
 padding: 0 0 20px 20px;
}
aside h2 {
 color: #800000;
 font-size: 130%;
 padding: .6em 0 .25em 0;
}

aside h3 {
 font-size: 105%;
 padding-bottom: .25em;
}
aside img {
 padding-bottom: 1em;
}

/* the styles for the footer */
footer {
 background-color: #931420;
 clear: both;

}
footer p {
 text-align: center;
 color: white;
 padding: 1em 0;
}

Guest speakers

October
Jeffrey Toobin

November
Andrew Ross Sorkin

January
Amy Chua

February
Scott Sampson

Return to Home page

Answer: #navlist .current will target the .current class, and you can apply a background or whatever it is to that class.

#navlist .current {
  background: red;
}
#navlist ul li{
 margin: 5px;
 background-image: url("../images/right.jpg");
 background-repeat: no-repeat;
 background-position: 95%;
 border: 2px solid black;
 border-radius:25px;
 padding: 10px;
 width: 175px;
 height: 35px;
 box-shadow: 5px 5px 2px #800000;

}

#navlist ul li.sam {
 background-color: #800000;
 }

#navlist ul{
 list-style-type: none;
 padding: 10px;
}

Guest speakers

October
Jeffrey Toobin

November
Andrew Ross Sorkin

January
Amy Chua

February
Scott Sampson

Return to Home page

Comment: There must be something else in my css file overriding it because neither of these fixes work. I'll add the rest to the original post
Comment: @KaitJardine the background change is working in your example, isn't it?
Comment: It is working on here from the snipett, however when I apply those changes and upload it to the server, it does not change the webpage. That's why I assume there must be something overriding it in the css and why I edited the question to include the entire css
Comment: @KaitJardine I mean it's working in **your** snippet, not mine.
Answer: Hey if i'm understanding your right I think you just need to add a background for the current class
.current {
  background-color:red;
}

CSS current page nav bar color change


Why does $n/\sqrt n = \sqrt n$

Question: I just graduated from uni in computer science, but decided I want to relearn calculus. I discovered that $\frac {n}{\sqrt n} = \sqrt n $ for every positive integer $n$. Can anyone explain this to me?
Comment: Welcome to Mathematics Stack Exchange.  Try multiplying both sides by $\sqrt n$
Answer: You could see it from different ways. For instance, since $$n = \sqrt{n}\cdot \sqrt{n}\tag{1}$$ (by definition of the square root, $x = (\sqrt{x})^2$ for all $x\geq 0$), you get
$$
\frac{n}{\sqrt{n}} = \frac{\sqrt{n}\cdot \sqrt{n}}{\sqrt{n}}
= \sqrt{n}\cdot \frac{\sqrt{n}}{\sqrt{n}} = \sqrt{n}\cdot  1 = \sqrt{n} \tag{2}
$$
by dividing both left- and right-hand-side of the equality in (1) by $\sqrt{n}$.

It is not only for integers, incidentally. This works for every positive real $x>0$.
Answer: It is because $(\sqrt n)^2=n$.
Answer: One way to show two quantities are equal is to show that the square of their difference is zero, i.e. $(a-b)^2=0$ and in our case it is $$\Big( \frac{n}{\sqrt{n}}-\sqrt{n}\Big)^2=\frac{n^2}{n}+n -2\frac{n}{\sqrt{n}}\cdot \sqrt{n}=0$$

Why does $n/\sqrt n = \sqrt n$


Variance of a poisson distribution

Question: For a certain section of pine forest, the number Y of diseased trees per acre has a Poisson distribution with mean lambda=10. The disased trees are sprayed with an insecticide at a cost of 3 dollars per tree, plus a fixed overhead cost for equipment rental of 50 dollars. Letting C denote the total spraying cost for a randomly selected acre, find the expected value and variance for C.
Expected value is easy to find: 80
I'm stuck on Variance? Why is variance 90?
Comment: See https://en.wikipedia.org/wiki/Variance#Basic_properties - specifically the third and fourth equation lines of that section
Answer: Because $C = 3Y+50$, and $var(C)=var(3Y+50)=9var(Y)=90$
Comment: I did upvote it. But it won't show as I have less than 50 reputation. Yes, approved it.
Comment: Thank you so much. Just a doubt, if we had to do it by the method of EX^2 etc. how would it look like?
Comment: $E[C^2]=E[(3Y+50)^2]=E[9Y^2+300Y+2500]=9E[Y^2]+300E[Y]+2500$; since Possion variance is $\lambda = 10$, $E[Y^2] = var(Y) + E[Y]^2 = 110$. Substituting leaves us with $E[C^2] = 6490$. $E[C]^2 = 6400$, then $var(C) = 6490-6400=90$
Comment: Wow, thank you so much. I was stuck with this for minutes.
Comment: You need a mere 15 reputation to upvote, not 50. [A single question, moderately well-written -- i.e. a somewhat average question on the site - can expect to earn about 2-3 upvotes, and 3 is sufficient to gain the privilege]

Variance of a poisson distribution


iframe dynamic src

Question: I want to get updated url of iframe using javascript?
Like this:

but the code above doesn't work. How can I do this?
I'll use external links in iframe which is not hosted on same domain where I'm using the code above.
Please Help.
Thanks
thanks again. http://yahoo.com is just an example. Again my domain is szacpp.com and I need to get the links of other.com. You mean I need to put htaccess in other.com while I don't have access the domain.
Comment: Try this by adding iframurl() after function declaration. Or add it to on document load function.
Comment: szacpp - I have updated my answer, hopefully this is useful to you.
Answer: The src attribute of an iframe will not update when the page changes within the iframe.
Your only option would be to query the document in the iframe, however that will only work if the page in the iframe comes from the same domain (otherwise you hit the same origin policy)
UPDATE
IF you have access to other.com, then you should be able to set Access-Control-Allow-Origin in the .htaccess file (assuming you are using a server that uses that file system).
You will find more information...

http://www.w3.org/TR/cors/#access-control-allow-origin-response-header
http://enable-cors.org/
Access-Control-Allow-Origin Multiple Origin Domains?

If you do not have access to other.com then you are simply out of luck. It will be impossible for you to know what the new page is, because the src attribute of the iframe will not be updated when the page changes within the iframe. And you will not be able to use JavaScript due to the same origin policy that I (or more precisely, Quentin) mentioned earlier.
Comment: Cross site scripting refers to a class of code injection vulnerability and is largely unrelated to cross origin communication. I've changed the reference.
Comment: hi, Quentin thanks for quick response.
You understood my problem.
I used .htaccess with the line: Header add Access-Control-Allow-Origin * but still not working.
Comment: also I'm receiving (Refused to set unsafe header "User-Agent")
Comment: You can't set *request* headers on the server (since the server sends *responses*, not requests). CORS is used by a server to give permission for *itself* to be accessed, you can't set response headers on yahoo.com.
Comment: thanks again.
yahoo.com is just an example. Again my domain is szacpp.com and I need to get the links of other.com. You mean I need to put htaccess in other.com while I don't have access the domain.
Comment: @szacpp - you've marked my answer as correct, therefore it is assumed that you don't need any help anymore.  If you're still in need of help, you'd best start a new question giving *exact* details (and reference this question if necessary)
Comment: Now I've marked your answer as incorrect. so pls answer my second last question. Am I right I need to put htaccess in other.com
Comment: @szacpp, my answer IS correct in the context of the question you asked in the first place, you should not be putting secondary questions within the comments.  Either update your original question with *updates*, or start a new one. It was Quentin who responded about the `.htaccess` file, not me.
Comment: @Quentin, I would appreciate any amendments you wish to make to my edited answer, as I'm an IIS boy and therefore have exceptionally limited knowledge of `.htaccess` - other than what I've just Googled
Comment: I can't see anything wrong with the answer as it stands. If a visitor to your site is doing something on a third party site, then you can't spy on what it is they are doing there (for obvious privacy/security reasons). The third party site has to cooperate.
Comment: Thanks. I have answerd my client. if you want to copy url so right click on a url and select "Copy link address" from context menu.
Answer: try this :

Comment: It took me a while to spot-the-difference (please highlight changes when you copy/paste entire blocks of code). Assuming this is the top level frame, adding `parent.` will make no difference. If it isn't the top level frame, it will break the attempt to get the iframe element by its id. This won't help at all and might make things worse.
Comment: This could never work, as the iframe object lives in the same document as the script, therefore by using `parent` you're referring to the parent of the document, not the parent of the iframe

iframe dynamic src


$\Pi_{i \in I}X_i$ Hausdorff $\Rightarrow$ each $X_i$ Hausdorff.

Question: Consider a collection of non-empty topological spaces $(X_i)_{i \in I}$ and the product topology $\Pi_{i \in I}X_i$.
I'm trying to prove that if $\Pi_{i \in I}X_i$ is Hausdorff then each $X_i$ is Hausdorff.
I've started similarly to this post: Theorem 19.4 in Munkres' TOPOLOGY, 2nd ed: Does the converse also hold?. However, I have a hard time writing the last steps in my proof.
Here's a sketch of my idea. So following the construction in the link, we have two points in the product topology that are equal in each component except, say the $i$th one. Because $\Pi_{i \in I}X_i$ is Hausdorff, we can find disjoint opens, resp. $U,V$, around these points. I then thought to use the base of the product topology that tells us that we can find $\Pi_{i \in I}U_i \subseteq U$ and $\Pi_{i \in I}V_i \subseteq V$ where $U_i$ and $V_i$ are opens in $X_i$ and $U_i = X_i$ and $V_j = X_j$ for all but finite many $i$ and $j$. Now, somehow we have to have that $U_i \cap V_i = \emptyset$ for the $i$ where the points in the product topology differ.
I am stuck on how to figure this last step out. Also is the step of using the base of the product topology really necessary? I feel like I don't really use it here, but on the other hand don't I need it to get to the $U_i$ and $V_i$?
Comment: I don't think you can show directly that $U_i\cap V_i=\varnothing$. Consider the case of two spaces, say $\mathbb{R}^2$, and let's take the points $(0,0)$ and $(1,1)$. Then I can take as one of my open sets the set of all $(x,y)$ with $-\frac{1}{2}\lt x\lt 1$ and $-\frac{1}{2}\lt y\lt \frac{1}{2}$; and the other set being all $(x,y)$ with $\frac{3}{4}\lt x\lt \frac{5}{4}$ and $\frac{1}{2}\lt y\lt \frac{3}{2}$. Then the two open sets intersect trivially, but the corresponding $U_1$ and $V_1$ are $(-\frac{1}{2},1)$ and $(\frac{3}{4},\frac{5}{4})$.
Comment: @ArturoMagidin So I'm on the wrong track?
Comment: Well, certainly you can't prove that $U_i\cap V_i$ is empty, as the example above shows.
Comment: @ArturoMagidin how would one then show that the $X_i$ are Hausdorff?
Comment: @freakish could you post an answer?
Comment: In https://math.stackexchange.com/a/1635686/861687 solution, can anyone show $\pi_\beta (U) \cap \pi_\beta (V) = \emptyset$? ATC, $\exists z\in \pi_\beta (U) \cap \pi_\beta (V)$. Then $\exists p\in U$ such that $\pi_\beta (p)=z$ and $\exists q\in V$ such that $\pi_\beta (q)=z$. Then how to proceed?
Comment: @ArturoMagidin  In your example, the two points differ in both coordinates, while the OP wrote: "we have two points in the product topology that are equal in each component except, say the ith one."
Comment: Inspired by @YuvalPeres answer. Construct $p=(p_\alpha )$ such that $p_\alpha =x_\alpha =y_\alpha$, $\forall \alpha \in J- \{ \beta \}$ and $p_\beta =z$. It's easy to show $p\in U\cap V$. Thus we reach contradiction.
Comment: @YuvalPeres: Thanks for pointing that out; I missed that.
Answer: You are on the right track. Suppose that  $x_i,y_i$ in $X_i$ are distinct, and
fix some $x_j \in X_j$ for all $j \in I\setminus {j}$. then $x=(x_j)_{j \in I} \in X=\prod_j X_j$ and $y$ obtained from $x$ by replacing $x_i$ by $y_i$ and leaving the other coordinates unchanged, can be separated in $X$ by open sets $U,V$. Choose basic open neighborhods $\prod_j U_j \subset U$ of $x$ and $\prod_j V_j \subset U$ of $y$. Note that $x_j \in U_j \cap V_j$ for all $j \ne i$. Now we claim $U_i \cap V_i=\emptyset$. Indeed, if there was some $z_i \in U_i \cap V_i$, then the point
$z$ obtained from $x$ by replacing $x_i$ by $z_i$ and leaving the other coordinates unchanged, would be in $U \cap V$, a contradiction.
Comment: @user264745 Thanks, edited.
Comment: So I was on the right track! Arturo's example did bug me, because of both different components. Thanks a lot!
Comment: X is not cartesian product of finite Hausdorff space. Though it easily generalize.
Answer: As noted in comments your approach has issues. Lets try it differently.
One of the ideas is to show that each $X_j$ is homeomorphic to some subspace of $\prod_{i\in I}X_i$ and thus it has to be Hausdorff.
First of all recall how the product space is defined:
$$\prod_{i\in I}X_i=\{f:I\to \bigcup_{i\in I} X_i\ |\ f\text{ is a choice function}\}$$
with appropriate (product) topology.
Now fix a point $e_j\in X_j$ for each $j$ and consider the following function:
$$\lambda_j:X_j\to\prod_{i\in I}X_i$$
$$\lambda_j(x)(i)=\begin{cases}
x&\text{if }i=j\\
e_i&\text{otherwise}
\end{cases}$$
This looks complicated, but for example if we have $X_1\times X_2\times X_3$ then $\lambda_1(x)=(x,e_2,e_3)$, $\lambda_2(x)=(e_1,x,e_3)$ and $\lambda_3(x)=(e_1,e_2,x)$. In other words $\lambda_j$ puts $x$ on $j$-th coordinate, and every other coordinate is fixed.
I leave as an exercise that each $\lambda_j$ is continuous, which easily follows from the universal property of product topology, because the composition $\pi_k\circ\lambda_j$ with each projection is either the identity or a constant map. Moreover each $\lambda_j$ is a homeomorphism onto its image, because the inverse is projection $\pi_j$ restricted to the image.
Comment: I think the approach of the OP is the most efficient.


SQL command to Insert a range of years into a table

Question: I am very new toSQL and am creating a basic database for a Car Dealership. I have a table "Years" that I need to hold a range of years (1950 - 2014).
Instead of
INSERT INTO 'Years' ('year') ("1950");
INSERT INTO 'Years' ('year') ("1951");
INSERT INTO 'Years' ('year') ("1952");

etc, etc...
Is there an easier way to populate the table?
Comment: What problem are you trying to solve with the `Years` table?
Answer: Apart from the disscussing the necessity of such a table for your application the task of pre-populating tables on MySQL side can be solved in several ways.
First and fastest is to do it in one statement utilizing a tally(numbers) table that can be persisted in your db or generate it on the fly as in following example
INSERT INTO years (`year`)
SELECT 1950 + q.n - 1
  FROM
(
   SELECT a.N + b.N * 10 + 1 n
     FROM
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
) q
 WHERE q.n <= 2014 - 1950 + 1

The subquery generates a sequence of numbers from 1 to 100. If you need ranges that span more than 100 years then you can adjust it or if you do a lot such queries then you can substitute it with a persisted tally(numbers) table.
Here is SQLFiddle demo

Second approach is to create a stored procedure that uses LOOP and uses prepared statement
DELIMITER $$
CREATE PROCEDURE populate_years(IN _start_year INT, IN _end_year INT)
BEGIN
  PREPARE stmt FROM 'INSERT INTO years (year) VALUES(?)';
  SET @y = _start_year;

  START TRANSACTION;
  WHILE @y <= _end_year DO
      EXECUTE stmt USING @y;
      SET @y = @y + 1;
  END WHILE;
  COMMIT;

  DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

Here is SQLFiddle demo
Comment: @user2813264 Did it help? Do you need more help with your question?
Answer: You should rethink your code, you will never need a table like that... whatever you are doing with that table surely could be done without it.
If you still want to create the table you have to use a loop.
For example if you are using php:
for ($i = 1950; $i <= 2014; $i++){
    mysqli->query("INSERT INTO 'Years' ('year') (".$i.")");
}


A view with exposed sort: can i turn off 'grouping field' for different sort criteria?

Question: My Views list of events is grouped by the date (using the Grouping Field checkbox in the Style settings).
But my exposed Sort Criteria can sort the list by either date or by name.
An alphabetical list of events grouped by date really doesn't make any sense.
What would make sense is for the Grouping Field to turn off when the Sort Criteria is by name.
I'm thinking either i do two views, and my template decides which view to embed depending on the URL query. Or perhaps a views hook like hook_views_query_alter() could turn off the Grouping Field depending on the circumstances?
Answer: Ok, i think i've managed it with a Views hook. Took an hour's worth of tinkering. I plopped this into my template.php...
<code>/** Find out what the sort criterion is.
    @return The sort criterion fieldname. IMPORTANT: this isn't sanitised!
*/
function MYTHEME_get_sort_by() {
    if (isset($_GET['sort_by']))
        return $_GET['sort_by'];
}

/** Turn off Views grouping-field when sorting by title.
*/
function MYTHEME_views_pre_build(&$view) {
    if ($view->name=='event_programme') {
        if (MYTHEME_get_sort_by()=='title')
            $view->display_handler->options['style_options']['grouping']='';
    }
}
</code>
Comment: Note: i'm using Drupal 6.22, Views 3.0rc2


Memento pattern and violation of encapsulation

Question: Across the internet I come across with examples of implementation of memento pattern
which I consider are fully incorrect.
They can be written in both Java and C#.
Here a several of them

Incorrect implementation of Memento pattern 1
Incorrect implementation of Memento pattern 2
Incorrect implementation of Memento pattern 3

The code:
public class Originator
{
    private string _state; //the private field of originator that shouldn't be exposed!!!!

    public Memento CreateMemento()
    {
        return new Memento(_state);
    }

    public void SetMemento(Memento memento)
    {
        _state = memento.GetState();
    }
}

public class Memento
{
    private string _state;

    public Memento(string state)
    {
        _state = state;
    }

    public string GetState()
    {
        return _state;  // here caretaker can access to private field of originator!!!
    }
}

public class Caretaker
{
    public Memento Memento { get; set; }
}

In code I left comments that should describe situation.
The caretaker class can read private field of originator through memento that violates one of the main principles of memento pattern:

The object's encapsulation must not be violated.

So the question is am I right?
Comment: @vborutenko, ok, now i see what bothers you. Exposing a **value** (a copy) of a private field is not violates encapsulation. As of your example, there should be _"Hi. I'm caretaker and I know the value of private field '_state' of originator that was equals " + memento.GetState() +  " **some time ago, it may be changed now, IDK**."_
Comment: @vborutenko, no try `object.ReferenceEquals(Memento._state, Originator._state)`. Also, change to `Originator._state` will not change `Memento._state` and vice versa
Comment: `int` will be copied at `Memento` constructor, so `Memento._state` and `Originator._state` are 2 different, independent `int`s (same as `string`)
Comment: Looks like a bit of missundestanding on reference vs. value types
Comment: @vborutenko, no, it have no access to `Originator` private field. It stores the **value** (a copy of that `string`/`int`) that was in that field some time ago. So, if `Originator` somehow change his `_state`, `Memento` will never know about this. Same time, if `Momento` somehow change his `_state` (his own copy of that `string`/`int` value) - this will never do anything to `Originator`s `_state`
Comment: I am not a c# specialist, but at least in Java `String`s are immutable, so "exposing" the field should not be a concern?
Comment: @Lino what if it would be for example int type?
Comment: @Lino so are in `c#`
Comment: In java,for example in the first Incorrect implementation of Memento pattern 1
Comment: Yes,technically they are different but anyway we can say for 100% sure that Memento._state ==Originator._state.And so we caretaker can know the value of PRIVATE field of originator
Comment: @vasily.sib but the caretaker class ,in other words, can read the value of private field through momento.It can know the value of the private field.For example the caretakerclass will know that the private field of originator will have for example "someprivatefield" value. Doesn't this violate encapsulation?
Comment: @bradbury9,the missundestanding here that I think that caretaker shouldn't know the value of internal state of originator
Comment: OK see the example.Caretaker ask originator to make a new memento.var memento = originator.CreateMemento() . Console.Writeline ( "Hi. I'm caretaker and I know the value of private field '_state' of originator. It equals " + memento.GetState).Doesn't this violate encapsulation?
Answer:
So the question is am I right?

Yes, you are right: the examples are all incorrect implementations of the Memento design pattern, because the Memento class exposes its internal dependency through a public method. As you noted, this allows the Caretaker (or any other class) to gain private information about the Originator.
Previous answers focus on the state of the internal field and whether the Memento state can vary independently of the Originator. But encapsulation can be violated in more ways than by exposing state. It can also be violated by exposing dependencies. The public getter method exposes the dependency that Originator has on String.
I wish I could say that misinformation is unusual regarding design patterns; but you will find inaccurate and misleading articles about design patterns across the Internet, including here on SO and on Wikipedia.
I happen to like https://refactoring.guru/design-patterns/memento but it's never a bad idea to crosscheck against the GoF book.
Answer: Encapsulation doesn't mean that you shouldn't be able to access the data at all, you just shouldn't be able to access it directly. You should only be able to access it via public methods :)
This link is probably able to explain it better than i am:
https://www.geeksforgeeks.org/encapsulation-in-java/
So encapsulation is kept in your code example, since the state can only be retrieved via a public get method.
Comment: But you made a false assumption because you failed to notice the difference between value and reference types
Comment: In originator class we 'hide' the value of the state make it private.We don't want that someone know the value of that field.But in the example we see that caretaker can know this value
Comment: If you dont want to let other classes know about a private property, dont add a public getter that retrieves its value.
Comment: It is implementation of memento pattern from the internet.I provided several links.
Comment: No,please see the last comments to the questions
Comment: vborutenko - If you look at the link i referenced. In the very first example of what encapsulation is, they make the private variables accessible via a public get method. You claim the reason why you think the implementations are wrong is because it doesn't adhere to encapsulation, because of the public get method in Memento, but the public get method is a part of encapsulation.Here's another link where this is used, if you are still in doubt : https://www.tutlane.com/tutorial/csharp/csharp-encapsulation
Answer: If we add some logic to check how the variables evolve, you will notice how Originator and Memento are not sharing the same data.
public class Originator
{
    private string _state = "originator_initial_state";

    public Memento CreateMemento()
    {
        return new Memento(_state);
    }

    public void DoSomeLogic()
    {
        _state = _state + " modified";
    }

    public void SetMemento(Memento memento)
    {
        _state = memento.GetState();
    }
}

public class Memento
{
    private string _state;

    public Memento(string state)
    {
        _state = state;
    }

    public string GetState()
    {
        return _state;
    }
}

Now lets work with them:
Originator myOriginator = new Originator();
Memento memento1 = myOriginator.CreateMemento();

myOriginator.DoSomeLogic();

Memento memento2 = myOriginator.CreateMemento();

string memento1_state = memento1.GetState();
string memento2_state = memento2.GetState();

Console.WriteLine(memento1_state);
Console.WriteLine(memento2_state);

You will notice that memento1_state and memento2_state are different, because they do not share the same underlying object.
Comment: I understand that they don't share the same object.Please see the last comments to the questions
Comment: If the class provides a getter method, that does not violate encapsulation.


How to prove positivity of $\int_{\Bbb R_+\times\Bbb R_+} x(x-y)P(x,y) dx dy $

Question: I need to show that
$\int_{\Bbb R_+\times\Bbb R_+}x(x-y)P(x,y) dx dy \geq0$
where $P(x,y)=P(y,x)$ symmetric (potentially $P(x,y)\geq0$ everywhere).
Intuitively this seems obvious by splitting the integral along the diagonal. But so far I failed to prove it.
Answer: The additional hypothesis $P\ge0$ a.e. is necessary.
$$\begin{align}\int_{\Bbb R_+\times\Bbb R_+}x(x-y)P(x,y)dxdy&=\int_{y,h>0}(y+h)hP(y+h,y)dhdy+\int_{x,k>0}x(-k)P(x,x+k)dxdk\\&=\int_{y,h>0}\left((y+h)hP(y+h,y)-yhP(y+h,y)\right)dhdy\\&=\int_{y,h>0}h^2P(y+h,y)dhdy\\&\ge0.
\end{align}$$
Comment: In the first step I splitted the integral as you suggested, and made a change of variable on each half. In the second step, I renamed $y,h$ the variables $x,k$ of the second half, and used the symmetry.
Comment: I don't fully understand what is going on there in the frist step (including notation)


django : url tag -> how to use a variable as url_name?

Question: I have a django view which declare a target variable :
target  = "name_of_next_view_to_call"
return render(request, template, locals() )

I want to use this target variable into my template, I tried the following :
<form action="{% url '{{target}}' %}" method="post">

which gives me an error :
Reverse for '{{target}}' not found. '{{target}}' is not a valid view function or pattern name.

How to use the value of my "target" variable as the name of the url to be constructed ?
From the doc I know it should be possible :

The first argument is a URL pattern name. It can be a quoted literal
  or any other context variable.
Comment: thanks. You can add it as an answer and I check it
Answer: Within template tags, you don't need to mark context variables. They are usually recognized without the braces:
<form action="{% url target %}" method="post">

should work just fine. Just as you have probably used other tags in a similar way:
{% if target %}
# or
{% for obj in object_list %}

While some these examples are listed in the docs for template variables and tags, the point is not explicitly made there.
Comment: Moreover it's better to pass a dict in place of `locals()`. For instance, `mycontext = {'target' : 'myurl', 'foo' : 'bar', ...}` and `return (render(request, template, mycontext)`.
Comment: @EdouardThiel Well, `locals()` is a `dict`, but I would also prefer to be explicit about what I pass to the template there. But it has little to do with the issue of the question, so I'll leave it out.