Why does compiling my project to dll give error codes C2664 and E0289 error when compiling?

Question: BOOL CALLBACK callback(HWND hwnd, LPARAM param) {
    DWORD pid;
    GetWindowThreadProcessId(hwnd, &pid);
    if (pid == param) {
        TCHAR classNameBuf[MAX_PATH];
        GetClassName(hwnd, classNameBuf, MAX_PATH);
        std::string className(&classNameBuf[0]);
        if (className != ("MSCTFIME UI") && className != ("IME") && className != ("ConsoleWindowClass")) {
            window_handle = hwnd;
            return false;
        }
    }
    return true;
}

When I try to compile my project and run it, it gives these errors.:

Error E0289 no instance of constructor "std::basic_string<_Elem, _Traits, _Alloc>::basic_string [with _Elem=char, _Traits=std::char_traits<char>, _Alloc=std::allocator<char>]" matches the argument list

And this one

Error C2664 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>::basic_string(std::initializer_list<_Elem>,const _Alloc &)': cannot convert argument 1 from 'TCHAR *' to 'std::initializer_list<_Elem>'

Can someone point out what I am doing wrong?
Comment: Looks like your project is configured to have `TCHAR` alias wide characters, not the common `char` that's acceptable to `std::string`. Try `std::wstring`.
Answer: You are calling the TCHAR-based GetClassName() macro, and you have your project set to define UNICODE, thus TCHAR is mapped to wchar_t, not char.  You can't create a std::string from a wchar[] array (well, not the way you are trying to, anyway).
So, either:

change your project settings to use the MBCS charset instead of UNICODE, so that TCHAR maps to char, and GetClassName maps to GetClassNameA().

don't use TCHAR at all, use GetClassNameA() directly, eg:
CHAR classNameBuf[MAX_PATH];
GetClassNameA(hwnd, classNameBuf, MAX_PATH);
std::string className(classNameBuf);
if (className != "MSCTFIME UI" && ...)

if you really want to use TCHAR (which you shouldn't - this is not the '90s), you can use std::basic_string<TCHAR> instead, just be sure to wrap your string literals with the TEXT() macro, eg:
TCHAR classNameBuf[MAX_PATH] = {};
GetClassName(hwnd, classNameBuf, MAX_PATH);
std::basic_string<TCHAR> className(classNameBuf);
if (className != TEXT("MSCTFIME UI") && ...)

you can just avoid std::(basic_)string altogether and use lstrcmp() instead to match the same TCHAR encoding that GetClassName() uses, eg:
TCHAR classNameBuf[MAX_PATH] = {};
GetClassName(hwnd, classNameBuf, MAX_PATH);
if (lstrcmp(classNameBuf, TEXT("MSCTFIME UI")) != 0 && ...)


Selecting the most similar subset from an alternative dataset

Question: Background: I have two different datasets coming from two different source. Dataset A has m features (e.g. v1,v2,v3,v4) with let us say 1 million instances. Second dataset B has n features some of which are same as in A and then some (e.g. v1,v2,v3,v4,v5,v6,v7,v8,v9) and 250,000 instances. Although B is a smaller dataset, it is more diverse than A.
Problem:I want to evaluate for the dataset A, how the remaining the features i.e. v5,v6,v7,v8 and v9 will look like.
Approach:I intend to select a subset from B whose features (v1,v2,v3 and v4) that is representative of A in terms of range, mean, standard deviation, distribution. How can I pick the best subset from B that mimics A ?
I tried selecting the subset based on ranges of each of m features in B, but I see that the distributions of several features are different than those of A.
What is this type of problem called so I can do more research on this topic?
Comment: Because you have asserted "m is a subset of n"--and it would seem that should be interpreted as meaning A is a subset of B--then A would be the best subset of B that mimics A. Something's obviously wrong with this interpretation. Could you edit this post to clear up that confusion?
Comment: Thank you for the edits. I still cannot come up with an alternative interpretation. You now show explicitly how A is a subset of B and you still ask to select a subset from all of B that is most like A.  Again, A obviously is the answer.
Comment: @whuber thanks. The problem is that A does not come from B. I want to select a subset from B that is representative of A and then evaluate features v5, v6, v7, v8, v9.
Comment: I'm starting to follow, but your notation is not helping. Are you saying that A consists of $m$ features--let's call them $A_1, A_2, \ldots, A_m$--and B consists of $n\gt m$ possibly different features $B_1,B_2,\ldots,B_n$? Then you wish to select a an $m$-subset of $\{1,2,\ldots,n\}$, say $\{i_1,i_2,\ldots,i_m\}$, for which $B_{i_1}, B_{i_2}, \ldots, B_{i_m}$ best "mimics" A? If so, please adjust your notation to make this evident. At the same time, give us some details concerning what it really means for one set to "mimic" or "be representative of" another one. How is that to be measured?
Answer: This problem seem to be the same as selecting control groups for case-control studies. In the famous Doll and Hill study of smoking and lung cancer, the authors identified patients with lung cancer (cases) and then examined a control group "deliberately selected to be closely comparable in age and sex with the carcinoma of the lung patients." The higher incidence of smoking, particularly heavy smoking, in the lung cancer cases provided important evidence of the relation between that behavior and the disease.
So in your situation your group A represents the cases, and group B represents those from whom you will choose your controls.
This is not an easy problem in general, as it requires careful definition of what you mean by "representative." This Cross Validated page provides a good entry into algorithms for making such choices.
Answer: EdM's answer seems like a good match, and you should absolutely look into that literature. Here's a possible alternative approach to explore.
One reasonable way of measuring distances between distributions is known as the maximum mean discrepancy (MMD); a thorough overview is given by Gretton, Borgwardt, Rasch, Schölkopf, and Smola, A Kernel Two-Sample Test, JMLR 2012. The basic idea is to embed distributions into a reproducing kernel Hilbert space (RKHS), and then get distances between those distributions in that RKHS. If the kernel of the RKHS is $k(x, y) = \langle \varphi(x), \varphi(y) \rangle$, you can estimate the distance between the distributions as (letting $n = |A|$, $m = |B|$):
$$\Big\| \frac1n \sum_{i=1}^n \varphi(A_i) - \frac1m \sum_{i=1}^m \varphi(B_j)\Big\|.$$
You can compute this using only $k$ via the kernel trick,
but for large-scale problems it's easier to use a finite-dimensional approximation $z$ with $z(x) \in \mathbb{R}^D$
such that $z(x)^T z \approx \langle \varphi(x), \varphi(y) \rangle$.
A popular example of such an approximation was given by Rahimi and Recht, Random Features for Large-Scale Kernel Machines, NIPS 2007. If you use use the very popular Gaussian kernel $k(x, y) = \exp\left( - \frac{1}{2 \sigma^2} \lVert x - y \rVert^2 \right)$,
then
$k(x, y) \approx z(x)^T z(y)$
where
$$
z(x) = \begin{bmatrix} \sin(\omega_1^T x) & \cos(\omega_1^T x) & \dots & \sin(\omega_D^T x) & \cos(\omega_D^T x) \end{bmatrix}
$$
for $\omega_i \sim N(0, \frac{1}{\sigma} I)$ (using the same $\omega$ values for each $x$).
(This isn't exactly the version given in the linked version of the paper, but this version is better.)
The estimate of the MMD is thus as above, except with $z$ instead of $\varphi$.
You'll need to pick an embedding dimension; for this scale of data, maybe 5000 is good.
You'll also need to pick a $\sigma$; a reasonable rule of thumb is maybe the median of the pairwise distances between elements of $B$.
Now, you want to find the subset of $B$ whose distribution is closest to that of $A$. We can write the problem by defining a vector $\alpha \in \{0, 1\}^m$ where $\alpha_i$ determines if $B_i$ is included or not:
\begin{align}\DeclareMathOperator*{\argmin}{\arg\min}
\alpha^*
&= \argmin_{\alpha \in \{0, 1\}^m} \Big\| \frac{1}{n} \sum_{i=1}^n z(A_i) - \frac{1}{1^T \alpha} \sum_{i=1}^m \alpha_i z(B_i)  \Big\|^2
\end{align}
where we make sure to treat the case $\alpha = 0$ as infinite.
Now, let $Y_i = z(B_i) - \frac{1}{n} \sum_{i=1}^n z(A_i)$,
i.e. $Y_i$ is the distance of $B_i$'s embedding from our target vector,
and we want to find an assignment $\alpha$ that minimizes the mean distance:
\begin{align}
\alpha^*
&= \argmin_{\alpha \in \{0, 1\}^m} \Big\| \frac{1}{1^T \alpha} \sum_{i=1}^m \alpha_i Y_i \Big\|^2
= \argmin_{\alpha \in \{0, 1\}^m} \left\lVert \frac{Y \alpha}{1^T \alpha} \right\rVert^2
\end{align}
where $Y = \begin{bmatrix} Y_1 & \dots & Y_m \end{bmatrix}$.
The 1d, integer-valued data version of this problem is pretty close to subset sum, so it's probably NP-hard. We'll have to approximate.
If we fix $1^T \alpha$, then this becomes a binary quadratic program. There's been some work on solving these approximately, seemingly mostly (in a quick search) from the computer vision community. It still seems hard to solve, though.
But: in your case, I think you'd be happy with weights assigned to $B$, yes? You could then do weighted density estimation or whatever to try to figure out the distribution of the unknown components of $A$.
In that case, fix $1^T \alpha = 1$.
Our problem becomes
$$
\argmin_{\alpha \in [0, 1]^m}
\left\lVert Y \alpha \right\rVert^2
\quad\text{s.t.}\;
1^T \alpha = 1
.$$
This is a simple quadratic program with linear constraints, for which there are many solvers.

I actually just remembered that Hino and Murata, Information estimators for weighted observations, Neural Networks 2013 did something similar in their section 5.2, "Application to distribution-preserving data compression" using their nearest-neighbor-type estimator of the KL divergence. The problem there is more difficult both computationally and in terms of effort to code it up, though. (They don't say this, but it's actually a convex maximization, so they're not even guaranteed to get the global optimum.)

Another approach entirely is to think of this as a regression problem. Train a predictor for $(v_5, \dots, v_9)$ using $(v_1, \dots, v_4)$ as features on the training set $B$, and then apply the predictor to each data point from $A$. This is in some sense "more work" than what you're trying to do, but it might be more useful in the end. You could use transductive approaches to do so; Quadrianto, Patterson, and Smola, Distribution Matching for Transduction, NIPS 2009 even used an approach similar to the distribution matching scheme above to try to solve this problem.
Answer: Thanks to EdM, this problem is called matching. And I found an excellent package in R called Matching for this purpose. I found an excellent resource in this related document Genetic Matching for Estimating Causal Effects!.


How to set the app controls for landscape mode or portrait mode?

Question: I know Auto Layout can be used to make the sizes and position consistent when the orientation changes. Is it possible to completely change the layout when the orientation changes? Means when the device is rotated to landscape mode all the controllers can be changed their position and set accordingly the device mode . And this could be done for all the devices of iPhone 4,5,6 ,6 plus.Without using storyboard. Anybody can help me out for this problem. Thanks in advance.
Answer: ****for view to superview
[self addEdgeConstraint:NSLayoutAttributeLeft superview:self.view subview:subView];
<code>[self addEdgeConstraint:NSLayoutAttributeRight superview:self.view subview:subView];

[self addEdgeConstraint:NSLayoutAttributeTop superview:self.view subview:subView];

[self addEdgeConstraint:NSLayoutAttributeBottom superview:self.view subview:subView];
</code>
-(void)addEdgeConstraint:(NSLayoutAttribute)edge superview:(NSView *)superview subview:(NSView *)subview
{
    [superview addConstraint:[NSLayoutConstraint constraintWithItem:subview attribute:edge relatedBy:NSLayoutRelationEqual                                 toItem:superview   attribute:edge multiplier:1 constant:0]];
}
for vertical spacing between views
NSMutableArray* newVerticalConstraints = [NSMutableArray array];
<code>[newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[view1]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(viewMainBanner)]];

[newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view1]-%d-[view2]",10] options:0 metrics:nil views:NSDictionaryOfVariableBindings(view1, view2)]];

[newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view2]-%d-[view3]",10]  options:0 metrics:nil views:NSDictionaryOfVariableBindings(view2, view3)]];

[newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view3]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view3)]];

[self.view addConstraints:newVerticalConstraints];***
</code>
///instead of v we can use 'H' for horizontal spacing
Comment: Can u explain more your answer. I can't get you
Comment: if you need space between left part of the view and its super view use the        [self addEdgeConstraint:NSLayoutAttributeLeft superview:self.view subview:subView];
Comment: for vertical spce between two view NSMutableArray* newVerticalConstraints = [NSMutableArray array];           [newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view1]-%d-[view2]",10] options:0 metrics:nil views:NSDictionaryOfVariableBindings(view1, view2)]];                                       [self.view addConstraints:newVerticalConstraints];
Comment: This code does not work for vertical space.Your above code of addEdge Works Correctly.. Can u plz correct this again
Comment: NSMutableArray* newVerticalConstraints = [NSMutableArray array];                         [newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[view1]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view1)]];    [newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:[NSString stringWithFormat:@"V:[view1]-%d-[view2]",10] options:0 metrics:nil views:NSDictionaryOfVariableBindings(view1, view2)]]; [self.view addConstraints:newVerticalConstraints];  view1 and view2 are your subviews objects
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90433/discussion-between-shebin-and-nisha-gupta).


Variáveis globais em GLSL?

Question: Existe alguma maneira de declarar variáveis para que possam ser utilizadas em outros arquivos, com o mesmo valor da original? Já tentei usar o varying mas ela só funciona para o arquivo .vsh e .fsh da mesma parte. Exemplo:
No arquivo composite.vsh:
bool isNight = false;
void main() {
    isNight = true;
}

Ai, eu uso essa mesma variávei no arquivo skybasic.vsh:
if (isNight) {
    //está noite
}

sem ter que "recriar" tudo de novo essa variável. Como posso fazer isso?
Answer: Não sei ao certo o que você está querendo fazer. As variáveis do tipo varying servem para repassar dados do vertex shader para o fragment shader.
Existem as variáveis do tipo attribute que você envia os valores através da sua aplicação, então a partir do código da aplicação, você pode enviar para quantos shaders desejar.
Também existem as do tipo uniform, que são enviadas a partir da aplicação, a diferença em relação ao attribute é que as uniform não podem ser modificadas depois que estão no shader. Acho que seu caso seja as uniform

Variáveis globais em GLSL?


How to add text to python calculation?

Question: I'm trying to create this with the help of python:
in a for loop (from 1,10)
text i+(i*(i+2.5)) text [i+(i*(i+2.5))] text

results:
text 1+(1*(1+2.5) text 4.5 text
text 2+(2*(2+2.5) text 11 text
text 3+(3*(3+2.5) text 19.5 text
etc

Every i must have a different formatting
All code must be in one commandline

This is what I have created
python -c "import locale; locale.setlocale(locale.LC_ALL, ''); print('\n'.join(locale.format('\%.1f',i+(i*(i+2.5))) for i in range(1,10,1)))"

How can add the rest of the text?
UPDATE:
With the help of Tanmaya Meher's answer I created this command:
python -c "import sys,locale; [sys.stdout.write('text1 ' + '\%.2f+(\%.2f*(\%.2f+2.5))'\%(i,i,i) +' text2 ' + '\%.2f'\%(i+(i*(i+2.5))) + ' text3' + '\n') for i in range(1,11,1)]"

but I still don't know where to place local formatting (locale)
Comment: Why do you want it in one command line? You should use a script for that.
Comment: I need a commandline to use it as an external command in my texteditor (vim)
Answer: I think this will help. Please specify if anything need to be added
python -c "import locale; locale.setlocale(locale.LC_ALL, ''); print ('\n'.join('text1 ' + locale.format_string('%.1f+(%.1f*(%.1f+2.5))',(i,i,i), grouping = True)  + ' text2 ' + locale.format_string('%.1f',i+(i*(i+2.5)), grouping = True) + ' text3'for i in range(1,1111)))"

Output:
text1 1.0+(1.0*(1.0+2.5)) text2 4.5 text3
text1 2.0+(2.0*(2.0+2.5)) text2 11.0 text3
text1 3.0+(3.0*(3.0+2.5)) text2 19.5 text3
text1 4.0+(4.0*(4.0+2.5)) text2 30.0 text3
text1 5.0+(5.0*(5.0+2.5)) text2 42.5 text3
text1 6.0+(6.0*(6.0+2.5)) text2 57.0 text3
text1 7.0+(7.0*(7.0+2.5)) text2 73.5 text3
text1 8.0+(8.0*(8.0+2.5)) text2 92.0 text3
text1 9.0+(9.0*(9.0+2.5)) text2 112.5 text3
text1 10.0+(10.0*(10.0+2.5)) text2 135.0 text3
...
...
text1 1,109.0+(1,109.0*(1,109.0+2.5)) text2 12,33,762.5 text3
text1 1,110.0+(1,110.0*(1,110.0+2.5)) text2 12,35,985.0 text3

If you don't want grouping, i.e., 12,35,985.0 format (with commas); then just remove grouping = True from the code.
Comment: Almost the solution, wow! :) The first three `i` still have no local formatting. Do I have to place every `%.1f` within a format() box and every `'('`, `'))'` and `'+'` within quotes?
Comment: No, its not allowed. :) See the updated one with complete locale formatting and grouping if you want that. If not just remove `grouping = True` from code.
Comment: This would be a good solution if I'm enable to use locale formatting.
Comment: This works also but I still don't know where to place the local formatting: `python -c "import sys,locale; [sys.stdout.write('text1 ' + '\%.2f+(\%.2f*(\%.2f+2.5))'\%(i,i,i) +' text2 ' + '\%.2f'\%(i+(i*(i+2.5))) + ' text3' + '\n') for i in range(1,11,1)]"` (I update my question)
Comment: sorry for late reply.:) Just look at the updated code I have edited and saved according to your criteria.
Comment: See the updated code. Just placed text to be displayed and formatting and the for loop inside the `join`.
Comment: I think you have to as you are trying to print a string with some formatting. See the updated code with complete locale formatting.

How to add text to python calculation?


call Windows Color System from Java

Question: I need to call Windows Color System functions from Java. Following this tutorial i tried to call DLL function using Java Native Access. All examples from this tutorial works fine. When i try to load and use Mscms.dll (one of the WCS libraries) that DLL seems to be loaded successfully, but i can not call any functions. List of functions is here.
I got a message:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'GetColorDirectory'

What's wrong with my code? Could you help me please?
import com.sun.jna.Library;
import com.sun.jna.Native;

public class WCS_test {

public interface Mscms extends Library {
    // http://msdn.microsoft.com/en-us/library/dd316928%28v=vs.85%29.aspx
    boolean GetColorDirectory(String pMachineName, String[] pBuffer, int pdwSize);
}

private static Mscms mscms = (Mscms) Native.loadLibrary("C:/Windows/system32/Mscms.dll", Mscms.class);

public static void main(String[] args) {

    if (mscms != null)
        System.out.println("Library loaded\n");
    else
        System.err.println("Library loading error\n");

    String[] pBuffer = new String[1024];
    mscms.GetColorDirectory(null, pBuffer, pBuffer.length);
}
}

Answer: When you get a java.lang.UnsatisfiedLinkError that means that it could not find the function 'GetColorDirectory' inside of the Mscms.dll. Looking at the link from your source code http://msdn.microsoft.com/en-us/library/dd316928%28v=vs.85%29.aspx you should try the Unicode name GetColorDirectoryW.
Comment: You are right. I missed that info. Now error message changed to "Invalid memory access", so function have been found, but my calling parameters are wrong. I will work on it. I tried another function with simpler parameters (CMGetInfo) and it works. Thank you very much!

call Windows Color System from Java


Resharper 6 upgrade broke in-IDE unit test functionality

Question: After installing Resharper 6,  none of the unit test icons in my unit test classes (I am using MbUNut and Gallio) are visible, and when I select Run Unit tests from any of the menus, Visual Studio cannot find any unit tests...
Comment: So it is problem of MbUnit and Gallio integration with VS / Resharper 6. It works without problem with MSTest and NUnit (even better then 5.1).
Comment: possible duplicate of [Does MBUnit support Resharper 6?](http://stackoverflow.com/questions/6622646/does-mbunit-support-resharper-6)
Comment: Another info about Gallio not supported in Resharper 6: http://www.jetbrains.com/resharper/plugins/index.jsp#Gallio
Answer: Ignoring the lack of an actual question here; there's an issue raised on the Gallio/MBUnit project for this (Issue 850) and a corresponding one for ReSharper 6.1 (Issue 873).  You should follow up there.
Gallio 3.3.1 is the version when ReSharper 6 support appeared.


Toolbar to insert HTML tags while editing content

Question: This very site features a neat toolbar just over the textareas in forms, where clicking on "B", for instance, will spawn **strong text**, abstracting away the need to know Markdown.
Is there a way to do the exact same thing with, for instance, filtered HTML, or another text format based on HTML, on my Drupal site? I find that WYSIWYG editors tend to bloat the actual code and I want my users to get used to seeing HTML tags, but for the moment they can't be bothered with typing the markup in themselves.
Answer: After asking on #drupal on irc.freenode.org, I was looking for the BUEditor module that does just that, specifically looking at its native support for HTML tags:
Screenshot (using BBCode)
Answer: It looks like it may be using "Markdown" filters.
https://www.drupal.org/project/markdown
More info:
http://cms.about.com/od/drupal-modules/a/Write-Faster-In-Drupal-With-The-Markdown-Module.htm
Comment: My question was about the toolbox JSing markup tags into the textarea, not about the specific markup language (I needed it for HTML). See my answer.


Cauchy-Schwarz inequality for summation of inner product

Question: I am reading a paper and it mentions the following inequality to be true by Cauchy-Schwarz inequality:
for $x_i, y_i \in \mathbb{R}^d$ for $i = 1,\ldots, n$, and any positive definite matrix $A \in \mathbb{R}^{d\times d}$, the following is true
\begin{equation}
\sum_{i=1}^n x_i^\top A y_i \leq \sqrt{(\sum_{i=1}^n \|x_i\|_A)(\sum_{i=1}^n \|y_i\|_A)}
\end{equation}
Can someone provide step by step proof of how CS inequality is used here?
Comment: $A=B^*B$. Apply CS to $Bx,By$
Answer: Since $A$ is positive definite, there exists a matrix $B$ such that $A = B^\top B$. Next, note that $$x_i^\top Ay_i = x_i^\top B^\top By_i = (Bx_i)^\top (By_i)$$ for each $i\in\{1,2,\dots, n\}$. Put $$u := \begin{pmatrix} Bx_1 \\ Bx_2 \\ \vdots \\ Bx_n \end{pmatrix}\qquad\text{and}\qquad v := \begin{pmatrix} By_1 \\ By_2 \\ \vdots \\ By_n \end{pmatrix}.$$ Note that $u,v\in\mathbb R^{d^2}$. Now apply the Cauchy-Schwartz inequality:
$$u^\top v = \sum_{i=1}^n (Bx_i)^\top(By_i) \leq \sqrt{\left(\sum_{i=1}^n\vert(Bx_i)^\top(Bx_i)\vert\right)\left(\sum_{i=1}^n\vert(By_i)^\top(By_i)\vert\right)}.$$ Finally, note that $(Bz)^\top (Bz) = z^\top B^\top B z = z^\top Az$, and write $\Vert z\Vert_A$ for $z^\top Az$.


Computation of domain of infinitesimal generator of Brownian motion

Question: Let $L:C_{0}(\mathbb{R}) \supseteq D(L) \rightarrow C_{0}(\mathbb{R})$ be the generator of the standard one dimensional Brownian motion.
I calculated that $\{f \in C_{0}(\mathbb{R}):f'' \in C_{0}(\mathbb{R})\} \subseteq D(L)$ holds and that $Lf=\frac{1}{2}f''$ on this subset. But how can I show that $\{f \in C_{0}(\mathbb{R}):f'' \in C_{0}(\mathbb{R})\} = D(L)$ holds? I would be really grateful for some hints or a solution.
Answer: A mantra: "The domain of the generator is the range of the resolvent".
For standard Brownian motion the ($\alpha$-)resolvent is the integral operator
$$
U^\alpha g(x):=\int_{\Bbb R} {1\over \sqrt{2\alpha}}e^{-\sqrt{2\alpha}|y-x|} g(y) dy \quad x\in\Bbb R.
$$
(Here $\alpha>0$.)
It's not too hard to check that $D(L)=U^\alpha(C_0(\Bbb R))\subset \{f\in C_0(\Bbb R): f''\in C_0(\Bbb R)\}$.


MongoDB $addtoSet and $set in the same operation

Question: In my Meteor/javascript app, I am trying to update a specific MongoDB document via $addToSet on a certain part of that document followed by $set on a different part of that same document. There is no overlap between these two portions, so from what I read online it should be safe. But I can't seem to get the syntax correct. How can I carry out these two operations in one javascript command? The below works as two separate commands, and I assume it would be faster if they could be combined into just one write to Mongo.
Collection.update(
  {_id: documentId},
  {$addToSet:
    {data:
      {$each: newData}
    }
  }
);
Collection.update(
  {_id: documentId},
  {$set:
    {lastTxn: lastTxn,
     updatedAt: new Date()}
  }
);

Answer: As long as they are not on the same path ( which is the one thing you cannot do ) then it is perfectly fine. The $set and $addToSet operations are just top level "keys" of the "update document":
 Collection.update(
  { "_id": documentId },
  {
    "$addToSet": { "data": { "$each": newData } },
    "$set": {
       "lastTxn": lastTxn,
       "updatedAt": new Date()
    }
  }
);

Comment: @JonCursi One trip to the server is certainly faster, as is one operation in general. I makes sense to update multiple fields at the same time right? That's all that happens, just with different types of operations because MongoDB is a document store that supports that, and not a SQL table. In fact think of it like a "transaction" updating the parent and related document in one.
Comment: Thank you! And is it true that the single command in your answer is faster than the dual commands in my question?
Comment: An atomic write seems much more important than any ~ms speed considerations.


How can I grant a "Computer" user specifics permissions?

Question: On the dialog "object types" I see:

Built-in security principals
Users
Groups

But "Computers" is not there. How can I grant permissions for a computer user?
Comment: can you post a screenshot? Perhaps you're looking at the wrong object types dialogue.
Comment: @Mark Henderson: This question is related to another question I did. Please check the screenshoot of the accepted answer. http://serverfault.com/questions/302223/how-to-grant-permissions-to-network-service-to-write-in-a-remote-location
Comment: I'm trying to change permissions for a folder
Comment: gotcha. That's the correct place to be looking.
Comment: Is this server on a domain?
Comment: @Mark Henderson: yes
Comment: @Mark Henderson: sorry for confusing you with a wrong answer and thanks for your help
Answer: I'm doubtful that the server in question is joined to a domain for the reason that there are no "local" computer accounts, there are only "domain" computer accounts and that accounts for why the computer object type is not present. Can you verify that the server is in fact joined to a Windows domain? If so, what type of domain? Windows NT, 2000, 2003, or 2008?
Can you give us a screenshot verifying the domain membership of this particular server?
Comment: maybe I'm confused. How can I check if the computer is joined to a domain? In case it's not joined is not possible to add computers accounts?
Comment: 1. Bring up the System Properties, select the Computer Name tab, look at what is reads for Full computer name and either Workgroup or Domain. You might try posting a screen shot of that tab for us. 2. There are no "local" computer accounts so if the computer is not joined to a domain then you won't be able to grant permissions on the folders to any computer accounts, because they don't exist.
Comment: My fault, the computer is joined to a Workgroup but not to a domain. Then, computer accounts are not available :(
Comment: Glad you got it figured out. On a side note, computers aren't actually "joined" to a Workgroup. A workgroup is a loose "association" of computers in the sense that they appear together in Network Neighborhood (or My Network Places) but they share no central user database, authentication provider, etc.
Comment: thanks for your help!. Then, granting remote permissions to Network Service is out of my possibilities, right? Please see my previous question http://serverfault.com/questions/302223/how-to-grant-permissions-to-network-service-to-write-in-a-remote-location
Comment: Not that I'm aware of. Why does it need to use the Network Service account? Can you use a standard user account, created specifically for this purpose? If so, I can give you a few suggestions as to how to do it.
Comment: Network Service is the user used by all application pools (IIS) on a web server farm and I'd need to provide to this user write permissions on a media server. If this is not possible, I'll need to create a custom user and assign it to all app pools. Thanks!
Comment: Sounds like you're on track then. Glad to help.
Answer: I see Built-in security principals, Service Accounts, Computers, Groups, Users.
Not that I have much clue what kind of object you are setting the security for, or on what OS.
I guess whatever item you are setting security on cannot have computer account security set on it?
EDIT
What happens if you do it from the command line? e.g.
<code>cacls "c:\folder\wherever" /E /G "domainname\computername$:F"
</code>
Comment: Setting permissions for a folder, the OS is on the question tags...
Comment: Ah, and, so it is.
Comment: See edit for suggestion.


module_invoke to create user search block not working

Question: I've done the following to create two search blocks:
$content_search = module_invoke('search', 'block_view', 'content_search');
$user_search = module_invoke('search', 'block_view', 'user_search');

And I then call the blocks as needed like so:
<?php print render($content_search['content']); ?>
<?php print render($user_search['content']); ?>

They render correctly and the content search works just fine, but running something through the user search block just searches content. I noticed that regardless of which block I use, they both go to the URL http://example.com/search/node/[search parameters]
(This is Drupal 7 BTW)
Answer: The search block only works for the default search type. From search_box_form_submit():
$info = search_get_default_module_info();
if ($info) {
  $form_state['redirect'] = 'search/' . $info['path'] . '/' . trim($form_state['values'][$form_id]);
}
else {
  form_set_error(NULL, t('Search is currently disabled.'), 'error');
}

The third parameters you're passing ('content_search', 'user_search') are ignored. Presumably your default search type is content and that's why you're being redirected to the content search in both forms.
You can build the correct search form pretty easily though:
$content_form = drupal_get_form('search_form', NULL, '', 'node');
$user_form = drupal_get_form('search_form', NULL, '', 'user');

Comment: How do I get $content_form and $user_form to display? I tried both render($content_form); and drupal_render($content_form) and both are blank. print $content_form produces the familiar "string to array conversion" error and print_r($content_form) does display the expected array data so I know the drupal_get_form call is working properly.
Comment: Yeah putting them through `render` is all you should need to do. Where is this code? It should be in a preprocess function, if it's in the template file itself that might be part of the problem
Comment: It's in a block (with PHP code). Will that not work?
Comment: I'm not sure to be honest, it's a bad idea to use the php filter for a bunch of reasons. I guess this could be one of those reasons. I'd recommend trying it the 'proper' way (hook_block_info + hook_block_view) to see if you have better luck
Comment: You mean as in a custom module?


How to merge the output of two associative arrays with no unique keys?

Question:
I've got the feeling that I get stuck with something that seemed to be a trivial task. Please take a look at the $data array. This is the data skeleton for a multilevel menue. $data['name'] contains the names for the given menue points/buttons and $data['url'] the corresponding links.  The array dimensions $data['name'] and $data['url'] are perfectly in sync - with exact same nodes, same element count and so on.
Having this I started to write a simple output function - with names only first. I know the code isn't pretty but it works. Beat me but my mind aches when mentioning recursion ;) Nevertheless my primitive way leads to proper output. In the second step I needed to add the url information corresponding to the names/buttons but this is where I fail and begun to feel dumb.
While iterating through $data['name'] I  need a pointer for the current element and would use it to get the corresponding url from $data['url'] but nope - this is an associative array so this way leads to the dead end. The keys aren't unique by the way ... this would be to easy sigh This array is only a shortened version of the original one which is generated from a 150 pages long word document that is still growing and changing.
Any ideas how to output button-names + corresponding url's ? I placed the working code on codepad.org for fiddling around.
My array:
<?PHP

$data = array (
  'name' =>
  array (
    'basics' =>
    array (
      0 => 'about',
      1 => 'why_do_i_need_it',
      2 => 'institutions',
      3 => 'agencys',
      4 => 'impact',
      5 => 'failing_this_test',
      6 => 'evaluation_criteria',
      7 => 'evaluation_range',
      8 => 'reissue_request',
      9 => 'procedure',
      'procedure' =>
      array (
        0 => 'psych',
        'psych' =>
        array (
          0 => 'test_1',
          1 => 'test_2',
          2 => 'test_3',
          3 => 'test_4',
          4 => 'test_5',
        ),
        'med' =>
        array (
          0 => 'examination',
          1 => 'exploration',
          2 => 'observation',
        ),
      ),
      10 => 'report',
      11 => 'revision',
      12 => 'evaluation',
      13 => 'report_structure',
      14 => 'charges',
      15 => 'sample_test',
    ),
    'drugs' =>
    array (
      0 => 'introduction',
      1 => 'requirements',
      'requirements' =>
      array (
        0 => 'sincerity',
        1 => 'excuses',
        2 => 'insight',
        3 => 'change',
        4 => 'stability',
      ),
      2 => 'procedure',
      3 => 'diagnostics',
      'diagnostics' =>
      array (
        0 => 'addiction',
        1 => 'advanced_level',
        2 => 'dangers',
        3 => 'sample_drugtest',
      ),
      4 => 'the_day_one',
      5 => 'background',
      6 => 'today',
      7 => 'intake',
      8 => 'screenings',
      'screenings' =>
      array (
        0 => 'analysys',
        1 => 'element',
      ),
    ),

  'url' =>
  array (
    'basics' =>
    array (
      0 => 'basics.about',
      1 => 'basics.why_do_i_need_it',
      2 => 'basics.institutions',
      3 => 'basics.agencys',
      4 => 'basics.impact',
      5 => 'basics.failing_this_test',
      6 => 'basics.evaluation_criteria',
      7 => 'basics.evaluation_range',
      8 => 'basics.reissue_request',
      9 => 'basics.procedure',
      'procedure' =>
      array (
        0 => 'basics.procedure.psych',
        'psych' =>
        array (
          0 => 'basics.procedure.psych.test_1',
          1 => 'basics.procedure.psych.test_2',
          2 => 'basics.procedure.psych.test_3',
          3 => 'basics.procedure.psych.test_4',
          4 => 'basics.procedure.psych.test_5',
        ),
        'med' =>
        array (
          0 => 'basics.procedure.med.examination',
          1 => 'basics.procedure.med.exploration',
          2 => 'basics.procedure.med.observation',
        ),
      ),
      10 => 'basics.report',
      11 => 'basics.revision',
      12 => 'basics.evaluation',
      13 => 'basics.report_structure',
      14 => 'basics.charges',
      15 => 'basics.sample_test',
    ),
    'drugs' =>
    array (
      0 => 'drugs.introduction',
      1 => 'drugs.requirements',
      'requirements' =>
      array (
        0 => 'drugs.requirements.sincerity',
        1 => 'drugs.requirements.excuses',
        2 => 'drugs.requirements.insight',
        3 => 'drugs.requirements.change',
        4 => 'drugs.requirements.stability',
      ),
      2 => 'drugs.procedure',
      3 => 'drugs.diagnostics',
      'diagnostics' =>
      array (
        0 => 'drugs.diagnostics.addiction',
        1 => 'drugs.diagnostics.advanced_level',
        2 => 'drugs.diagnostics.dangers',
        3 => 'drugs.diagnostics.sample_drugtest',
      ),
      4 => 'drugs.the_day_one',
      5 => 'drugs.background',
      6 => 'drugs.today',
      7 => 'drugs.intake',
      8 => 'drugs.screenings',
      'screenings' =>
      array (
        0 => 'drugs.screenings.analysys',
        1 => 'drugs.screenings.element',
      ),
    ),
  ),
 )
);

My code:
//-----------------------------------------------------------

    menueOutput($data);

//-----------------------------------------------------------

function menueOutput($str)
{
foreach($str AS $index =>$atom)
{
    if(is_array($atom))
    {
        echo "\n\r>".$index;

        foreach($atom AS $index2 => $atom2)
        {
            if(is_array($atom2))
            {
            echo "\n\r>>".$index2;

                foreach($atom2 AS $index3 => $atom3)
                {
                    if(is_array($atom3))
                    {
                        echo "\n\r>>>".$index3;

                        foreach($atom3 AS $index4 => $atom4)
                        {
                            if(is_array($atom4))
                            {
                                echo "\n\r>>>>".$index4;

                                foreach($atom4 AS $index5 => $atom5)
                                {
                                    if(is_array($atom5))
                                    {
                                        echo "\n\r>>>>>".$index5;
                                        foreach($atom5 AS $index6 => $atom6)
                                        {
                                            echo "\n\r------".$atom6;
                                        }
                                    }
                                    else
                                        echo "\n\r-----".$atom5;
                                }
                            }
                            else
                                echo "\n\r----".$atom4;
                        }
                    }
                    else
                    {
                        echo "\n\r---".$atom3;
                    }
                }
            }
            else
            {
                echo "\n\r--".$atom2;
            }
        }
    }
    else
    {
        echo "\n\r".$atom;
    }
 }
}

//-----------------------------------------------------------

UPDATE:
I'm also considering to merge the partial arrays by parallel loops. I found this  MULTIPLEITERATOR EXAMPLE that may be what I need (if I'll be lazy). Otherwise I'll be forced to refactor my data which can be painful. If I do this Revent answer would become very useful.
Comment: Holy nesting, Batman!
Comment: Must be some kind of array humor *lol*
Answer: What I do with menu systems is have a multi-dimensional array with all the info for one menu item in one element of the array. For example
$menu = array(
   'top_level' => array(
      0 => array('name'=>'Item 1','url' =>'Url 1', ...),
      1 => array('name'=>'Item 2','url' =>'Url 2', ...)
    ),
    'sub_level' => array(
      0 => array('name'=>'Item 1','url' =>'Url 1', ...),
      1 => array('name'=>'Item 2','url' =>'Url 2', ...)
    ),
    ...
);

I go through the pain initially of fetching my data and putting into an array that is easy to output to the screen.
Without unique ids in your arrays, you are left to match them by position in the array, which may or may not be reliable. If you have control over the data going into them I would highly recommend rebuilding your array into something that makes more sense. If you have over 150 items then you will need to be as efficient as you can with your array design.
UPDATE:
Here is how I would probably structure the data:
<?php
$data = array (
  'basics' => array ('name'=>'basics', url=>'basics', 'children'=>
      array (
         0 => array('name'=>'about', 'url'=>'basics.about'),
         1 => array('name'=>'why_do_i_need_it', 'url'=>'basics.why_do_i_need_it'),
         2 => array('name'=>'institutions', 'url'=>'basics.institutions'),
         3 => array('name'=>'agencys', 'url'=>'basics.agencys'),
         4 => array('name'=>'impact', 'url'=>'basics.impact'),
         5 => array('name'=>'failing_this_test', 'url'=>'basics.failing_this_test'),
         6 => array('name'=>'evaluation_criteria', 'url'=>'basics.evaluation_criteria'),
         7 => array('name'=>'evaluation_range', 'url'=>'basics.evaluation_range'),
         8 => array('name'=>'reissue_request', 'url'=>'basics.reissue_request'),
         9 => array('name'=>'procedure', 'url'=>'basics.procedure', 'children' =>
            array(
               0 => array('name'=>'psych', 'url'=>'psych', 'children'=>
                  array(
                     0 => array('name'=>'test_1', 'url'=>'test_1'),
                     1 => array('name'=>'test_2', 'url'=>'test_2'),
                     2 => array('name'=>'test_3', 'url'=>'test_3'),
                     3 => array('name'=>'test_4', 'url'=>'test_4'),
                     4 => array('name'=>'test_5', 'url'=>'test_5')
                  )
               ),
               1 => array('name'=>'med', 'url'=>'med', 'children'=>
                  array(
                     0 => array('name'=>'examination', 'url'=>'examination'),
                     1 => array('name'=>'exploration', 'url'=>'exploration'),
                     2 => array('name'=>'observation', 'url'=>'observation')
                  )
               )
            )
         ),
         ...
      )
    )
  );
?>

As you can see, each menu item stores both the name and the url. If there are children, you simply add a third element to that array with the children in a similar array. Your PHP code to extract the data loops should be greatly simplified as shown below:
foreach ( $data as $top )
{
   echo '
'.$top['name'].'';   // print out the menu item

   if ( array_key_exists('children', $top) )
   {
      foreach ($top['children'] as $level2)
      {
         echo '
 - '.$level2['name'].'';   // print out the children
         if ( array_key_exists('children', $level2) )
         {
            foreach ($level2['children'] as $level3)
            {
               echo '
   - '.$level3['name'].'';   // print out the grandchildren
               if ( array_key_exists('children', $level3) )
               {
                  // process the greatgrandchildren, etc.
               }
            }
         }
      }
   }
}

Comment: Revent, your suggestion sounds resonable but this flat Array design doesen't work with my data. I've got here herarchical structures where items can have One or more children, grandchildren and even grandgrandchildren. In general I like your idea with flat arrays but I've got no clue how to adapt it to my data and keep the hierarchy.
Comment: Has no one an idea or direction?
Comment: One way would be to give each menu item a unique id, then have sub-menu items store that parent id. You could even do different arrays for each menu level this way - of course you would have four nested loops in PHP to output them, but it should still render fairly quickly. This kind of tree structure might also lend itself to a recursive algorithm, but you may not want to go there.
Comment: I have updated my answer above with the data structure and PHP code that I would use.
Comment: Oh wow! Reverent this looks great. I'll give it a try this evening. The first look I took on [codepad.org](http://codepad.org/l1Q3fEsn) is very promising. This may be the way to go as far as I would be able to refactor my array to the new structure.


Gap between Continuous Functions on Closed and Open subsets

Question: Let $A$ be a proper non-empty subset of $\mathbb{R}^n$.  If $A$ is closed then Tietze's extension theorem shows that $C(A,\mathbb{R}^m)$ can be identified with $C(\mathbb{R}^n,\mathbb{R}^m)$.  However, if $A$ is open, this is not so in general.
For example, if $A=(0,1)\cup (1,2)$ then there the function $f= I_{(0,1)} + 2I_{(0,2)}$ is in $C(A,\mathbb{R})$ but cannot be extended to a function in $C(\mathbb{R},\mathbb{R})$.  Conversely however, every function in the later space restricts to one from the former.

My question is, if $A=\bigcup_{n=1}^N A_n$ where, $A_n$ are pairwise disjoint open subsets of $\mathbb{R}^d$, then is every function in $C(A,\mathbb{R}^m)$ of the form
$$
f = \sum_n f_n I_{A_n}
,
$$
where $f_n$ is a continuous function on $\mathbb{R}^d$?
Comment: Can be identified with? They're not homeomorphic, if that's what you think... There *is* a linear 1-1 map between them.
Comment: What is the domain of definition of each $f_n$ is it $A$ or $\Bbb R^n$?
Comment: @Sumanta  Their domain in $R^n$ but they are only continuous on $A_n$.
Comment: @HennoBrandsma Oh they aren't so the restriction is just an injective linear map but not an extension since it doesn't have a unique section?
Answer:
If $A$ is closed then Tietze's extension theorem shows that $C(A,\mathbb{R}^m)$ can be identified with $C(\mathbb{R}^n,\mathbb{R}^m)$.

Not really. The theorem states that $C(A,\mathbb{R}^m)$ can be identified with a subset of $C(\mathbb{R}^n,\mathbb{R}^m)$. Or more precisely that there is a function $F:C(A,\mathbb{R}^m)\to C(\mathbb{R}^n,\mathbb{R}^m)$ with the property $F(f)_{|A}=f$. In particular $F$ is injective. But such bijective function cannot exist if $A$ is a proper closed subset of $\mathbb{R}^n$, since every continuous function $A\to\mathbb{R}^m$ admits multiple (infinitely many) distinct extensions to $\mathbb{R}^n$.

My question is, if $A=\bigcup_{n=1}^N A_n$ where, $A_n$ are pairwise disjoint open subsets of $\mathbb{R}^d$, then is every function in $C(A,\mathbb{R}^m)$ of the form
$$
f = \sum_n f_n I_{A_n}
,
$$
where $f_n$ is a continuous function on $\mathbb{R}^d$?

This already fails for $N=1$, e.g. $f:(0,\infty)\to\mathbb{R}$, $f(x)=1/x$. And so this fails for any $N$ (even infinite) simply by taking $N$ open distinct subsets of $(0,\infty)$ with $0$ being a limit point of one of them.
Comment: Yes, this will work in that scenario. Because this clearly means that such a map $A\to\mathbb{R}^m$ can be extended to $\overline{A}$ by putting $0$ at the boundary $\partial A$. And then Tietze applies to $\overline{A}$. We again end up with a single $f_1=\cdots =f_n$ function.
Comment: Right, so the correct second statement should be for every compact $K\subseteq A$, there exists $f_1,\dots,f_n$ continuous on $\mathbb{R}^d$ such that $f|_K = \sum_{n} f_nI_{A_n\cap K}$?  (This would also reflect the ucc topology typically on this set).
Comment: If $K\subseteq A$ is compact then it is closed in $\mathbb{R}^n$ (regardless of what $A$ is) and so Tietze extension theorem applies. And so yes, actually a single $f_1=\cdots = f_n$ exists with this property.
Comment: Actually, I'm thinking, if I replace $C(A,\mathbb{R}^m)$ with $C_b(A,\mathbb{R}^m)$ then the second claim would in fact hold no?  Since it seems only explosions at the boundary can cause a problem.
Comment: $C_b(A,\mathbb{R}^m)$ meaning bounded? Still no, e.g. $x\mapsto \sin(1/x)$ cannot be continuously extended to $0$. The problem is not boundary. The problem is [essential discontinuity](https://en.wikipedia.org/wiki/Classification_of_discontinuities#Essential_discontinuity).
Comment: Right, so its would only be possible if we use $C_0(A,\mathbb{R}^m)$...so that terms vanish at $\partial A$?


Find all functions $f:\mathbb{R} \to \mathbb{R},$ which is continuous in $\mathbb{R}$ then $f(x-y)+f(y-z)+f(z-x)+27=0.$

Question: Find all functions $f:\mathbb{R} \to \mathbb{R},$ which is continuous in $\mathbb{R}$ then $$f(x-y)+f(y-z)+f(z-x)+27=0.$$
I actually don't have any ideas to deal with it, but here is some tries:
Let $x=y,y=z,z=x$ then we have $3f(0)=-27\Rightarrow f(0)=-9.$
Let $z=y$ then $f(x-y)+f(y-x)+18=0.$
Let $y=0$ then $f(x)=-18 -f(-x).$
Also, if we let $x-y=a;y-z=b;z-x=c\Rightarrow y-x=b+c.$
Thus $f(a)+f(b+c) +18 =0; f(a)+f(b)+f(c)+27=0,$ and $a+b+c=0.$
Comment: Fixed tags for you. FYI functional analysis is the study of infinite dimension vector spaces.
Comment: This is the Cauchy functional equation, but dressed up a little bit.
Comment: I still can't see how I can use Cauchy functional equation, sorry.
Answer: First, do a translation $f(x)=g(x)-9$ then you will get
$g(x-y)+g(y-z)+g(z-x)=0$. Now let $x-y=a, y-z=b$ then $z-x=-(a+b)$, putting this we get
$g(a)+g(b)=-g(-(a+b))$.
Now from $f(x)=-18-f(-x)$ we can show $g(x)=-g(-x)$ So we get the cauchy equation.
$g(a)+g(b)=g((a+b))$.
Comment: This is the same, you solve for g and get $g(x)=cx$ then you will find $f(x)=cx-9$ for the second comment just put $f=g-9$ in $f(x)=-18-f(-x)$.
Comment: Also I still don't know how we can show $g(x)=-g(-x),$ help me, thanks a lot. (+1)


How do we calculate multiclass probabilities in yardstick?

Question: I have a multiclass classification problem and want to build a precision-recall curve using pr_curve from yardstick library in R. This function requires that a tibble with probabilities for each class were fed to it, like this (this is data(hpc_cv)).

How do I get there from my classification results, stored as columns in a tibble?
library(yardstick)
data <- tibble(predicted = as.factor(c("A", "A", "B", "B", "C", "C")),
               expected = as.factor(c("A", "B", "B", "C", "A", "C")))
data %>% conf_mat(truth = expected, estimate = predicted)

I have not found a function in yardstick (or elsewhere) to calculate those.
I am not sure how class probs are calculated, I am thinking along these lines:
data %>% filter(predicted == "A") %>% summarise(n = n() / 6)

Is this correct? If so, I wonder if there is a nice way to do it without for-loops on each class in each fold, and to receive a tibble like hpc_cv on the picture above.
Answer:
I am not sure how class probs are calculated

Class probabilities are generated by a specific model for each individual data point.
PR curves (and precision and recall) are metrics for data sets where the outcome has two classes. You can do multiclass averaging to get an overall PR curve AUC though.
There is an example below but I would advise reading the tidymodels book for a bit before proceeding.
library(nnet) # <- for mutlinom_fit
library(tidymodels)

tidymodels_prefer()

data(hpc_data, package = "modeldata")

set.seed(1)
hpc_split <- initial_split(hpc_data)
hpc_train <- training(hpc_split)
hpc_test  <- testing(hpc_split)

set.seed(2)
mutlinom_fit <-
  multinom_reg() %>%
  fit(class ~ iterations + compounds, data = hpc_train)

test_predictions <- augment(mutlinom_fit, new_data = hpc_test)

# examples of the hard class predictions and the
# predicted probabilities:
test_predictions %>% select(starts_with(".pred")) %>% head()
#> # A tibble: 6 × 5
#>   .pred_class .pred_VF .pred_F .pred_M .pred_L
#>   <fct>          <dbl>   <dbl>   <dbl>   <dbl>
#> 1 VF             0.641   0.279  0.0670  0.0128
#> 2 VF             0.640   0.280  0.0671  0.0128
#> 3 VF             0.628   0.287  0.0711  0.0138
#> 4 VF             0.628   0.287  0.0711  0.0138
#> 5 VF             0.626   0.288  0.0716  0.0139
#> 6 VF             0.626   0.288  0.0719  0.0140

# a confusion matrix
test_predictions %>% conf_mat(class, .pred_class)
#>           Truth
#> Prediction  VF   F   M   L
#>         VF 516 278  74  16
#>         F   18  46  36   4
#>         M    2   7  19  21
#>         L    0  11   7  28

# create some metrics:
cls_metrics <- metric_set(accuracy, precision, recall, pr_auc)
# precision, recal, and the PR AUC are caluclated using macro weighting of 4
# different 1 vs all results.
# See https://yardstick.tidymodels.org/articles/multiclass.html

# evaluate them
test_predictions %>%
  # See ?metric_set for more information. We pass the truth (class), all of the
  # predicted probability columns (.pred_VF:.pred_L), and the named hard class
  # predictions.
  cls_metrics(class, .pred_VF:.pred_L, estimate = .pred_class)
#> # A tibble: 4 × 3
#>   .metric   .estimator .estimate
#>   <chr>     <chr>          <dbl>
#> 1 accuracy  multiclass     0.562
#> 2 precision macro          0.506
#> 3 recall    macro          0.411
#> 4 pr_auc    macro          0.481

Created on 2022-12-09 with reprex v2.0.2
Comment: Thank you. In my case, it is not a trained model, but a comparison of several distance metrics for text classification (like here https://link.springer.com/chapter/10.1007/978-3-030-53360-1_3). I have a corpus of texts and a bunch of distance metrics (some of them implemented in philentropy), and I take multiple samples from my corpus to compare their performance. So, is it possible to get probs without training a model as in the example above?


Inconsistent auto-layout rendering

Question: There are a few issues with auto-layout that seem to present some inconsistencies from one scene to the other of my SpriteKit game:
Firstly, despite using the same piece of art for the ground in the first and second scenes, the artwork appears way smaller in the first. I am not sure how this is possible. They are both PNG files and the two scenes that hold the images are .swift, and I loaded the exact same images into imagesx.cassets. Yet when the first scene opens, the ground node is shorter and thinner than in the second scene (which I created first).
The other inconsistency is In my second scene when I use:
<code>self.groundbar.anchorPoint = CGPointMake(0.0, 0.5)
self.groundbar.position = CGPointMake(CGRectGetMinX(self.frame), CGRectGetMinY(self.frame) + (self.groundbar.size.height) / 2)
</code>
The groundbar nestles precisely at the bottom of my screen, halfway through the middle of the groundbar (as indicated by the y-value).
Now, when I try this SAME code on the first scene, the ground is nowhere on the screen. I thought this might be due to the strange fact that the ground renders smaller in the first scene, but then it shouldn't matter because it's auto-layout and is referencing the specific characteristics of the node.
It seems like I'm almost dealing with two separate sets of auto-layout constraints or something. The first scene IS a physicsworld, and the second scene IS NOT, but when I removed that the ground in the first scene still did not render properly.
Even when I try to change the anchorPoint, the texture of the node moves visually, but the collision physics stays the same.
Why the major difference in auto-layout?
Why are my two pieces of art different sizes when rendered in the same scene despite being the same pieces of art?
Comment: You can't use AutoLayout with Sprite Kit - AutoLayout is only for UIKit. Regarding your problem, have you checked the `scaleMode` and `size` of each scene?
Comment: Well The first scene loads up right after the Launch Screen. I have a node, that when clicked, initializes the second scene. The code I used for this was: scene.scalemode = .ResizeFill and scene.size = skView.bounds.size
Comment: Are you using a different `scaleMode` for each scene? That would definitely cause objects to look different between scenes.
Comment: I'm a beginner and am not quite sure what you mean by this. Is there a way I can check the scaleMode?
Answer: You should be able to check which scaleMode is being used in the game's view controller. Make sure that the scaleModes are the same (there are three scaleModes: .AspectFill, .AspectFit and.ResizeFill). Next, make sure the anchorPoints match up (by default, the anchorPoints are (x: 0, y:0). Both things can be checked in the game's ViewController.

Inconsistent auto-layout rendering


OpenCL kernel with generic data type

Question: When writing code for kernels, is it possible to specify a generic data type so that copying the kernel for each used data type is not necessary? Currently I'm using preprocessor macros to define the whole function with various data types:
#define REDUCTION(type) __kernel void reduce_##type##_f(__global __read_only type* a) \
{ \
// do something
} \

REDUCTION(float)
REDUCTION(float2)

This however is not very comfortable. Is there some type specifier like gentype available?
Answer: You should be able to do that starting with OpenCL 2.1 which let you use C++ and templates in kernel code Knronos's OpenCL page.
With that, you can simply write:
template <class T>
void reduce_f(__global __read_only T* a) {
   // do something
}

However I am not 100% sure templates would be available in the definition of __kernel functions. If that is not the case, you would still need to wrap the kernel declaration within preprocessing macros as so:
#define REDUCTION(type) __kernel void reduce_##type##_f(__global __read_only type* a) \
{ \
  return reduce_t(a); \
}

REDUCTION(float)

Comment: Shouldn't your macro have backslashes at ends-of-lines?

OpenCL kernel with generic data type


Using instagram API

Question: i need to use instagram api public_content scope to
get the recent media liked by the user.
and this is use case and permissions compliance

We will approve submissions of apps that fall into these use cases:
<code>1-To help individuals share their own content with 3rd party apps
2-To help brands and advertisers understand and manage their audience and digital media rights
3-To help broadcasters and publishers discover content, get digital rights to media, and share media with proper attribution
</code>

my qusetion is what they mean by brands , advertisers,broadcasters and publishers ?
and i  need some examples of applications that compatible with these conditions to use the api
Answer: A publisher is anyone who is publishing content, like a blogger.

Using instagram API


Is this JSON correct?

Question: How can I validate this JSON and add placeholders for the columns in SQL table?
<code>[
  {name: 'Afghanistan', code: 'AF'},
  {name: 'Åland Islands', code: 'AX'},
  {name: 'Albania', code: 'AL'},
  {name: 'Algeria', code: 'DZ'},
  {name: 'American Samoa', code: 'AS'},
]
</code>
Comment: What you mean by "placeholders for the columns in SQL table" is utterly unclear. [Edit] the question and add a [example].
Comment: SQL is just a language used within DB Management Systems, you should share with us name of your DBMS product in order to get an exact answer.
Answer: You must use quotes also for field names. There are plenty of JSON validators and formatters online where you can test the syntax of your JSON data (e.g. https://jsonformatter.org/).
<code>[
  {"name": "Afghanistan", "code": "AF"},
  {"name": "Åland Islands", "code": "AX"},
  {"name": "Albania", "code": "AL"},
  {"name": "Algeria", "code": "DZ"},
  {"name": "American Samoa", "code": "AS"}
]
</code>
Comment: Thank you so much! I'm new to JSON and still learning. Do you know how I can add a placeholder for all objects in this file without doing it manually?
Comment: What do you consider a placeholder in this file ? You mean replacing name: with "name": ? In this case, you can use any text editor. Or you can use the file you find here: https://gist.github.com/keeguon/2310008#gistcomment-869598

Is this JSON correct?


reCaptcha Google

Question: Olá.
Bom tenho este código aqui.
Porem tenho um problema...
O reCaptcha apareceu no meu site, porem a pessoa consegue enviar o formulario mesmo não tendo feito o passo do Captcha...
<form action="" method="post" name="power" id="power">

Os campos com "*" são obrigatórios!!

         Nome*

         <input  class="form-control" name="nome" type="text" id="nome" placeholder="Nome Completo" required>

         Facebook

         <input  class="form-control" name="facebook" type="text" id="facebook" placeholder="Link do Perfil no Facebook">

         Skype

         <input  class="form-control" name="skype" type="text" id="skype" placeholder="Contato Skype">

         Discord

         <input  class="form-control" name="discord" type="text" id="discord" placeholder="Contato Discord">

         Assunto*

         <input  class="form-control" name="assunto" type="text" id="assunto" placeholder="Assunto"  required>

         Email*

         <input class="form-control" name="email" type="email" id="email" placeholder="E-mail"  maxlength="40" required>

         Mensagem*

         <textarea class="form-control" name="mensagem" id="mensagem" placeholder="Sua Mensagem"  rows="5" required></textarea>

   <input name="Send" class="button-contato" type="submit" id="Send" value="Enviar" required>

   <input name="Clear" class="button-contato" type="reset" id="Clear" value="Limpar">
   <?php
      if (isset($_POST[nome])){
      $nome =   $_POST[nome];
      $facebook =   $_POST[facebook];
      $skype =   $_POST[skype];
      $discord =   $_POST[discord];
      $email =  $_POST[email];
      $mensagem = $_POST[mensagem];
      $grecaptcha = $_POST[grecaptcha];
      $assunto = "$_POST[nome], esta entrando em contato com voce.     Assunto: $_POST[assunto]";

        $send = ("$email_01"); //Coloque seu E-mail aqui.

        $data = date("d/m/y");
        $hora = date("H:i:s");
        $ip = $_SERVER[REMOTE_ADDR];

        $headers .= "From: $send\r\n";
                                //para o envio em formato HTML
                                $headers = "MIME-Version: 1.0\r\n";
                                $headers .= "Content-type: text/html;
                                charset=iso-8859-1\r\n";

                                $corpo =("
                                            Nome Completo:    $nome

                                            Perfil Facebook:   $facebook

                                            Contato Skype:    $skype

                                            Contato Discord:    $discord

                                            E-Mail:    $email

                                            Mensagem:
  $mensagem

                                              Data:   $data

                                              Hora:   $hora

                                              IP:   $ip

                                            ");

                                    mail($send, $assunto, $corpo, $headers);

                                echo "";

      } else{

      }

       ?>
</form>

Não entendi a API do reCaptcha muito bem. Alguém poderia fazer para mim ?
Comment: o reCaptcha irá te passar uma chave, que você irá validar no webservice da Google, usando PHP
Comment: Se o usuário não realizar o captcha, o valor passado pelo form será nulo. Se reCaptcha perder a validade, ao verificar no PHP, ele emitira um erro.
Comment: @Sveen isso eu entendi. O que não estou conseguindo fazer e que, a pessoa passe do formulario fazendo ele
Comment: Relacionada: https://pt.stackoverflow.com/q/268143/8063
Comment: Você só está a verificar o nome `if (isset($_POST[nome])){`, tem de verificar o recaptcha também
Answer: No seu código só há a verificação do nome, o que é uma falha:
if (isset($_POST[nome])){

Sua verificação deverá seguir dessa forma:
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):

Após verificar se existe a informação do recaptcha preenchido deverá validar o json recebido. Segue código de exemplo disponível no site CodexWorld (adaptado), que ilustra bem como deve ser feita toda a validação:
<?php
if(isset($_POST['submit']) && !empty($_POST['submit']))
{
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
    {
        //your site secret key
        $secret = '9LuDh9kyetYYYYdTXXXXXXXXXXXXXXXXX';
        //get verify response data
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
        if($responseData->success)
        {
            //SEU CODIGO AQUI
        } else {
            //ERRO: Robot verification failed, please try again.
        }
    } else {
        //ERRO: Please click on the reCAPTCHA box.
    }
}
?>

Comment: Ainda continuo nao conseguindo...
Comment: Por favor dê detalhes do que está a ocorrer, não tenho como ajudar sem saber o problema.
Comment: Fernando, o código não funcionou...
Teria como fazer um pra mim com meu código ?

reCaptcha Google


Is there a name for this pattern of piano chord progressions? (Clementi Op. 36 No. 5 & 6)

Question: I noticed in Clementi Op. 36 No. 5 and No. 6 there are these very similar and peculiar chord progressions (see image). Do those three chords often go together like that? Or is it more a Clementi style? Is there a name to refer to it? Anything special about it? Any comments welcome.
Answer: As I understand your question, no, there isn't a specific name for the pattern you've identified.
However, it is quite common, particularly in the classical era, and there are names for components of it.
1. I - IV - V - I
This is a very standard chord progression. It can have a variety of names depending on context, but here, being in the middle of the phrase, it's just noteworthy in and of itself and doesn't have a particular name. If you say to someone, "note the I-IV-V-I progression here", you will be understood.
Consider the first Clementi excerpt, interpreting it in the key of D major. The overarching harmony of measure 17 is D major, the I harmony. The first half of measure 18 is G major, the IV harmony; and the latter half of the measure is the A major, the V harmony.
Not shown is measure 19, which returns to D major.
Note that the A major portion of measure 18 includes D as the lowest pitch. That brings us to the next point.
2. Pedal Tone
A pedal tone is a pitch — often the lowest, but not necessarily — that remains constant while the harmony changes.
In bottom-most D, A, and D, respectively, in the three musical segments can be interpreted as pedal tones.
3. Changing tones, or Double neighbor
As a preface: strictly speaking, the terms don't apply here. But the idea is worth knowing both how it comes up and why it doesn't apply.
Changing tones occur when a primary note is "surrounded" by its upper and lower neighbors. For example, in the third Clementi excerpt, we have the melodic figure F# G E F#. Taking F# as the "primary note", it is interrupted by its upper neighbor, then its lower neighbor, before returning to F# again.
The reason it doesn't (strictly) apply here is that changing tones are, by definition, non-chord tones. Since the chords themselves are changing, this particular progression of pitches doesn't fit the definition. Nevertheless, the effect is similar at the level of the individual voice.
Changing tones are also discussed in

What is the harmony of this bar from Chopin's Minute waltz?
Csus4, Csus2, C is there a name?
Comment: @GrandAdagio earlier in the post I wrote, "Consider the first Clementi excerpt, interpreting it in the key of D major". That means that I did the analysis as though that part of the piece was in D major rather than G major.
Comment: @GrandAdagio Also, the chord you refer to as "the d-e chord" is not a d-e chord. Remembering that one has to consider the melody in determining the chord, it's an A major chord, and the D is not part of the chord – it's a "pedal tone", explained in section 2.
Comment: Thank, very interesting, esp. about the double neighbor. Sorry to ask a very ignorant question re "The first half of measure 18 is G major, the IV harmony; and the latter half of the measure is the A major, the V harmony." Why is the D G chord called "IV harmony" in G major? I thought IV chord should be built on the 4th key of G major, which would be C? Similarly, why is D E chord called 'the V harmony" in A major? The 5th key in A major is E, not D, though? (Hopefully this will help me start to learn some chord theory, which I found confusing.)
Comment: Thanks for the explanations. All what I can find about chord theory define the chords I, II,... as triads--e.g. in A major, the "IV" chord is D-F#-A. It confuses me when other variations could also be called the "IV" chord, sometimes it's a double note, or a slightly different triad containing some of the D, F#, A notes.


need path of an image created using an image style

Question: <?php
  $node=node_load(3);
  $theme_img = file_create_url($node->field_theme_image[$node->language][0]['uri']);  //origional image path
  print $theme_img;
?>

I am trying to load an image in "page--front.tpl.php", which was created from a content of node value 3.
Using above code, I am able to get origional image url. But I need path of image created using image style (home_theme)
Comment: http://drupal.stackexchange.com/questions/42061/render-or-print-image-in-a-drupal-7-node-tpl?rq=1 should give you some pointers
Answer: You can use image_style_url($style_name, $path)
Example:
$img_url = $node->field_image['und'][0]['uri'];
<img src="<?php print image_style_url("thumbnail", $img_url); ?>" />

Where you will be replacing thumbnail with the image style name you have in place


Regularization of a Matrix Using a Diagonal Matrix

Question: For a $n\times n$ matrix $A$ it is well known that $A + \lambda I$ for suffiecientely large $\lambda >0$ makes $A$ positive definite. The proof is straightforward by looking at the characteristic polynomial. I wonder what happens if we look at a diagonal matrix $\Lambda$ with possibly distinct diagonal elements? Is the  conclusion still valid that $A + \Lambda$ becomes positive definite for large enough $\Lambda$?
Background: I have implemented a code that performs regularization using the former approach. By experimental studies I found that using different values for regularization improves my results. So I was wonderung whether this also backed by theory.
Comment: What exactly do you mean by "large enough $\Lambda$"? It makes sense for a number to be large, but what do you mean when you say that the diagonal matrix is large?  Also: for your definition of positive definite, are positive definite matrices necessarily symmetric?
Comment: I understand "large" and "small" for square (symmetric) matrices in terms of Loewner ordering, i.e. $X>Y$ iff $X - Y$ is positive definite. In my case $A$ is symmetric, so yes.
Comment: Well if we have $\Lambda > \lambda I$ (for large enough $\lambda$), then your statement will be true
Comment: "For a $n\times n$ matrix $A$ it is well known that $A + \lambda I$ for suffiecientely large $\lambda >0$ makes $A$ positive definite. *The proof is straightforward by looking at the characteristic polynomial."*  This can't be right.  For an arbitrary n x n matrix, just looking at eigenvalues (or equivalently char poly) is not sufficient to ensure being positive definite.
Comment: @user8675309 not related; but why? the char poly of $A + \lambda I$ becomes $\chi(\xi - \lambda)$ ($\xi$ = eigenvalue of $A$). So all eigenvalues are shiftet to the right. Now just take $\lambda$ large enough to make it positive?
Answer: By definition $A + \lambda I$ is positive definite if, for every vector
$\vec x \ne 0,  \tag 1$
we have
$\vec x^\bot(A + \lambda I) \vec x > 0; \tag{1.5}$
since
$\vec x^\bot(A + \lambda I) \vec x= \vec x^\bot A \vec x + \vec x^\bot (\lambda \vec x) = \vec x^\bot A \vec x + \lambda \vec x^T \vec x, \tag 2$
clearly (1.5) binds for $\lambda > 0$ sufficiently large, since
$\exists M > 0, \; \vert \vec x^\bot A \vec x \vert < M \vec x^\bot \vec x; \tag 3$
we need only choose
$\lambda > M. \tag 4$
If now
$\Lambda = \text{diag}(\lambda_1, \lambda_2, \ldots, \lambda_n), \tag 5$
then
$\vec x^\bot (A + \Lambda) \vec x = \vec x^\bot A \vec x + \vec x^\bot \Lambda \vec x; \tag 6$
with
$\vec x = (x_1, x_2, \ldots, x_n)^\bot, \tag 7$
we have
$\Lambda \vec x = (\lambda_1 x_1, \lambda_2 x_2, \ldots, \lambda_n x_n)^\bot, \tag 8$
whence
$\vec x^\bot \Lambda \vec x = \displaystyle \sum_1^n \lambda_i x_i^2; \tag 9$
choosing each $\lambda_i > \lambda$ yields
$\vec x^\bot \Lambda \vec x = \displaystyle \sum_1^n \lambda_i x_i^2 > \lambda \sum_1^n x_i^2 = \lambda \vec x^\bot \vec x, \tag{10}$
from which in light of (1.5) shows that $M + \Lambda$ is positive definite.
Answer: The conclusion is still correct, as
\begin{align*}
\Lambda&=\text{diag}\left(\lambda_{1},\lambda_{2},\dots,\lambda_{n}\right)\\
&=\lambda_{\text{min}}I+\Xi\\
\Xi&=\text{diag}\left(\lambda_{1}-\lambda_{\text{min}},
\lambda_{2}-\lambda_{\text{min}},\dots,\lambda_{n}-\lambda_{\text{min}}\right)\\
\end{align*}
Here $\lambda_{\text{min}}=\min_{1\leq j\leq n}\lambda_{j}$. For large enough $\lambda_{\text{min}}$, we have that $A+\lambda_{\text{min}}I$ is positive definite, that is for any nonzero vector $u$, we have
\begin{align*}
u^{\top}\left(A+\lambda_{\text{min}}I\right)u>0
\end{align*}
If $u$ is nonzero then
\begin{align*}
u^{\top}\Xi u&=\sum_{j}u_{j}^{2}\left(\lambda_{j}-\lambda_{\text{min}}\right)\geq 0
\end{align*}
using this we have for every nonzero vector $u$
\begin{align*}
u^{\top}\left(A+\Lambda\right)u&=u^{\top}\left(A+\lambda_{\text{min}}I+\Xi\right)u>0
\end{align*}
thus $A+\Lambda$ is guaranteed to be positive definite, provided that the minimum entry of $\Lambda$ is sufficiently large.
Comment: wonderful! very neat proof. Thank you


RESTAPI in AngularJS - Does calling a GET Route always cause a new connection to be established?

Question: I would like to know if you call several GET Routes in AngularJS via a RESTAPI, if for each GET a new connection is established or if it's just one connection with several "underconnections" (Threads)
Answer: Yes every Ajax call opens a new connection. A browser can't just do multiple threads under one connection for Ajax purposes because multiple connections can come from different sources. But now with HTTP/2 your initial connection has the potential to come along one pipe. You can potentially open a websocket and funnel traffic down a single pipe but that isn't Ajax.


Can a tennis ball bounce multiple times and still be returned?

Question:

At 0:48, Djokovic intentionally waits for the ball to bounce twice and returns it to score a point. Can a tennis ball bounce multiple times and still be returned like this?
Comment: The ball hits the net and bounces once, not twice, before he strikes it.
Comment: There are exactly two changes to the ball's otherwise smooth path. If one is the net, the other must be a single bounce. Without any evidence to suggest the judges perfectly and entirely ignored one of the two fundamental rules for tennis play, I'm not sure what else can be expected here, except for "it didn't bounce twice, your depth perception is broken by the camera".
Comment: @Nij It seems to hit the net, but after that it looks a clear enough double bounce to me.
Comment: Note how the commentator says "Nicely dealt with by Djokovic", implying he's had to *deal with* something - namely, the flight of the ball being altered by contact with the net...
Answer: This is an optical illusion. At 0:50 in the video, the ball makes first contact with the net, not the ground. However, the ball hits the net very close to the center of the net, where there is a reinforcing post. As a result, the net doesn't vibrate at all. This lack of vibration makes it look like the ball hits the ground beyond the net. In reality, it hit the net.
One way to tell that the ball actually hit the net first is to notice that the ball has lost most of its speed after that contact. If the ball had actually hit the ground, it would have bounced much more energetically. Because it hit the net first, it bounced off very slowly.
After the ball hit the net, Djokovic correctly let it hit the ground once, before hitting the ball himself.


Loop of a list in python

Question: I want to define a function, short_pnl which takes two parameters:

positions (list) of strike prices for each future contract
mtm (list) of the current market value of each asset
To simplify the exercise, I will assume that positions and mtm lists have the same length and that the order is identical (first element in positions can be compared to the first element in mtm, etc.). I will also assume that all the futures in the portfolio are not yet up to maturity.

This function should compute and return the P&L (net income) of the portfolio.
Example:
I hold a porfolio of 3 future contracts on 3 different underlying assets:
Future A (SHORT) with a strike price of 100
Future B (SHORT) with a strike price of 140
Future C (SHORT) with a strike price of 200
Tonight, the market closes and the following market prices are spotted:
A closes at 110
B closes at 120
C closes at 180
The P&L portfolio can be computed like this: (100 - 110) + (140 - 120) + (200 - 180) = 30
My question is, how can i do this? I tried to write a piece of code in python but doesn't seem to work
positions=[100, 140, 200]
mtm=[110, 120, 180]
for i in range(0,3):
    short_pnl=positions[i]-mtm[i]
    print(short_pnl)

Furthermor, I have to make true this test:
import unittest
from financials import forward_price, short_pnl
class TestFinancials(unittest.TestCase):
    def test_forward_price_no_interest_rate(self):
        self.assertEqual(forward_price(100, 0, 1), 100)
        self.assertEqual(forward_price(100, 0, 2), 100)
        self.assertEqual(forward_price(100, 0, 3), 100)
        self.assertEqual(forward_price(100, 0, 4), 100)
        self.assertEqual(forward_price(100, 0, 5), 100)

Thank you!
Comment: I guess += instead of = on line 4 should work
Comment: plus you have syntax error in ```short_pnl=positions[i])-(mtm[i])```, it should be ```short_pnl=positions[i]-(mtm[i])```, also you can remove the parantheses from mtm
Comment: 1. Init short_pnl = 0 before loop, 2), 2. Don't hardcode 3, use `for i in range(len(positions))`, and 3) use `short_pnl+=positions[i]-(mtm[i])`
Answer: Using coding changes in comments we have:
positions=[100, 140, 200]
mtm=[110, 120, 180]
short_pnl = 0
for i in range(len(positions)):
    short_pnl+=positions[i]-(mtm[i])
    print(short_pnl)

But, this can written more preferably using zip as:
short_pnl = 0
for p, m in zip(positions, mtm):
    short_pnl += p - m
    print(short_pnl)

Or if all you care about is the final result use:
print(sum(p-m for p, m in zip(positions, mtm)))  # Output: 30

Comment: I have to make True this test:
import unittest
from financials import forward_price, short_pnl

class TestFinancials(unittest.TestCase):
    def test_forward_price_no_interest_rate(self):
        self.assertEqual(forward_price(100, 0, 1), 100)
        self.assertEqual(forward_price(100, 0, 2), 100)
        self.assertEqual(forward_price(100, 0, 3), 100)
        self.assertEqual(forward_price(100, 0, 4), 100)
        self.assertEqual(forward_price(100, 0, 5), 100)
Comment: @FrankPlatania--This seem like a different question. Also, you don't provide any information on the function `forward_price`.  What are the arguments? Is the function suppose to implement [Forward Price Definition](https://www.investopedia.com/terms/f/forwardprice.asp#:~:text=Forward%20price%20is%20the%20predetermined,predetermined%20date%20in%20the%20future.)

Loop of a list in python


Is there a way to remove unknown event listeners from objects?

Question: I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.
public function registerButtonCallback(function:Function):void
{
  clearButtonCallback();

  button.addEventListener(MouseEvent.CLICK, function, false, 0, true);
}

public function clearButtonCallback():void
{
  if (button.hasEventListener(MouseEvent.CLICK) == true)
  {
    // do something to remove that listener
  }
}

I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice.
Suggestions?
Answer: I am presuming that you want only one callback function at any given time.  If that's teh case then why not have a single callback function associated with the click event on the button which itself called a function and have that function be settable...
<mx:Button click="doCallback()" .../>

public var onClickFunction:Function = null;
private function doCallback():void
{
    if (onClickFunction != null)
    {
        onClickFunction(); // optionally you can pass some parameters in here if you match the signature of your callback
    }
}

A consumer of your control which houses your button would set the onClickFunction with the appropriate function.  In fact you could set it as often as you liked.
If you wanted to go one step further you could subclass the AS3 Button class and wrap all of this inside it.
Comment: Gotcha. You know, I think I started to do that and decided against it for some reason which I don't remember. Either way, your presumption is correct and it's a good way to do what I've intended. Thanks.
Comment: Great, glad I could help.  If you mark this as the answer I'll get a few rep points too :-)
Answer: No.  You need to hold a reference to the listener in order to remove it.  Unless you store a reference to the listener function in advance, there is no documented public method available to retrieve such a reference from an EventDispatcher.
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
dispatchEvent(event:Event):Boolean
hasEventListener(type:String):Boolean
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
willTrigger(type:String):Boolean

As you can see, there are two methods to tell you whether a type of event has a listener registered or one of its parents has a listener registered, but none of those methods actually return a list of registered listeners.
Now please go harass Adobe for writing such a useless API.  Basically, they give you the ability to know "whether" the event flow has changed, but they give you no way of doing anything with that information!
Answer: Store the listener as a prop. When another event is added, check to see if the listener exists, and if it does, call removeEventListener.
Alternatively, override the addEventListener method of you button. When addEventListener is called, store the closure before adding it to the event in a Dictionary object. When addEventListener is called again, remove it:

var listeners:Dictionary = new Dictionary();
override public function addEventListener( type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = false) : void {
  if( listeners[ type ] ) {

     if( listeners[ type ] [ useCapture ] {

        //snip... etc: check for existence of the listener

        removeEventListener( type, listeners[ type ] [ useCapture ], useCapture );

        listeners[ type ] [ useCapture ] = null;

        //clean up: if no listeners of this type exist, remove the dictionary key for the type, etc...

     }

  }

  listeners[ type ] [ useCapture ] = listener;

  super.addEventListener( type, listener, useCapture, priority, useWeakReference );

};

Comment: But they do offer ways to make the unknown event listeners known which is another way to approach the problem.
Comment: Neither of those options do what the question is asking, which is to retrieve an UNKOWN event listener from an existing EventDispatcher object.  These methods are just storing a KNOWN listener before it's added to the object.  If the listener is not known and stored before it's added to the object, then there is no way to retrieve it later.
Answer: I written a subclass called EventCurb for that purpose, see my blog here or paste below.
package
{
   import flash.events.EventDispatcher;
   import flash.utils.Dictionary;
   /**
    * ...
    * @author Thomas James Thorstensson
    * @version 1.0.1
    */
   public class EventCurb extends EventDispatcher
   {
      private static var instance:EventCurb= new EventCurb();
      private var objDict:Dictionary = new Dictionary(true);
      private var _listener:Function;
      private var objArr:Array;
      private var obj:Object;

      public function EventCurb() {
         if( instance ) throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" );
      }

      public static function getInstance():EventCurb {
         return instance;
      }

      override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
      {
         super.addEventListener(type, listener, useCapture, priority, useWeakReference);
      }

      override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
      {
         super.removeEventListener(type, listener, useCapture);
      }

      public function addListener(o:EventDispatcher, type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
         // the object as key for an array of its event types
         if (objDict[o] == null)  objArr = objDict[o] = [];
         for (var i:int = 0; i <  objArr.length; i++) {
            if ( objArr[i].type == type)
            trace ("_______object already has this listener not adding!")
            return
         }
         obj = { type:type, listener:listener }
         objArr.push(obj);
         o.addEventListener(type, listener, useCapture, priority, useWeakReference);
      }

      public function removeListener(o:EventDispatcher, type:String, listener:Function, useCapture:Boolean = false):void {
         // if the object has listeners (ie exists in dictionary)
         if (objDict[o] as Array !== null) {
            var tmpArr:Array = [];
            tmpArr = objDict[o] as Array;
            for (var i:int = 0; i < tmpArr.length; i++) {
               if (tmpArr[i].type == type) objArr.splice(i);
            }

            o.removeEventListener(type, listener, useCapture);
            if (tmpArr.length == 0) {
               delete objDict[o]
            }
         }else {
            trace("_______object has no listeners");
         }
      }

      /**
       * If object has listeners, returns an Array which can be accessed
       * as array[index].type,array[index].listeners
       * @param   o
       * @return Array
       */
      public function getListeners(o:EventDispatcher):Array{
         if (objDict[o] as Array !== null) {
            var tmpArr:Array = [];
            tmpArr = objDict[o] as Array;
            // forget trying to trace out the function name we use the function literal...
            for (var i:int = 0; i < tmpArr.length; i++) {
               trace("_______object " + o + " has event types: " + tmpArr[i].type +" with listener: " + tmpArr[i].listener);
            }
            return tmpArr

         }else {
            trace("_______object has no listeners");
            return null
         }

      }

      public function removeAllListeners(o:EventDispatcher, cap:Boolean = false):void {
         if (objDict[o] as Array !== null) {
            var tmpArr:Array = [];
            tmpArr = objDict[o] as Array;
            for (var i:int = 0; i < tmpArr.length; i++) {
               o.removeEventListener(tmpArr[i].type, tmpArr[i].listener, cap);
            }
            for (var p:int = 0; p < tmpArr.length; p++) {
               objArr.splice(p);
            }

            if (tmpArr.length == 0) {
               delete objDict[o]
            }
         }else {
            trace("_______object has no listeners");
         }
      }
   }
}

Answer: Something I like to do is use a dynamic Global class and add a quick reference to the listener function inline. This is presuming you like to have the listener function in the addEventListener method like I do. This way, you can use removeEventListener inside the addEventListener :)
Try this out:
package {

import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;

[SWF(width="750", height="400", backgroundColor="0xcdcdcd")]
public class TestProject extends Sprite
{
    public function TestProject()
    {
        addEventListener(Event.ADDED_TO_STAGE, Global['addStageEvent'] = function():void {
            var i:uint = 0;
            //How about an eventlistener inside an eventListener?
            addEventListener(Event.ENTER_FRAME, Global['someEvent'] = function():void {
                //Let's make some text fields
                var t:TextField = new TextField();
                    t.text = String(i);
                    t.x = stage.stageWidth*Math.random();
                    t.y = stage.stageHeight*Math.random();
                addChild(t);
                i++;
                trace(i);
                //How many text fields to we want?
                if(i >= 50) {
                    //Time to stop making textFields
                    removeEventListener(Event.ENTER_FRAME, Global['someEvent']);
                    //make sure we don't have any event listeners
                    trace("hasEventListener(Event.ENTER_FRAME) = "+hasEventListener(Event.ENTER_FRAME));
                }
            });

            //Get rid of the listener
            removeEventListener(Event.ADDED_TO_STAGE, Global['addStageEvent']);
            trace('hasEventListener(Event.ADDED_TO_STAGE) = '+hasEventListener(Event.ADDED_TO_STAGE));

        });
    }

}

}
// looky here! This is the important bit
dynamic class Global {}
The secret is the dynamic class Global. With that you can dynamically add properties in at runtime.
Answer: private function callFunction(function:Function):void
{
     checkObject();
     obj.addEventListener(MouseEvent.CLICK,function);
}

private function checkObject():void
{
    if(obj.hasEventListener(MouseEvent.CLICK))
   {
      //here remove that objects
   }
}

Answer: The following doesn't address the fundamental issue of removing unknown event listeners, but if what you need is disabling all mouse related events, including unknown ones, just use:
mouseEnabled=false on your event target.
More good stuff here:
http://www.thoughtprocessinteractive.com/blog/the-power-and-genius-of-mousechildren-and-mouseenabled
Answer: K2xL EventManager Class
http://k2xl.com/wordpress/2008/07/02/as3-eventmanager-class-removealllisteners/


XSLT 2.0: filter duplicates

Question: I have this line in a template:
<xsl:for-each select="//img/@src[not(@ = preceding::@)]">
to generate a list of filenames of pictures :

Now I need to filter duplicate pictures from the list of pictures.
<xsl:for-each select="//img[not(node() = preceding::img)]">
does not work because it works on the whole image node.
How can I change the line to work on src attributes?
So the question is about the last part of the line in question.
Answer: You could just use distinct-values(//img/@src), e.g.
<xsl:for-each select="distinct-values(//img/@src)">

<xsl:value-of select="."/>

<xsl:for-each>

Alternatively you can use for-each-group
<xsl:for-each-group select="//img" group-by="@src">

<xsl:value-of select="@src"/>

<xsl:for-each-group>

Comment: Thank you. Very helpful. and insde that loop, hou would I use generate-id() on the parent node img? (in your first suggestion)
Comment: @Erik you can't, because `distinct-values` gives you the distinct _values_, not the nodes they came from (i.e. you're for-eaching over a sequence of atomic values, not a sequence of nodes).
Comment: I see. Of course. Then I'll use position() and a prefix to generate id's. Thanks again.
Comment: @Erik with the `for-each-group` version you _can_ use `generate-id()` because in that case `.` is the first `img` element in document order that has the current `@src` value (and `current-group()` will give you all the members of the group if you need them).

XSLT 2.0: filter duplicates


Converting Cifar10 dataset to RecordIO format for Amazon SageMaker

Question: I have downloaded cifar-10 dataset and need to convert it to RecordIO format. If you unzip the downloaded cifar-10-python.tar.gz dataset, you will see below
cifar-10-batches-py/
cifar-10-batches-py/data_batch_4
cifar-10-batches-py/readme.html
cifar-10-batches-py/test_batch
cifar-10-batches-py/data_batch_3
cifar-10-batches-py/batches.meta
cifar-10-batches-py/data_batch_2
cifar-10-batches-py/data_batch_5
cifar-10-batches-py/data_batch_1

Now, I want to separate out the data_batch_*.bin to train set and test_batch.bin to test set and convert to recordIO format.
Following this tutorial link but not sure how im2rec  actually works to make it happen.
Please suggest.
Answer: This is how you use im2rec: https://mxnet.incubator.apache.org/versions/master/faq/recordio.html
Or you could download CIFAR-10 in RecordIO format directly:
wget http://data.mxnet.io/data/cifar10/cifar10_val.rec
wget http://data.mxnet.io/data/cifar10/cifar10_train.rec


Probability of asymmetric random walk returning to the origin

Question: Consider the random walk $S_n$ given by
$
S_{n+1} =  \left\{
  \begin{array}{l}
    S_n+2 & \text{with probability $p$}\\
    S_n - 1 & \text{with probability $1-p$}
  \end{array}
\right.
\
$
Assume that $S_0 = n >0 $. What is the probability of eventually reaching the the point $0$?
Seems that the probability for this must be less than one; since it is not symmetric, it is not guaranteed to reach the origin if $p>0.5$. It also seems like the positive starting value not being at the origin matters too, but I'm not sure how to compute the probability of eventually reaching the origin.
Comment: You may want to have a look at this http://math.stackexchange.com/a/65050/233398 -- about generating functions.
Comment: There is also the possibility to solve this using martingale theory. If you are interested, just ping me.
Comment: @saz, I would be interested in the alternate solution!
Answer: For any $n \ge 0$, let
$$f_n = {\bf Pr}\big[ S_0 =n \land \exists t > 0, S_t = 0 \big]$$
be the probability for a random walk start at location $n$ returns to origin in some finite time $t$.
Let $q = 1-p$ and $\displaystyle\;\mu = \frac{q}{p}\;$. It is easy to see $f_n$ satisfies a recurrence relation
$$f_n = \begin{cases}
1, & n = 0,\\
p f_{n+2} + q f_{n-1}, & n > 0
\end{cases}\tag{*1}$$
The corresponding characteristic equation
$$\begin{align}
p \lambda^2 + q\lambda^{-1} - 1 = 0
&\iff p(\lambda^2 - 1) - q(1-\lambda^{-1}) = 0\\
&\iff (\lambda^2 + \lambda - \mu)(\lambda - 1) = 0
\end{align}
\tag{*2}
$$
has three roots,
$$1,\quad -\frac{1+\sqrt{1+4\mu}}{2}\quad\text{ and }\quad\frac{\sqrt{1+4\mu}-1}{2}$$
This implies
$$f_n = A + B \left( -\frac{1+\sqrt{1+4\mu}}{2} \right)^n + C \left(\frac{\sqrt{1+4\mu}-1}{2}\right)^n$$
for some suitably chosen constants $A, B, C$.
Notice among the three roots, the $2^{nd}$ root is largest in magnitude and $< -1$. If $B \ne 0$, then $f_n$ will be negative for some sufficiently large $n$. This contradicts with the nature of $f_n$ being the probability of some event. This means
$B = 0$. What happens to $A$ and $C$ depends on $\mu$.

If $\mu < 2$, the average drift of the random walk $r = 2p - q = p(2-\mu) > 0$.
For $t$ not too small, we can approximate $S_t$ by a normal distribution with mean
$r t + n$ and standard derivation $\sigma = \sqrt{4p^2 + q - r^2} = 3\sqrt{pq}$. Within $K$ sigma, we have
$$S_t > r t + n - K\sigma\sqrt{t} = r\left(\sqrt{t} - \frac{K\sigma}{2r}\right)^2 + n - \frac{K^2\sigma^2}{4r}$$
When $\displaystyle\;n > \frac{K^2\sigma^2}{4r}\;$, we expect the "return to origin" becomes a $K$ sigma event. This suggests$\color{blue}{^{[1]}}$
$$\lim_{n\to\infty} f_n = 0 \quad\implies\quad A = 0$$
Combine with the constraint $f_0 = 1$, we find $C = 1$ and
$$f_n = \left(\frac{\sqrt{1+4\mu}-1}{2}\right)^n$$
If $\mu > 2$, the $3^{rd}$ root $\displaystyle\;\frac{\sqrt{1+4\mu} - 1}{2} > 1$.
If $C \ne 0$, then $f_n$ will become unbounded for sufficiently large $n$. One again, this contradict with the nature of $f_n$ begin the probability of some event.
This leads to $C = 0, A = 1$ and hence $f_n = 1$.
If $\mu = 2$, the characteristic equation $(*2)$ has a double root at $\lambda = 1$.
The general solution for $(*1)$ now takes the form
$$f_n = A + B \left( -\frac{1+\sqrt{1+4\mu}}{2} \right)^n + C'n$$
One again, it is easy to see $C' = 0, A = 1$ and hence $f_n = 1$.

To summarize:
$$f_n = \begin{cases}
\displaystyle\;\left(\frac{\sqrt{1+4\mu}-1}{2}\right)^n, & \mu < 2\\
1, & \mu \ge 2
\end{cases}$$
Notes

$\color{blue}{[1]}$ This is a hand waving argument, feel free to justify this rigorously.
Comment: This is very helpful. Are you sure $B=0$? You say the second root is <-1 but that doesn't seem to account for the fact that it's divided by 2.
Comment: @EdJar Remember $\mu > 0 \implies \sqrt{1+4\mu} > 1 \implies \frac{1+\sqrt{1+4\mu}}{2} > 1$.
Comment: @achillehui Your answer is really helpful. I have some difficulty in understanding the argument that $\lim f_n = 0$ when $\mu <2$. Is there any chance to add some more details?